diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1dfe31e --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.bundle/ +log/*.log +pkg/ +test/dummy/db/*.sqlite3 +test/dummy/log/*.log +test/dummy/tmp/ +test/dummy/.sass-cache diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..c68498b --- /dev/null +++ b/Gemfile @@ -0,0 +1,17 @@ +source "http://rubygems.org" + +# Declare your gem's dependencies in chaplin-on-rails.gemspec. +# Bundler will treat runtime dependencies like base dependencies, and +# development dependencies will be added by default to the :development group. +gemspec + +# jquery-rails is used by the dummy application +gem "jquery-rails" + +# Declare any dependencies that are still in development here instead of in +# your gemspec. These might include edge Rails or gems from your path or +# Git. Remember to move these dependencies to your gemspec before releasing +# your gem to rubygems.org. + +# To use debugger +# gem 'debugger' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..8ae2912 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,115 @@ +PATH + remote: . + specs: + chaplin-on-rails (0.0.1) + coffee-rails + rails (>= 3.1) + requirejs-rails + +GEM + remote: http://rubygems.org/ + specs: + actionmailer (3.2.11) + actionpack (= 3.2.11) + mail (~> 2.4.4) + actionpack (3.2.11) + activemodel (= 3.2.11) + activesupport (= 3.2.11) + builder (~> 3.0.0) + erubis (~> 2.7.0) + journey (~> 1.0.4) + rack (~> 1.4.0) + rack-cache (~> 1.2) + rack-test (~> 0.6.1) + sprockets (~> 2.2.1) + activemodel (3.2.11) + activesupport (= 3.2.11) + builder (~> 3.0.0) + activerecord (3.2.11) + activemodel (= 3.2.11) + activesupport (= 3.2.11) + arel (~> 3.0.2) + tzinfo (~> 0.3.29) + activeresource (3.2.11) + activemodel (= 3.2.11) + activesupport (= 3.2.11) + activesupport (3.2.11) + i18n (~> 0.6) + multi_json (~> 1.0) + ansi (1.4.3) + arel (3.0.2) + builder (3.0.4) + coffee-rails (3.2.2) + coffee-script (>= 2.2.0) + railties (~> 3.2.0) + coffee-script (2.2.0) + coffee-script-source + execjs + coffee-script-source (1.4.0) + erubis (2.7.0) + execjs (1.4.0) + multi_json (~> 1.0) + hike (1.2.1) + i18n (0.6.1) + journey (1.0.4) + jquery-rails (2.1.4) + railties (>= 3.0, < 5.0) + thor (>= 0.14, < 2.0) + json (1.7.6) + mail (2.4.4) + i18n (>= 0.4.0) + mime-types (~> 1.16) + treetop (~> 1.4.8) + mime-types (1.19) + multi_json (1.5.0) + polyglot (0.3.3) + rack (1.4.4) + rack-cache (1.2) + rack (>= 0.4) + rack-ssl (1.3.2) + rack + rack-test (0.6.2) + rack (>= 1.0) + rails (3.2.11) + actionmailer (= 3.2.11) + actionpack (= 3.2.11) + activerecord (= 3.2.11) + activeresource (= 3.2.11) + activesupport (= 3.2.11) + bundler (~> 1.0) + railties (= 3.2.11) + railties (3.2.11) + actionpack (= 3.2.11) + activesupport (= 3.2.11) + rack-ssl (~> 1.3.2) + rake (>= 0.8.7) + rdoc (~> 3.4) + thor (>= 0.14.6, < 2.0) + rake (10.0.3) + rdoc (3.12) + json (~> 1.4) + requirejs-rails (0.9.1) + railties (>= 3.1.1, < 3.3) + sprockets (2.2.2) + hike (~> 1.2) + multi_json (~> 1.0) + rack (~> 1.0) + tilt (~> 1.1, != 1.3.0) + sqlite3 (1.3.7) + thor (0.16.0) + tilt (1.3.3) + treetop (1.4.12) + polyglot + polyglot (>= 0.3.1) + turn (0.9.6) + ansi + tzinfo (0.3.35) + +PLATFORMS + ruby + +DEPENDENCIES + chaplin-on-rails! + jquery-rails + sqlite3 + turn diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100644 index 0000000..26afef2 --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright 2013 aenaku + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..05d417d --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# ChaplinOnRails + +Gem for using [Chaplin.js](https://github.com/chaplinjs/chaplin) with Rails asset pipeline, based on +[chaplin-rails](https://github.com/chaplinjs/chaplin-rails) boilerplate project. + +Since Chaplin requires module system this gem has +[requirejs-rails](https://github.com/jwhitley/requirejs-rails) gem +in dependecy. Those, you're forced to use `requirejs` for your project :) + +Gem already comes with `underscore.js` and `backbone.js`. + +## Installation + +Add this line to your application's Gemfile: + + gem 'chaplin-on-rails', git: 'git://github.com/eicaa/chaplin-on-rails.git' + +And then execute: + + $ bundle + +## Usage + +Run + + rails g chaplin:install + +It should create basic application structure with some basic files. +To learn more about this see +[chaplin-rails](https://github.com/chaplinjs/chaplin-rails). + +This gem generates new `application.js.coffee` for you, so you should +migrate your old `application.js` to `requirejs` config file and remove +`application.js` file. + +Also, there might be a problem with replacing `requirejs_include_tag`. +Just follow for generator's output instructions. + +## TODO + +1. Write tests for install generator. +2. Write generators for scaffold/resource/controller/model. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..17135a8 --- /dev/null +++ b/Rakefile @@ -0,0 +1,38 @@ +#!/usr/bin/env rake +begin + require 'bundler/setup' +rescue LoadError + puts 'You must `gem install bundler` and `bundle install` to run rake tasks' +end +begin + require 'rdoc/task' +rescue LoadError + require 'rdoc/rdoc' + require 'rake/rdoctask' + RDoc::Task = Rake::RDocTask +end + +RDoc::Task.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'ChaplinOnRails' + rdoc.options << '--line-numbers' + rdoc.rdoc_files.include('README.rdoc') + rdoc.rdoc_files.include('lib/**/*.rb') +end + + + + +Bundler::GemHelper.install_tasks + +require 'rake/testtask' + +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.libs << 'test' + t.pattern = 'test/**/*_test.rb' + t.verbose = false +end + + +task :default => :test diff --git a/chaplin-on-rails.gemspec b/chaplin-on-rails.gemspec new file mode 100644 index 0000000..eee808a --- /dev/null +++ b/chaplin-on-rails.gemspec @@ -0,0 +1,25 @@ +$:.push File.expand_path("../lib", __FILE__) + +# Maintain your gem's version: +require "chaplin-on-rails/version" + +# Describe your gem and declare its dependencies: +Gem::Specification.new do |s| + s.name = "chaplin-on-rails" + s.version = ChaplinOnRails::VERSION + s.authors = ["TODO: name"] + s.email = ["TODO: email"] + s.homepage = "TODO" + s.summary = "TODO: Summary of ChaplinOnRails." + s.description = "TODO: Description of ChaplinOnRails." + + s.files = Dir["{vendor,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] + s.test_files = Dir["test/**/*"] + + s.add_dependency 'rails', '>= 3.1' + s.add_dependency 'coffee-rails' + s.add_dependency 'requirejs-rails' + + s.add_development_dependency 'sqlite3' + s.add_development_dependency 'turn' +end diff --git a/lib/chaplin-on-rails.rb b/lib/chaplin-on-rails.rb new file mode 100644 index 0000000..bc56941 --- /dev/null +++ b/lib/chaplin-on-rails.rb @@ -0,0 +1,2 @@ +require "chaplin-on-rails/engine" +require "chaplin-on-rails/version" diff --git a/lib/chaplin-on-rails/engine.rb b/lib/chaplin-on-rails/engine.rb new file mode 100644 index 0000000..149aa4d --- /dev/null +++ b/lib/chaplin-on-rails/engine.rb @@ -0,0 +1,6 @@ +require 'requirejs-rails' + +module ChaplinOnRails + class Engine < Rails::Engine + end +end diff --git a/lib/chaplin-on-rails/version.rb b/lib/chaplin-on-rails/version.rb new file mode 100644 index 0000000..9cb5747 --- /dev/null +++ b/lib/chaplin-on-rails/version.rb @@ -0,0 +1,3 @@ +module ChaplinOnRails + VERSION = "0.7.0-pre" +end diff --git a/lib/generators/chaplin/helpers.rb b/lib/generators/chaplin/helpers.rb new file mode 100644 index 0000000..a462a29 --- /dev/null +++ b/lib/generators/chaplin/helpers.rb @@ -0,0 +1,94 @@ +module Chaplin + module Generators + module Helpers + + def asset_path + File.join('app', 'assets') + end + + def javascript_path + File.join(asset_path, 'javascripts') + end + + def model_path + File.join(javascript_path, "models") + end + + def view_path + File.join(javascript_path, "views") + end + + def controller_path + File.join(javascript_path, "controllers") + end + + def lib_path + File.join(javascript_path, "lib") + end + + def base_path(path) + File.join(path, 'base') + end + + def template_path + File.join(asset_path, "templates") + end + + def singular_file_name + "#{file_name.singularize}#{@ext}" + end + + def plural_file_name + "#{file_name.pluralize}#{@ext}" + end + + def router_file_name + "#{file_name.pluralize}_router#{@ext}" + end + + def view_file_name + "#{file_name.pluralize}_index#{@ext}" + end + + def model_namespace + [app_name, "Models", file_name.singularize.camelize].join(".") + end + + def collection_namespace + [app_name, "Collections", file_name.pluralize.camelize].join(".") + end + + def router_namespace + [app_name, "Routers", file_name.pluralize.camelize].join(".") + end + + def view_namespace + [app_name, "Views", "#{file_name.pluralize.camelize}Index"].join(".") + end + + def template_namespace + File.join(file_path.pluralize, "index") + end + + def app_name + rails_app_name.camelize + end + + def app_filename + rails_app_name.underscore + end + + def rails_app_name + Rails.application.class.name.split('::').first + end + + def layout_path + Dir['app/views/layouts/application*'].first + end + + def display(output, color = :green) + say(" - #{output}", color) + end + end + end +end diff --git a/lib/generators/chaplin/install/install_generator.rb b/lib/generators/chaplin/install/install_generator.rb new file mode 100644 index 0000000..9470d80 --- /dev/null +++ b/lib/generators/chaplin/install/install_generator.rb @@ -0,0 +1,68 @@ +require 'generators/chaplin/helpers' + +module Chaplin + module Generators + class InstallGenerator < Rails::Generators::Base + include Chaplin::Generators::Helpers + + source_root File.expand_path("../templates", __FILE__) + + desc "Generates a Chaplin.js skeleton directory structure and manifest" + + # TODO currently only coffee works + #class_option :javascript, + #type: :boolean, + #aliases: "-j", + #default: false, + #desc: "Generate JavaScript" + + def copy_app_boilerplate + # it should remove empty directories during 'destroy' command + %w(controllers lib models views).each do |dir_name| + empty_directory File.join(javascript_path, dir_name) + end + + # copy all /javascripts directory + directory 'javascripts', javascript_path + + # create empty 'assets/templates' directory + empty_directory template_path + end + + def generate_app_files + template "application.js.coffee", "#{javascript_path}/application.js.coffee" + template "app_template.js.coffee", "#{javascript_path}/#{app_filename}.js.coffee" + end + + def apply_requirejs + # copy config file + copy_file 'requirejs.yml', 'config/requirejs.yml' + + # check if we can find layout file + # TODO doesn't work during 'destroy' command + if layout_path + # inject requirejs tag + unless gsub_file(layout_path, /javascript_include_tag/, 'requirejs_include_tag') + display "Can't find a javascript_include_tag in '#{layout_path}'!" + display "You must add 'requirejs_include_tag' instead of 'javascript_include_tag'" + display "in your layout(s)." + end + else + display "Can't find a layout to inject requirejs tag!" + display "You must add 'requirejs_include_tag' instead of 'javascript_include_tag'" + display "in your layout(s)." + end + end + + + def post_install_messages + if File.exists?("#{javascript_path}/application.js") + display "You have 'application.js' file in your 'assets/' folder." + display "You should migrate all dependencies to the 'requirejs.yml' config file" + display "and remove 'application.js file." + end + end + + end + end +end diff --git a/lib/generators/chaplin/install/templates/app_template.js.coffee b/lib/generators/chaplin/install/templates/app_template.js.coffee new file mode 100644 index 0000000..173f330 --- /dev/null +++ b/lib/generators/chaplin/install/templates/app_template.js.coffee @@ -0,0 +1,65 @@ +define [ + 'chaplin' + 'views/layout' + 'routes' + # Require base controllers manually because + # they aren’t compiled individually + # 'controllers/my_controller' +], (Chaplin, Layout, routes) -> + 'use strict' + + # The application object + # Choose a meaningful name for your application + class <%= app_name %> extends Chaplin.Application + + # Set your application name here so the document title is set to + # “Controller title – Site title” (see Layout#adjustTitle) + title: '<%= rails_app_name %>' + + initialize: -> + super + + # Initialize core components + @initDispatcher() + @initLayout() + @initMediator() + + # Application-specific scaffold + @initControllers() + + # Register all routes and start routing + @initRouter routes + # You might pass Router/History options as the second parameter. + # Chaplin enables pushState per default and Backbone uses / as + # the root per default. You might change that in the options + # if necessary: + # @initRouter routes, pushState: false, root: '/subdir/' + + # Freeze the application instance to prevent further changes + Object.freeze? this + + # Override standard layout initializer + # ------------------------------------ + initLayout: -> + # Use an application-specific Layout class. Currently this adds + # no features to the standard Chaplin Layout, it’s an empty placeholder. + @layout = new Layout {@title} + + # Instantiate common controllers + # ------------------------------ + initControllers: -> + # These controllers are active during the whole application runtime. + # You don’t need to instantiate all controllers here, only special + # controllers which do not to respond to routes. They may govern models + # and views which are needed the whole time, for example header, footer + # or navigation views. + # e.g. new NavigationController() + + # Create additional mediator properties + # ------------------------------------- + initMediator: -> + # Create a user property + Chaplin.mediator.user = null + # Add additional application-specific properties and methods + # Seal the mediator + Chaplin.mediator.seal() diff --git a/lib/generators/chaplin/install/templates/application.js.coffee b/lib/generators/chaplin/install/templates/application.js.coffee new file mode 100644 index 0000000..764e4c0 --- /dev/null +++ b/lib/generators/chaplin/install/templates/application.js.coffee @@ -0,0 +1,13 @@ +# +# add '= require hamlcoffee' for hamlcoffee support +# +#= require_tree ../templates + +# Bootstrap the application +require [ + '<%= app_filename %>' +], (<%= app_name %>) -> + 'use strict' + + app = new <%= app_name %>() + app.initialize() diff --git a/lib/generators/chaplin/install/templates/javascripts/controllers/base/controller.js.coffee b/lib/generators/chaplin/install/templates/javascripts/controllers/base/controller.js.coffee new file mode 100644 index 0000000..df7c385 --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/controllers/base/controller.js.coffee @@ -0,0 +1,8 @@ +define [ + 'chaplin' +], (Chaplin) -> + 'use strict' + + class Controller extends Chaplin.Controller + + # Place your application-specific controller features here diff --git a/lib/generators/chaplin/install/templates/javascripts/lib/support.js.coffee b/lib/generators/chaplin/install/templates/javascripts/lib/support.js.coffee new file mode 100644 index 0000000..46de5eb --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/lib/support.js.coffee @@ -0,0 +1,19 @@ +define [ + 'underscore' + 'lib/utils' + 'chaplin' +], (_, utils, Chaplin) -> + + # Application-specific feature detection + # -------------------------------------- + + # Delegate to Chaplin’s support module + support = utils.beget Chaplin.support + + # Add additional application-specific properties and methods + + # _(support).extend + # someProperty: 'foo' + # someMethod: -> + + support diff --git a/lib/generators/chaplin/install/templates/javascripts/lib/utils.js.coffee b/lib/generators/chaplin/install/templates/javascripts/lib/utils.js.coffee new file mode 100644 index 0000000..14060b8 --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/lib/utils.js.coffee @@ -0,0 +1,18 @@ +define [ + 'underscore' + 'chaplin' +], (_, Chaplin) -> + + # Application-specific utilities + # ------------------------------ + + # Delegate to Chaplin’s utils module + utils = Chaplin.utils.beget Chaplin.utils + + # Add additional application-specific properties and methods + + # _(utils).extend + # someProperty: 'foo' + # someMethod: -> + + utils diff --git a/lib/generators/chaplin/install/templates/javascripts/lib/view_helper.js.coffee b/lib/generators/chaplin/install/templates/javascripts/lib/view_helper.js.coffee new file mode 100644 index 0000000..769b49c --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/lib/view_helper.js.coffee @@ -0,0 +1,16 @@ +define [ + 'chaplin' + 'lib/utils' +], (Handlebars, Chaplin, utils) -> + 'use strict' + + # View helpers (HAML Coffee in this case) + # --------------------------------------- + + HAML.globals = -> + { + #someProperty: 'foo' + #someMethod: -> + } + + null diff --git a/lib/generators/chaplin/install/templates/javascripts/models/base/collection.js.coffee b/lib/generators/chaplin/install/templates/javascripts/models/base/collection.js.coffee new file mode 100644 index 0000000..aecc8f1 --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/models/base/collection.js.coffee @@ -0,0 +1,9 @@ +define [ + 'chaplin' +], (Chaplin) -> + + class Collection extends Chaplin.Collection + # Mixin a synchronization state machine + # _(@prototype).extend Chaplin.SyncMachine + + # Place your application-specific collection features here diff --git a/lib/generators/chaplin/install/templates/javascripts/models/base/model.js.coffee b/lib/generators/chaplin/install/templates/javascripts/models/base/model.js.coffee new file mode 100644 index 0000000..4da85b1 --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/models/base/model.js.coffee @@ -0,0 +1,9 @@ +define [ + 'chaplin' +], (Chaplin) -> + + class Model extends Chaplin.Model + # Mixin a synchronization state machine + # _(@prototype).extend Chaplin.SyncMachine + + # Place your application-specific model features here diff --git a/lib/generators/chaplin/install/templates/javascripts/routes.js.coffee b/lib/generators/chaplin/install/templates/javascripts/routes.js.coffee new file mode 100644 index 0000000..7a6200f --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/routes.js.coffee @@ -0,0 +1,9 @@ +define -> + 'use strict' + + # The routes for the application. This module returns a function. + # `match` is match method of the Router + (match) -> + + #match '', 'pages#home' + diff --git a/lib/generators/chaplin/install/templates/javascripts/views/base/collection_view.coffee b/lib/generators/chaplin/install/templates/javascripts/views/base/collection_view.coffee new file mode 100644 index 0000000..045d48e --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/views/base/collection_view.coffee @@ -0,0 +1,11 @@ +define [ + 'chaplin', + 'views/base/view' +], (Chaplin, View) -> + 'use strict' + + class CollectionView extends Chaplin.CollectionView + + # This class doesn’t inherit from the application-specific View class, + # so we need to borrow the method from the View prototype: + getTemplateFunction: View::getTemplateFunction diff --git a/lib/generators/chaplin/install/templates/javascripts/views/base/view.coffee b/lib/generators/chaplin/install/templates/javascripts/views/base/view.coffee new file mode 100644 index 0000000..dcf72ec --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/views/base/view.coffee @@ -0,0 +1,15 @@ +define [ + 'chaplin' + 'lib/view_helper' # Just load the view helpers, no return value +], (Chaplin) -> + 'use strict' + + class View extends Chaplin.View + + # change this method according to your templating system + getTemplateFunction: -> + templateFunction = JST[@templateName] + if typeof @templateName is 'string' and typeof templateFunction isnt 'function' + throw new Error "View template #{@templateName} not found" + + templateFunction diff --git a/lib/generators/chaplin/install/templates/javascripts/views/layout.js.coffee b/lib/generators/chaplin/install/templates/javascripts/views/layout.js.coffee new file mode 100644 index 0000000..c38927c --- /dev/null +++ b/lib/generators/chaplin/install/templates/javascripts/views/layout.js.coffee @@ -0,0 +1,8 @@ +define [ + 'chaplin' +], (Chaplin) -> + 'use strict' + + class Layout extends Chaplin.Layout + + # Place your application-specific Layout features here diff --git a/lib/generators/chaplin/install/templates/requirejs.yml b/lib/generators/chaplin/install/templates/requirejs.yml new file mode 100644 index 0000000..0a9bfbc --- /dev/null +++ b/lib/generators/chaplin/install/templates/requirejs.yml @@ -0,0 +1,6 @@ +shim: + 'underscore': + exports: '_' + 'backbone': + deps: ['underscore', 'jquery'] + exports: 'Backbone' diff --git a/test/chaplin-on-rails_test.rb b/test/chaplin-on-rails_test.rb new file mode 100644 index 0000000..c3a8bc6 --- /dev/null +++ b/test/chaplin-on-rails_test.rb @@ -0,0 +1,19 @@ +require 'test_helper' + +class ChaplinOnRailsTest < ActiveSupport::TestCase + def setup + @app = Dummy::Application + end + + test "backbone.js is found as an asset" do + assert_not_nil @app.assets["backbone"] + end + + test "underscore.js is found as an asset" do + assert_not_nil @app.assets["underscore"] + end + + test "chaplin.js is found as an asset" do + assert_not_nil @app.assets["chaplin"] + end +end diff --git a/test/dummy/README.rdoc b/test/dummy/README.rdoc new file mode 100644 index 0000000..7c36f23 --- /dev/null +++ b/test/dummy/README.rdoc @@ -0,0 +1,261 @@ +== Welcome to Rails + +Rails is a web-application framework that includes everything needed to create +database-backed web applications according to the Model-View-Control pattern. + +This pattern splits the view (also called the presentation) into "dumb" +templates that are primarily responsible for inserting pre-built data in between +HTML tags. The model contains the "smart" domain objects (such as Account, +Product, Person, Post) that holds all the business logic and knows how to +persist themselves to a database. The controller handles the incoming requests +(such as Save New Account, Update Product, Show Post) by manipulating the model +and directing data to the view. + +In Rails, the model is handled by what's called an object-relational mapping +layer entitled Active Record. This layer allows you to present the data from +database rows as objects and embellish these data objects with business logic +methods. You can read more about Active Record in +link:files/vendor/rails/activerecord/README.html. + +The controller and view are handled by the Action Pack, which handles both +layers by its two parts: Action View and Action Controller. These two layers +are bundled in a single package due to their heavy interdependence. This is +unlike the relationship between the Active Record and Action Pack that is much +more separate. Each of these packages can be used independently outside of +Rails. You can read more about Action Pack in +link:files/vendor/rails/actionpack/README.html. + + +== Getting Started + +1. At the command prompt, create a new Rails application: + rails new myapp (where myapp is the application name) + +2. Change directory to myapp and start the web server: + cd myapp; rails server (run with --help for options) + +3. Go to http://localhost:3000/ and you'll see: + "Welcome aboard: You're riding Ruby on Rails!" + +4. Follow the guidelines to start developing your application. You can find +the following resources handy: + +* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html +* Ruby on Rails Tutorial Book: http://www.railstutorial.org/ + + +== Debugging Rails + +Sometimes your application goes wrong. Fortunately there are a lot of tools that +will help you debug it and get it back on the rails. + +First area to check is the application log files. Have "tail -f" commands +running on the server.log and development.log. Rails will automatically display +debugging and runtime information to these files. Debugging info will also be +shown in the browser on requests from 127.0.0.1. + +You can also log your own messages directly into the log file from your code +using the Ruby logger class from inside your controllers. Example: + + class WeblogController < ActionController::Base + def destroy + @weblog = Weblog.find(params[:id]) + @weblog.destroy + logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") + end + end + +The result will be a message in your log file along the lines of: + + Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! + +More information on how to use the logger is at http://www.ruby-doc.org/core/ + +Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are +several books available online as well: + +* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) +* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) + +These two books will bring you up to speed on the Ruby language and also on +programming in general. + + +== Debugger + +Debugger support is available through the debugger command when you start your +Mongrel or WEBrick server with --debugger. This means that you can break out of +execution at any point in the code, investigate and change the model, and then, +resume execution! You need to install ruby-debug to run the server in debugging +mode. With gems, use sudo gem install ruby-debug. Example: + + class WeblogController < ActionController::Base + def index + @posts = Post.all + debugger + end + end + +So the controller will accept the action, run the first line, then present you +with a IRB prompt in the server window. Here you can do things like: + + >> @posts.inspect + => "[#nil, "body"=>nil, "id"=>"1"}>, + #"Rails", "body"=>"Only ten..", "id"=>"2"}>]" + >> @posts.first.title = "hello from a debugger" + => "hello from a debugger" + +...and even better, you can examine how your runtime objects actually work: + + >> f = @posts.first + => #nil, "body"=>nil, "id"=>"1"}> + >> f. + Display all 152 possibilities? (y or n) + +Finally, when you're ready to resume execution, you can enter "cont". + + +== Console + +The console is a Ruby shell, which allows you to interact with your +application's domain model. Here you'll have all parts of the application +configured, just like it is when the application is running. You can inspect +domain models, change values, and save to the database. Starting the script +without arguments will launch it in the development environment. + +To start the console, run rails console from the application +directory. + +Options: + +* Passing the -s, --sandbox argument will rollback any modifications + made to the database. +* Passing an environment name as an argument will load the corresponding + environment. Example: rails console production. + +To reload your controllers and models after launching the console run +reload! + +More information about irb can be found at: +link:http://www.rubycentral.org/pickaxe/irb.html + + +== dbconsole + +You can go to the command line of your database directly through rails +dbconsole. You would be connected to the database with the credentials +defined in database.yml. Starting the script without arguments will connect you +to the development database. Passing an argument will connect you to a different +database, like rails dbconsole production. Currently works for MySQL, +PostgreSQL and SQLite 3. + +== Description of Contents + +The default directory structure of a generated Ruby on Rails application: + + |-- app + | |-- assets + | |-- images + | |-- javascripts + | `-- stylesheets + | |-- controllers + | |-- helpers + | |-- mailers + | |-- models + | `-- views + | `-- layouts + |-- config + | |-- environments + | |-- initializers + | `-- locales + |-- db + |-- doc + |-- lib + | `-- tasks + |-- log + |-- public + |-- script + |-- test + | |-- fixtures + | |-- functional + | |-- integration + | |-- performance + | `-- unit + |-- tmp + | |-- cache + | |-- pids + | |-- sessions + | `-- sockets + `-- vendor + |-- assets + `-- stylesheets + `-- plugins + +app + Holds all the code that's specific to this particular application. + +app/assets + Contains subdirectories for images, stylesheets, and JavaScript files. + +app/controllers + Holds controllers that should be named like weblogs_controller.rb for + automated URL mapping. All controllers should descend from + ApplicationController which itself descends from ActionController::Base. + +app/models + Holds models that should be named like post.rb. Models descend from + ActiveRecord::Base by default. + +app/views + Holds the template files for the view that should be named like + weblogs/index.html.erb for the WeblogsController#index action. All views use + eRuby syntax by default. + +app/views/layouts + Holds the template files for layouts to be used with views. This models the + common header/footer method of wrapping views. In your views, define a layout + using the layout :default and create a file named default.html.erb. + Inside default.html.erb, call <% yield %> to render the view using this + layout. + +app/helpers + Holds view helpers that should be named like weblogs_helper.rb. These are + generated for you automatically when using generators for controllers. + Helpers can be used to wrap functionality for your views into methods. + +config + Configuration files for the Rails environment, the routing map, the database, + and other dependencies. + +db + Contains the database schema in schema.rb. db/migrate contains all the + sequence of Migrations for your schema. + +doc + This directory is where your application documentation will be stored when + generated using rake doc:app + +lib + Application specific libraries. Basically, any kind of custom code that + doesn't belong under controllers, models, or helpers. This directory is in + the load path. + +public + The directory available for the web server. Also contains the dispatchers and the + default HTML files. This should be set as the DOCUMENT_ROOT of your web + server. + +script + Helper scripts for automation and generation. + +test + Unit and functional tests along with fixtures. When using the rails generate + command, template test files will be generated for you and placed in this + directory. + +vendor + External libraries that the application depends on. Also includes the plugins + subdirectory. If the app has frozen rails, those gems also go here, under + vendor/rails/. This directory is in the load path. diff --git a/test/dummy/Rakefile b/test/dummy/Rakefile new file mode 100644 index 0000000..3645852 --- /dev/null +++ b/test/dummy/Rakefile @@ -0,0 +1,7 @@ +#!/usr/bin/env rake +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require File.expand_path('../config/application', __FILE__) + +Dummy::Application.load_tasks diff --git a/test/dummy/app/assets/stylesheets/application.css b/test/dummy/app/assets/stylesheets/application.css new file mode 100644 index 0000000..3192ec8 --- /dev/null +++ b/test/dummy/app/assets/stylesheets/application.css @@ -0,0 +1,13 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, + * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the top of the + * compiled file, but it's generally better to create a new file per style scope. + * + *= require_self + *= require_tree . + */ diff --git a/test/dummy/app/controllers/application_controller.rb b/test/dummy/app/controllers/application_controller.rb new file mode 100644 index 0000000..e8065d9 --- /dev/null +++ b/test/dummy/app/controllers/application_controller.rb @@ -0,0 +1,3 @@ +class ApplicationController < ActionController::Base + protect_from_forgery +end diff --git a/test/dummy/app/controllers/home_controller.rb b/test/dummy/app/controllers/home_controller.rb new file mode 100644 index 0000000..3181ce6 --- /dev/null +++ b/test/dummy/app/controllers/home_controller.rb @@ -0,0 +1,5 @@ +class HomeController < ApplicationController + def index + + end +end diff --git a/test/dummy/app/helpers/application_helper.rb b/test/dummy/app/helpers/application_helper.rb new file mode 100644 index 0000000..de6be79 --- /dev/null +++ b/test/dummy/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/test/dummy/app/helpers/home_helper.rb b/test/dummy/app/helpers/home_helper.rb new file mode 100644 index 0000000..23de56a --- /dev/null +++ b/test/dummy/app/helpers/home_helper.rb @@ -0,0 +1,2 @@ +module HomeHelper +end diff --git a/test/dummy/app/mailers/.gitkeep b/test/dummy/app/mailers/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/app/models/.gitkeep b/test/dummy/app/models/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/app/views/home/index.html.erb b/test/dummy/app/views/home/index.html.erb new file mode 100644 index 0000000..fd932e9 --- /dev/null +++ b/test/dummy/app/views/home/index.html.erb @@ -0,0 +1 @@ +
diff --git a/test/dummy/app/views/layouts/application.html.erb b/test/dummy/app/views/layouts/application.html.erb new file mode 100644 index 0000000..4cab268 --- /dev/null +++ b/test/dummy/app/views/layouts/application.html.erb @@ -0,0 +1,14 @@ + + + + Dummy + <%= stylesheet_link_tag "application", :media => "all" %> + <%= javascript_include_tag "application" %> + <%= csrf_meta_tags %> + + + +<%= yield %> + + + diff --git a/test/dummy/config.ru b/test/dummy/config.ru new file mode 100644 index 0000000..1989ed8 --- /dev/null +++ b/test/dummy/config.ru @@ -0,0 +1,4 @@ +# This file is used by Rack-based servers to start the application. + +require ::File.expand_path('../config/environment', __FILE__) +run Dummy::Application diff --git a/test/dummy/config/application.rb b/test/dummy/config/application.rb new file mode 100644 index 0000000..77ac926 --- /dev/null +++ b/test/dummy/config/application.rb @@ -0,0 +1,59 @@ +require File.expand_path('../boot', __FILE__) + +require 'rails/all' + +Bundler.require +require "chaplin-on-rails" + +module Dummy + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Custom directories with classes and modules you want to be autoloadable. + # config.autoload_paths += %W(#{config.root}/extras) + + # Only load the plugins named here, in the order given (default is alphabetical). + # :all can be used as a placeholder for all plugins not explicitly named. + # config.plugins = [ :exception_notification, :ssl_requirement, :all ] + + # Activate observers that should always be running. + # config.active_record.observers = :cacher, :garbage_collector, :forum_observer + + # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. + # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. + # config.time_zone = 'Central Time (US & Canada)' + + # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. + # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] + # config.i18n.default_locale = :de + + # Configure the default encoding used in templates for Ruby 1.9. + config.encoding = "utf-8" + + # Configure sensitive parameters which will be filtered from the log file. + config.filter_parameters += [:password] + + # Enable escaping HTML in JSON. + config.active_support.escape_html_entities_in_json = true + + # Use SQL instead of Active Record's schema dumper when creating the database. + # This is necessary if your schema can't be completely dumped by the schema dumper, + # like if you have constraints or database-specific column types + # config.active_record.schema_format = :sql + + # Enforce whitelist mode for mass assignment. + # This will create an empty whitelist of attributes available for mass-assignment for all models + # in your app. As such, your models will need to explicitly whitelist or blacklist accessible + # parameters by using an attr_accessible or attr_protected declaration. + config.active_record.whitelist_attributes = true + + # Enable the asset pipeline + config.assets.enabled = true + + # Version of your assets, change this if you want to expire all your assets + config.assets.version = '1.0' + end +end + diff --git a/test/dummy/config/boot.rb b/test/dummy/config/boot.rb new file mode 100644 index 0000000..eba0681 --- /dev/null +++ b/test/dummy/config/boot.rb @@ -0,0 +1,10 @@ +require 'rubygems' +gemfile = File.expand_path('../../../../Gemfile', __FILE__) + +if File.exist?(gemfile) + ENV['BUNDLE_GEMFILE'] = gemfile + require 'bundler' + Bundler.setup +end + +$:.unshift File.expand_path('../../../../lib', __FILE__) \ No newline at end of file diff --git a/test/dummy/config/database.yml b/test/dummy/config/database.yml new file mode 100644 index 0000000..51a4dd4 --- /dev/null +++ b/test/dummy/config/database.yml @@ -0,0 +1,25 @@ +# SQLite version 3.x +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem 'sqlite3' +development: + adapter: sqlite3 + database: db/development.sqlite3 + pool: 5 + timeout: 5000 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + adapter: sqlite3 + database: db/test.sqlite3 + pool: 5 + timeout: 5000 + +production: + adapter: sqlite3 + database: db/production.sqlite3 + pool: 5 + timeout: 5000 diff --git a/test/dummy/config/environment.rb b/test/dummy/config/environment.rb new file mode 100644 index 0000000..3da5eb9 --- /dev/null +++ b/test/dummy/config/environment.rb @@ -0,0 +1,5 @@ +# Load the rails application +require File.expand_path('../application', __FILE__) + +# Initialize the rails application +Dummy::Application.initialize! diff --git a/test/dummy/config/environments/development.rb b/test/dummy/config/environments/development.rb new file mode 100644 index 0000000..82c74d1 --- /dev/null +++ b/test/dummy/config/environments/development.rb @@ -0,0 +1,37 @@ +Dummy::Application.configure do + # Settings specified here will take precedence over those in config/application.rb + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Log error messages when you accidentally call methods on nil. + config.whiny_nils = true + + # Show full error reports and disable caching + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Don't care if the mailer can't send + config.action_mailer.raise_delivery_errors = false + + # Print deprecation notices to the Rails logger + config.active_support.deprecation = :log + + # Only use best-standards-support built into browsers + config.action_dispatch.best_standards_support = :builtin + + # Raise exception on mass assignment protection for Active Record models + config.active_record.mass_assignment_sanitizer = :strict + + # Log the query plan for queries taking more than this (works + # with SQLite, MySQL, and PostgreSQL) + config.active_record.auto_explain_threshold_in_seconds = 0.5 + + # Do not compress assets + config.assets.compress = false + + # Expands the lines which load the assets + config.assets.debug = true +end diff --git a/test/dummy/config/environments/production.rb b/test/dummy/config/environments/production.rb new file mode 100644 index 0000000..bdac56a --- /dev/null +++ b/test/dummy/config/environments/production.rb @@ -0,0 +1,67 @@ +Dummy::Application.configure do + # Settings specified here will take precedence over those in config/application.rb + + # Code is not reloaded between requests + config.cache_classes = true + + # Full error reports are disabled and caching is turned on + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Disable Rails's static asset server (Apache or nginx will already do this) + config.serve_static_assets = false + + # Compress JavaScripts and CSS + config.assets.compress = true + + # Don't fallback to assets pipeline if a precompiled asset is missed + config.assets.compile = false + + # Generate digests for assets URLs + config.assets.digest = true + + # Defaults to nil and saved in location specified by config.assets.prefix + # config.assets.manifest = YOUR_PATH + + # Specifies the header that your server uses for sending files + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # See everything in the log (default is :info) + # config.log_level = :debug + + # Prepend all log lines with the following tags + # config.log_tags = [ :subdomain, :uuid ] + + # Use a different logger for distributed setups + # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) + + # Use a different cache store in production + # config.cache_store = :mem_cache_store + + # Enable serving of images, stylesheets, and JavaScripts from an asset server + # config.action_controller.asset_host = "http://assets.example.com" + + # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) + # config.assets.precompile += %w( search.js ) + + # Disable delivery errors, bad email addresses will be ignored + # config.action_mailer.raise_delivery_errors = false + + # Enable threaded mode + # config.threadsafe! + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation can not be found) + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners + config.active_support.deprecation = :notify + + # Log the query plan for queries taking more than this (works + # with SQLite, MySQL, and PostgreSQL) + # config.active_record.auto_explain_threshold_in_seconds = 0.5 +end diff --git a/test/dummy/config/environments/test.rb b/test/dummy/config/environments/test.rb new file mode 100644 index 0000000..f1a4814 --- /dev/null +++ b/test/dummy/config/environments/test.rb @@ -0,0 +1,37 @@ +Dummy::Application.configure do + # Settings specified here will take precedence over those in config/application.rb + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Configure static asset server for tests with Cache-Control for performance + config.serve_static_assets = true + config.static_cache_control = "public, max-age=3600" + + # Log error messages when you accidentally call methods on nil + config.whiny_nils = true + + # Show full error reports and disable caching + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment + config.action_controller.allow_forgery_protection = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Raise exception on mass assignment protection for Active Record models + config.active_record.mass_assignment_sanitizer = :strict + + # Print deprecation notices to the stderr + config.active_support.deprecation = :stderr +end diff --git a/test/dummy/config/initializers/backtrace_silencers.rb b/test/dummy/config/initializers/backtrace_silencers.rb new file mode 100644 index 0000000..59385cd --- /dev/null +++ b/test/dummy/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/test/dummy/config/initializers/inflections.rb b/test/dummy/config/initializers/inflections.rb new file mode 100644 index 0000000..5d8d9be --- /dev/null +++ b/test/dummy/config/initializers/inflections.rb @@ -0,0 +1,15 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format +# (all these examples are active by default): +# ActiveSupport::Inflector.inflections do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end +# +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/test/dummy/config/initializers/mime_types.rb b/test/dummy/config/initializers/mime_types.rb new file mode 100644 index 0000000..72aca7e --- /dev/null +++ b/test/dummy/config/initializers/mime_types.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf +# Mime::Type.register_alias "text/html", :iphone diff --git a/test/dummy/config/initializers/secret_token.rb b/test/dummy/config/initializers/secret_token.rb new file mode 100644 index 0000000..933e729 --- /dev/null +++ b/test/dummy/config/initializers/secret_token.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +Dummy::Application.config.secret_token = 'e5a6dc17a0525a29983af7ed73aa05875ed7271e9c850bf420a73c4564e358576e41dd8cccf04f6b2155d586b26b15dc90d27745c971127f890241c6c4c2c9e7' diff --git a/test/dummy/config/initializers/session_store.rb b/test/dummy/config/initializers/session_store.rb new file mode 100644 index 0000000..952473f --- /dev/null +++ b/test/dummy/config/initializers/session_store.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' + +# Use the database for sessions instead of the cookie-based default, +# which shouldn't be used to store highly confidential information +# (create the session table with "rails generate session_migration") +# Dummy::Application.config.session_store :active_record_store diff --git a/test/dummy/config/initializers/wrap_parameters.rb b/test/dummy/config/initializers/wrap_parameters.rb new file mode 100644 index 0000000..999df20 --- /dev/null +++ b/test/dummy/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. +# +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# Disable root element in JSON by default. +ActiveSupport.on_load(:active_record) do + self.include_root_in_json = false +end diff --git a/test/dummy/config/locales/en.yml b/test/dummy/config/locales/en.yml new file mode 100644 index 0000000..179c14c --- /dev/null +++ b/test/dummy/config/locales/en.yml @@ -0,0 +1,5 @@ +# Sample localization file for English. Add more files in this directory for other locales. +# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. + +en: + hello: "Hello world" diff --git a/test/dummy/config/routes.rb b/test/dummy/config/routes.rb new file mode 100644 index 0000000..3e7d5ea --- /dev/null +++ b/test/dummy/config/routes.rb @@ -0,0 +1,58 @@ +Dummy::Application.routes.draw do + # The priority is based upon order of creation: + # first created -> highest priority. + + # Sample of regular route: + # match 'products/:id' => 'catalog#view' + # Keep in mind you can assign values other than :controller and :action + + # Sample of named route: + # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase + # This route can be invoked with purchase_url(:id => product.id) + + # Sample resource route (maps HTTP verbs to controller actions automatically): + # resources :products + + # Sample resource route with options: + # resources :products do + # member do + # get 'short' + # post 'toggle' + # end + # + # collection do + # get 'sold' + # end + # end + + # Sample resource route with sub-resources: + # resources :products do + # resources :comments, :sales + # resource :seller + # end + + # Sample resource route with more complex sub-resources + # resources :products do + # resources :comments + # resources :sales do + # get 'recent', :on => :collection + # end + # end + + # Sample resource route within a namespace: + # namespace :admin do + # # Directs /admin/products/* to Admin::ProductsController + # # (app/controllers/admin/products_controller.rb) + # resources :products + # end + + # You can have the root of your site routed with "root" + # just remember to delete public/index.html. + root :to => 'home#index' + + # See how all your routes lay out with "rake routes" + + # This is a legacy wild controller route that's not recommended for RESTful applications. + # Note: This route will make all actions in every controller accessible via GET requests. + # match ':controller(/:action(/:id))(.:format)' +end diff --git a/test/dummy/log/.gitkeep b/test/dummy/log/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/public/404.html b/test/dummy/public/404.html new file mode 100644 index 0000000..9a48320 --- /dev/null +++ b/test/dummy/public/404.html @@ -0,0 +1,26 @@ + + + + The page you were looking for doesn't exist (404) + + + + + +
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+ + diff --git a/test/dummy/public/422.html b/test/dummy/public/422.html new file mode 100644 index 0000000..83660ab --- /dev/null +++ b/test/dummy/public/422.html @@ -0,0 +1,26 @@ + + + + The change you wanted was rejected (422) + + + + + +
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+ + diff --git a/test/dummy/public/500.html b/test/dummy/public/500.html new file mode 100644 index 0000000..f3648a0 --- /dev/null +++ b/test/dummy/public/500.html @@ -0,0 +1,25 @@ + + + + We're sorry, but something went wrong (500) + + + + + +
+

We're sorry, but something went wrong.

+
+ + diff --git a/test/dummy/public/favicon.ico b/test/dummy/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/test/dummy/script/rails b/test/dummy/script/rails new file mode 100755 index 0000000..f8da2cf --- /dev/null +++ b/test/dummy/script/rails @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. + +APP_PATH = File.expand_path('../../config/application', __FILE__) +require File.expand_path('../../config/boot', __FILE__) +require 'rails/commands' diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..d231467 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,7 @@ +# Configure Rails Environment +ENV["RAILS_ENV"] = "test" + +require File.expand_path("../dummy/config/environment.rb", __FILE__) +require "rails/test_help" + +Rails.backtrace_cleaner.remove_silencers! diff --git a/vendor/assets/javascripts/backbone.js b/vendor/assets/javascripts/backbone.js new file mode 100644 index 0000000..07ed747 --- /dev/null +++ b/vendor/assets/javascripts/backbone.js @@ -0,0 +1,1497 @@ +// Backbone.js 0.9.9 + +// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. +// Backbone may be freely distributed under the MIT license. +// For all details and documentation: +// http://backbonejs.org + +(function(){ + + // Initial Setup + // ------------- + + // Save a reference to the global object (`window` in the browser, `exports` + // on the server). + var root = this; + + // Save the previous value of the `Backbone` variable, so that it can be + // restored later on, if `noConflict` is used. + var previousBackbone = root.Backbone; + + // Create a local reference to array methods. + var array = []; + var push = array.push; + var slice = array.slice; + var splice = array.splice; + + // The top-level namespace. All public Backbone classes and modules will + // be attached to this. Exported for both CommonJS and the browser. + var Backbone; + if (typeof exports !== 'undefined') { + Backbone = exports; + } else { + Backbone = root.Backbone = {}; + } + + // Current version of the library. Keep in sync with `package.json`. + Backbone.VERSION = '0.9.9'; + + // Require Underscore, if we're on the server, and it's not already present. + var _ = root._; + if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); + + // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable. + Backbone.$ = root.jQuery || root.Zepto || root.ender; + + // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable + // to its previous owner. Returns a reference to this Backbone object. + Backbone.noConflict = function() { + root.Backbone = previousBackbone; + return this; + }; + + // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option + // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and + // set a `X-Http-Method-Override` header. + Backbone.emulateHTTP = false; + + // Turn on `emulateJSON` to support legacy servers that can't deal with direct + // `application/json` requests ... will encode the body as + // `application/x-www-form-urlencoded` instead and will send the model in a + // form param named `model`. + Backbone.emulateJSON = false; + + // Backbone.Events + // --------------- + + // Regular expression used to split event strings. + var eventSplitter = /\s+/; + + // Implement fancy features of the Events API such as multiple event + // names `"change blur"` and jQuery-style event maps `{change: action}` + // in terms of the existing API. + var eventsApi = function(obj, action, name, rest) { + if (!name) return true; + if (typeof name === 'object') { + for (var key in name) { + obj[action].apply(obj, [key, name[key]].concat(rest)); + } + } else if (eventSplitter.test(name)) { + var names = name.split(eventSplitter); + for (var i = 0, l = names.length; i < l; i++) { + obj[action].apply(obj, [names[i]].concat(rest)); + } + } else { + return true; + } + }; + + // Optimized internal dispatch function for triggering events. Tries to + // keep the usual cases speedy (most Backbone events have 3 arguments). + var triggerEvents = function(obj, events, args) { + var ev, i = -1, l = events.length; + switch (args.length) { + case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); + return; + case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0]); + return; + case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1]); + return; + case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1], args[2]); + return; + default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); + } + }; + + // A module that can be mixed in to *any object* in order to provide it with + // custom events. You may bind with `on` or remove with `off` callback + // functions to an event; `trigger`-ing an event fires all callbacks in + // succession. + // + // var object = {}; + // _.extend(object, Backbone.Events); + // object.on('expand', function(){ alert('expanded'); }); + // object.trigger('expand'); + // + var Events = Backbone.Events = { + + // Bind one or more space separated events, or an events map, + // to a `callback` function. Passing `"all"` will bind the callback to + // all events fired. + on: function(name, callback, context) { + if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this; + this._events || (this._events = {}); + var list = this._events[name] || (this._events[name] = []); + list.push({callback: callback, context: context, ctx: context || this}); + return this; + }, + + // Bind events to only be triggered a single time. After the first time + // the callback is invoked, it will be removed. + once: function(name, callback, context) { + if (!(eventsApi(this, 'once', name, [callback, context]) && callback)) return this; + var self = this; + var once = _.once(function() { + self.off(name, once); + callback.apply(this, arguments); + }); + once._callback = callback; + this.on(name, once, context); + return this; + }, + + // Remove one or many callbacks. If `context` is null, removes all + // callbacks with that function. If `callback` is null, removes all + // callbacks for the event. If `name` is null, removes all bound + // callbacks for all events. + off: function(name, callback, context) { + var list, ev, events, names, i, l, j, k; + if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; + if (!name && !callback && !context) { + this._events = {}; + return this; + } + + names = name ? [name] : _.keys(this._events); + for (i = 0, l = names.length; i < l; i++) { + name = names[i]; + if (list = this._events[name]) { + events = []; + if (callback || context) { + for (j = 0, k = list.length; j < k; j++) { + ev = list[j]; + if ((callback && callback !== ev.callback && + callback !== ev.callback._callback) || + (context && context !== ev.context)) { + events.push(ev); + } + } + } + this._events[name] = events; + } + } + + return this; + }, + + // Trigger one or many events, firing all bound callbacks. Callbacks are + // passed the same arguments as `trigger` is, apart from the event name + // (unless you're listening on `"all"`, which will cause your callback to + // receive the true name of the event as the first argument). + trigger: function(name) { + if (!this._events) return this; + var args = slice.call(arguments, 1); + if (!eventsApi(this, 'trigger', name, args)) return this; + var events = this._events[name]; + var allEvents = this._events.all; + if (events) triggerEvents(this, events, args); + if (allEvents) triggerEvents(this, allEvents, arguments); + return this; + }, + + // An inversion-of-control version of `on`. Tell *this* object to listen to + // an event in another object ... keeping track of what it's listening to. + listenTo: function(object, events, callback) { + var listeners = this._listeners || (this._listeners = {}); + var id = object._listenerId || (object._listenerId = _.uniqueId('l')); + listeners[id] = object; + object.on(events, callback || this, this); + return this; + }, + + // Tell this object to stop listening to either specific events ... or + // to every object it's currently listening to. + stopListening: function(object, events, callback) { + var listeners = this._listeners; + if (!listeners) return; + if (object) { + object.off(events, callback, this); + if (!events && !callback) delete listeners[object._listenerId]; + } else { + for (var id in listeners) { + listeners[id].off(null, null, this); + } + this._listeners = {}; + } + return this; + } + }; + + // Aliases for backwards compatibility. + Events.bind = Events.on; + Events.unbind = Events.off; + + // Allow the `Backbone` object to serve as a global event bus, for folks who + // want global "pubsub" in a convenient place. + _.extend(Backbone, Events); + + // Backbone.Model + // -------------- + + // Create a new model, with defined attributes. A client id (`cid`) + // is automatically generated and assigned for you. + var Model = Backbone.Model = function(attributes, options) { + var defaults; + var attrs = attributes || {}; + this.cid = _.uniqueId('c'); + this.attributes = {}; + if (options && options.collection) this.collection = options.collection; + if (options && options.parse) attrs = this.parse(attrs, options) || {}; + if (defaults = _.result(this, 'defaults')) { + attrs = _.defaults({}, attrs, defaults); + } + this.set(attrs, options); + this.changed = {}; + this.initialize.apply(this, arguments); + }; + + // Attach all inheritable methods to the Model prototype. + _.extend(Model.prototype, Events, { + + // A hash of attributes whose current and previous value differ. + changed: null, + + // The default name for the JSON `id` attribute is `"id"`. MongoDB and + // CouchDB users may want to set this to `"_id"`. + idAttribute: 'id', + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Return a copy of the model's `attributes` object. + toJSON: function(options) { + return _.clone(this.attributes); + }, + + // Proxy `Backbone.sync` by default. + sync: function() { + return Backbone.sync.apply(this, arguments); + }, + + // Get the value of an attribute. + get: function(attr) { + return this.attributes[attr]; + }, + + // Get the HTML-escaped value of an attribute. + escape: function(attr) { + return _.escape(this.get(attr)); + }, + + // Returns `true` if the attribute contains a value that is not null + // or undefined. + has: function(attr) { + return this.get(attr) != null; + }, + + // ---------------------------------------------------------------------- + + // Set a hash of model attributes on the object, firing `"change"` unless + // you choose to silence it. + set: function(key, val, options) { + var attr, attrs, unset, changes, silent, changing, prev, current; + if (key == null) return this; + + // Handle both `"key", value` and `{key: value}` -style arguments. + if (typeof key === 'object') { + attrs = key; + options = val; + } else { + (attrs = {})[key] = val; + } + + options || (options = {}); + + // Run validation. + if (!this._validate(attrs, options)) return false; + + // Extract attributes and options. + unset = options.unset; + silent = options.silent; + changes = []; + changing = this._changing; + this._changing = true; + + if (!changing) { + this._previousAttributes = _.clone(this.attributes); + this.changed = {}; + } + current = this.attributes, prev = this._previousAttributes; + + // Check for changes of `id`. + if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; + + // For each `set` attribute, update or delete the current value. + for (attr in attrs) { + val = attrs[attr]; + if (!_.isEqual(current[attr], val)) changes.push(attr); + if (!_.isEqual(prev[attr], val)) { + this.changed[attr] = val; + } else { + delete this.changed[attr]; + } + unset ? delete current[attr] : current[attr] = val; + } + + // Trigger all relevant attribute changes. + if (!silent) { + if (changes.length) this._pending = true; + for (var i = 0, l = changes.length; i < l; i++) { + this.trigger('change:' + changes[i], this, current[changes[i]], options); + } + } + + if (changing) return this; + if (!silent) { + while (this._pending) { + this._pending = false; + this.trigger('change', this, options); + } + } + this._pending = false; + this._changing = false; + return this; + }, + + // Remove an attribute from the model, firing `"change"` unless you choose + // to silence it. `unset` is a noop if the attribute doesn't exist. + unset: function(attr, options) { + return this.set(attr, void 0, _.extend({}, options, {unset: true})); + }, + + // Clear all attributes on the model, firing `"change"` unless you choose + // to silence it. + clear: function(options) { + var attrs = {}; + for (var key in this.attributes) attrs[key] = void 0; + return this.set(attrs, _.extend({}, options, {unset: true})); + }, + + // Determine if the model has changed since the last `"change"` event. + // If you specify an attribute name, determine if that attribute has changed. + hasChanged: function(attr) { + if (attr == null) return !_.isEmpty(this.changed); + return _.has(this.changed, attr); + }, + + // Return an object containing all the attributes that have changed, or + // false if there are no changed attributes. Useful for determining what + // parts of a view need to be updated and/or what attributes need to be + // persisted to the server. Unset attributes will be set to undefined. + // You can also pass an attributes object to diff against the model, + // determining if there *would be* a change. + changedAttributes: function(diff) { + if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; + var val, changed = false; + var old = this._changing ? this._previousAttributes : this.attributes; + for (var attr in diff) { + if (_.isEqual(old[attr], (val = diff[attr]))) continue; + (changed || (changed = {}))[attr] = val; + } + return changed; + }, + + // Get the previous value of an attribute, recorded at the time the last + // `"change"` event was fired. + previous: function(attr) { + if (attr == null || !this._previousAttributes) return null; + return this._previousAttributes[attr]; + }, + + // Get all of the attributes of the model at the time of the previous + // `"change"` event. + previousAttributes: function() { + return _.clone(this._previousAttributes); + }, + + // --------------------------------------------------------------------- + + // Fetch the model from the server. If the server's representation of the + // model differs from its current attributes, they will be overriden, + // triggering a `"change"` event. + fetch: function(options) { + options = options ? _.clone(options) : {}; + if (options.parse === void 0) options.parse = true; + var success = options.success; + options.success = function(model, resp, options) { + if (!model.set(model.parse(resp, options), options)) return false; + if (success) success(model, resp, options); + }; + return this.sync('read', this, options); + }, + + // Set a hash of model attributes, and sync the model to the server. + // If the server returns an attributes hash that differs, the model's + // state will be `set` again. + save: function(key, val, options) { + var attrs, success, method, xhr, attributes = this.attributes; + + // Handle both `"key", value` and `{key: value}` -style arguments. + if (key == null || typeof key === 'object') { + attrs = key; + options = val; + } else { + (attrs = {})[key] = val; + } + + // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`. + if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false; + + options = _.extend({validate: true}, options); + + // Do not persist invalid models. + if (!this._validate(attrs, options)) return false; + + // Set temporary attributes if `{wait: true}`. + if (attrs && options.wait) { + this.attributes = _.extend({}, attributes, attrs); + } + + // After a successful server-side save, the client is (optionally) + // updated with the server-side state. + if (options.parse === void 0) options.parse = true; + success = options.success; + options.success = function(model, resp, options) { + // Ensure attributes are restored during synchronous saves. + model.attributes = attributes; + var serverAttrs = model.parse(resp, options); + if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); + if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { + return false; + } + if (success) success(model, resp, options); + }; + + // Finish configuring and sending the Ajax request. + method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); + if (method == 'patch') options.attrs = attrs; + xhr = this.sync(method, this, options); + + // Restore attributes. + if (attrs && options.wait) this.attributes = attributes; + + return xhr; + }, + + // Destroy this model on the server if it was already persisted. + // Optimistically removes the model from its collection, if it has one. + // If `wait: true` is passed, waits for the server to respond before removal. + destroy: function(options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + + var destroy = function() { + model.trigger('destroy', model, model.collection, options); + }; + + options.success = function(model, resp, options) { + if (options.wait || model.isNew()) destroy(); + if (success) success(model, resp, options); + }; + + if (this.isNew()) { + options.success(this, null, options); + return false; + } + + var xhr = this.sync('delete', this, options); + if (!options.wait) destroy(); + return xhr; + }, + + // Default URL for the model's representation on the server -- if you're + // using Backbone's restful methods, override this to change the endpoint + // that will be called. + url: function() { + var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); + if (this.isNew()) return base; + return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id); + }, + + // **parse** converts a response into the hash of attributes to be `set` on + // the model. The default implementation is just to pass the response along. + parse: function(resp, options) { + return resp; + }, + + // Create a new model with identical attributes to this one. + clone: function() { + return new this.constructor(this.attributes); + }, + + // A model is new if it has never been saved to the server, and lacks an id. + isNew: function() { + return this.id == null; + }, + + // Check if the model is currently in a valid state. + isValid: function(options) { + return !this.validate || !this.validate(this.attributes, options); + }, + + // Run validation against the next complete set of model attributes, + // returning `true` if all is well. Otherwise, fire a general + // `"error"` event and call the error callback, if specified. + _validate: function(attrs, options) { + if (!options.validate || !this.validate) return true; + attrs = _.extend({}, this.attributes, attrs); + var error = this.validationError = this.validate(attrs, options) || null; + if (!error) return true; + this.trigger('invalid', this, error, options || {}); + return false; + } + + }); + + // Backbone.Collection + // ------------------- + + // Provides a standard collection class for our sets of models, ordered + // or unordered. If a `comparator` is specified, the Collection will maintain + // its models in sort order, as they're added and removed. + var Collection = Backbone.Collection = function(models, options) { + options || (options = {}); + if (options.model) this.model = options.model; + if (options.comparator !== void 0) this.comparator = options.comparator; + this.models = []; + this._reset(); + this.initialize.apply(this, arguments); + if (models) this.reset(models, _.extend({silent: true}, options)); + }; + + // Define the Collection's inheritable methods. + _.extend(Collection.prototype, Events, { + + // The default model for a collection is just a **Backbone.Model**. + // This should be overridden in most cases. + model: Model, + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // The JSON representation of a Collection is an array of the + // models' attributes. + toJSON: function(options) { + return this.map(function(model){ return model.toJSON(options); }); + }, + + // Proxy `Backbone.sync` by default. + sync: function() { + return Backbone.sync.apply(this, arguments); + }, + + // Add a model, or list of models to the set. + add: function(models, options) { + models = _.isArray(models) ? models.slice() : [models]; + options || (options = {}); + var i, l, model, attrs, existing, doSort, add, at, sort, sortAttr; + add = []; + at = options.at; + sort = this.comparator && (at == null) && options.sort != false; + sortAttr = _.isString(this.comparator) ? this.comparator : null; + + // Turn bare objects into model references, and prevent invalid models + // from being added. + for (i = 0, l = models.length; i < l; i++) { + if (!(model = this._prepareModel(attrs = models[i], options))) { + this.trigger('invalid', this, attrs, options); + continue; + } + + // If a duplicate is found, prevent it from being added and + // optionally merge it into the existing model. + if (existing = this.get(model)) { + if (options.merge) { + existing.set(attrs === model ? model.attributes : attrs, options); + if (sort && !doSort && existing.hasChanged(sortAttr)) doSort = true; + } + continue; + } + + // This is a new model, push it to the `add` list. + add.push(model); + + // Listen to added models' events, and index models for lookup by + // `id` and by `cid`. + model.on('all', this._onModelEvent, this); + this._byId[model.cid] = model; + if (model.id != null) this._byId[model.id] = model; + } + + // See if sorting is needed, update `length` and splice in new models. + if (add.length) { + if (sort) doSort = true; + this.length += add.length; + if (at != null) { + splice.apply(this.models, [at, 0].concat(add)); + } else { + push.apply(this.models, add); + } + } + + // Silently sort the collection if appropriate. + if (doSort) this.sort({silent: true}); + + if (options.silent) return this; + + // Trigger `add` events. + for (i = 0, l = add.length; i < l; i++) { + (model = add[i]).trigger('add', model, this, options); + } + + // Trigger `sort` if the collection was sorted. + if (doSort) this.trigger('sort', this, options); + + return this; + }, + + // Remove a model, or a list of models from the set. + remove: function(models, options) { + models = _.isArray(models) ? models.slice() : [models]; + options || (options = {}); + var i, l, index, model; + for (i = 0, l = models.length; i < l; i++) { + model = this.get(models[i]); + if (!model) continue; + delete this._byId[model.id]; + delete this._byId[model.cid]; + index = this.indexOf(model); + this.models.splice(index, 1); + this.length--; + if (!options.silent) { + options.index = index; + model.trigger('remove', model, this, options); + } + this._removeReference(model); + } + return this; + }, + + // Add a model to the end of the collection. + push: function(model, options) { + model = this._prepareModel(model, options); + this.add(model, _.extend({at: this.length}, options)); + return model; + }, + + // Remove a model from the end of the collection. + pop: function(options) { + var model = this.at(this.length - 1); + this.remove(model, options); + return model; + }, + + // Add a model to the beginning of the collection. + unshift: function(model, options) { + model = this._prepareModel(model, options); + this.add(model, _.extend({at: 0}, options)); + return model; + }, + + // Remove a model from the beginning of the collection. + shift: function(options) { + var model = this.at(0); + this.remove(model, options); + return model; + }, + + // Slice out a sub-array of models from the collection. + slice: function(begin, end) { + return this.models.slice(begin, end); + }, + + // Get a model from the set by id. + get: function(obj) { + if (obj == null) return void 0; + this._idAttr || (this._idAttr = this.model.prototype.idAttribute); + return this._byId[obj.id || obj.cid || obj[this._idAttr] || obj]; + }, + + // Get the model at the given index. + at: function(index) { + return this.models[index]; + }, + + // Return models with matching attributes. Useful for simple cases of `filter`. + where: function(attrs) { + if (_.isEmpty(attrs)) return []; + return this.filter(function(model) { + for (var key in attrs) { + if (attrs[key] !== model.get(key)) return false; + } + return true; + }); + }, + + // Force the collection to re-sort itself. You don't need to call this under + // normal circumstances, as the set will maintain sort order as each item + // is added. + sort: function(options) { + if (!this.comparator) { + throw new Error('Cannot sort a set without a comparator'); + } + options || (options = {}); + + // Run sort based on type of `comparator`. + if (_.isString(this.comparator) || this.comparator.length === 1) { + this.models = this.sortBy(this.comparator, this); + } else { + this.models.sort(_.bind(this.comparator, this)); + } + + if (!options.silent) this.trigger('sort', this, options); + return this; + }, + + // Pluck an attribute from each model in the collection. + pluck: function(attr) { + return _.invoke(this.models, 'get', attr); + }, + + // Smartly update a collection with a change set of models, adding, + // removing, and merging as necessary. + update: function(models, options) { + options = _.extend({add: true, merge: true, remove: true}, options); + if (options.parse) models = this.parse(models, options); + var model, i, l, existing; + var add = [], remove = [], modelMap = {}; + + // Allow a single model (or no argument) to be passed. + if (!_.isArray(models)) models = models ? [models] : []; + + // Proxy to `add` for this case, no need to iterate... + if (options.add && !options.remove) return this.add(models, options); + + // Determine which models to add and merge, and which to remove. + for (i = 0, l = models.length; i < l; i++) { + model = models[i]; + existing = this.get(model); + if (options.remove && existing) modelMap[existing.cid] = true; + if ((options.add && !existing) || (options.merge && existing)) { + add.push(model); + } + } + if (options.remove) { + for (i = 0, l = this.models.length; i < l; i++) { + model = this.models[i]; + if (!modelMap[model.cid]) remove.push(model); + } + } + + // Remove models (if applicable) before we add and merge the rest. + if (remove.length) this.remove(remove, options); + if (add.length) this.add(add, options); + return this; + }, + + // When you have more items than you want to add or remove individually, + // you can reset the entire set with a new list of models, without firing + // any `add` or `remove` events. Fires `reset` when finished. + reset: function(models, options) { + options || (options = {}); + if (options.parse) models = this.parse(models, options); + for (var i = 0, l = this.models.length; i < l; i++) { + this._removeReference(this.models[i]); + } + options.previousModels = this.models.slice(); + this._reset(); + if (models) this.add(models, _.extend({silent: true}, options)); + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Fetch the default set of models for this collection, resetting the + // collection when they arrive. If `update: true` is passed, the response + // data will be passed through the `update` method instead of `reset`. + fetch: function(options) { + options = options ? _.clone(options) : {}; + if (options.parse === void 0) options.parse = true; + var success = options.success; + options.success = function(collection, resp, options) { + var method = options.update ? 'update' : 'reset'; + collection[method](resp, options); + if (success) success(collection, resp, options); + }; + return this.sync('read', this, options); + }, + + // Create a new instance of a model in this collection. Add the model to the + // collection immediately, unless `wait: true` is passed, in which case we + // wait for the server to agree. + create: function(model, options) { + options = options ? _.clone(options) : {}; + if (!(model = this._prepareModel(model, options))) return false; + if (!options.wait) this.add(model, options); + var collection = this; + var success = options.success; + options.success = function(model, resp, options) { + if (options.wait) collection.add(model, options); + if (success) success(model, resp, options); + }; + model.save(null, options); + return model; + }, + + // **parse** converts a response into a list of models to be added to the + // collection. The default implementation is just to pass it through. + parse: function(resp, options) { + return resp; + }, + + // Create a new collection with an identical list of models as this one. + clone: function() { + return new this.constructor(this.models); + }, + + // Reset all internal state. Called when the collection is reset. + _reset: function() { + this.length = 0; + this.models.length = 0; + this._byId = {}; + }, + + // Prepare a model or hash of attributes to be added to this collection. + _prepareModel: function(attrs, options) { + if (attrs instanceof Model) { + if (!attrs.collection) attrs.collection = this; + return attrs; + } + options || (options = {}); + options.collection = this; + var model = new this.model(attrs, options); + if (!model._validate(attrs, options)) return false; + return model; + }, + + // Internal method to remove a model's ties to a collection. + _removeReference: function(model) { + if (this === model.collection) delete model.collection; + model.off('all', this._onModelEvent, this); + }, + + // Internal method called every time a model in the set fires an event. + // Sets need to update their indexes when models change ids. All other + // events simply proxy through. "add" and "remove" events that originate + // in other collections are ignored. + _onModelEvent: function(event, model, collection, options) { + if ((event === 'add' || event === 'remove') && collection !== this) return; + if (event === 'destroy') this.remove(model, options); + if (model && event === 'change:' + model.idAttribute) { + delete this._byId[model.previous(model.idAttribute)]; + if (model.id != null) this._byId[model.id] = model; + } + this.trigger.apply(this, arguments); + }, + + sortedIndex: function (model, value, context) { + value || (value = this.comparator); + var iterator = _.isFunction(value) ? value : function(model) { + return model.get(value); + }; + return _.sortedIndex(this.models, model, iterator, context); + } + + }); + + // Underscore methods that we want to implement on the Collection. + var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', + 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', + 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', + 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', + 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', + 'isEmpty', 'chain']; + + // Mix in each Underscore method as a proxy to `Collection#models`. + _.each(methods, function(method) { + Collection.prototype[method] = function() { + var args = slice.call(arguments); + args.unshift(this.models); + return _[method].apply(_, args); + }; + }); + + // Underscore methods that take a property name as an argument. + var attributeMethods = ['groupBy', 'countBy', 'sortBy']; + + // Use attributes instead of properties. + _.each(attributeMethods, function(method) { + Collection.prototype[method] = function(value, context) { + var iterator = _.isFunction(value) ? value : function(model) { + return model.get(value); + }; + return _[method](this.models, iterator, context); + }; + }); + + // Backbone.Router + // --------------- + + // Routers map faux-URLs to actions, and fire events when routes are + // matched. Creating a new one sets its `routes` hash, if not set statically. + var Router = Backbone.Router = function(options) { + options || (options = {}); + if (options.routes) this.routes = options.routes; + this._bindRoutes(); + this.initialize.apply(this, arguments); + }; + + // Cached regular expressions for matching named param parts and splatted + // parts of route strings. + var optionalParam = /\((.*?)\)/g; + var namedParam = /(\(\?)?:\w+/g; + var splatParam = /\*\w+/g; + var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; + + // Set up all inheritable **Backbone.Router** properties and methods. + _.extend(Router.prototype, Events, { + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Manually bind a single named route to a callback. For example: + // + // this.route('search/:query/p:num', 'search', function(query, num) { + // ... + // }); + // + route: function(route, name, callback) { + if (!_.isRegExp(route)) route = this._routeToRegExp(route); + if (!callback) callback = this[name]; + Backbone.history.route(route, _.bind(function(fragment) { + var args = this._extractParameters(route, fragment); + callback && callback.apply(this, args); + this.trigger.apply(this, ['route:' + name].concat(args)); + this.trigger('route', name, args); + Backbone.history.trigger('route', this, name, args); + }, this)); + return this; + }, + + // Simple proxy to `Backbone.history` to save a fragment into the history. + navigate: function(fragment, options) { + Backbone.history.navigate(fragment, options); + return this; + }, + + // Bind all defined routes to `Backbone.history`. We have to reverse the + // order of the routes here to support behavior where the most general + // routes can be defined at the bottom of the route map. + _bindRoutes: function() { + if (!this.routes) return; + var route, routes = _.keys(this.routes); + while ((route = routes.pop()) != null) { + this.route(route, this.routes[route]); + } + }, + + // Convert a route string into a regular expression, suitable for matching + // against the current location hash. + _routeToRegExp: function(route) { + route = route.replace(escapeRegExp, '\\$&') + .replace(optionalParam, '(?:$1)?') + .replace(namedParam, function(match, optional){ + return optional ? match : '([^\/]+)'; + }) + .replace(splatParam, '(.*?)'); + return new RegExp('^' + route + '$'); + }, + + // Given a route, and a URL fragment that it matches, return the array of + // extracted parameters. + _extractParameters: function(route, fragment) { + return route.exec(fragment).slice(1); + } + + }); + + // Backbone.History + // ---------------- + + // Handles cross-browser history management, based on URL fragments. If the + // browser does not support `onhashchange`, falls back to polling. + var History = Backbone.History = function() { + this.handlers = []; + _.bindAll(this, 'checkUrl'); + + // Ensure that `History` can be used outside of the browser. + if (typeof window !== 'undefined') { + this.location = window.location; + this.history = window.history; + } + }; + + // Cached regex for stripping a leading hash/slash and trailing space. + var routeStripper = /^[#\/]|\s+$/g; + + // Cached regex for stripping leading and trailing slashes. + var rootStripper = /^\/+|\/+$/g; + + // Cached regex for detecting MSIE. + var isExplorer = /msie [\w.]+/; + + // Cached regex for removing a trailing slash. + var trailingSlash = /\/$/; + + // Has the history handling already been started? + History.started = false; + + // Set up all inheritable **Backbone.History** properties and methods. + _.extend(History.prototype, Events, { + + // The default interval to poll for hash changes, if necessary, is + // twenty times a second. + interval: 50, + + // Gets the true hash value. Cannot use location.hash directly due to bug + // in Firefox where location.hash will always be decoded. + getHash: function(window) { + var match = (window || this).location.href.match(/#(.*)$/); + return match ? match[1] : ''; + }, + + // Get the cross-browser normalized URL fragment, either from the URL, + // the hash, or the override. + getFragment: function(fragment, forcePushState) { + if (fragment == null) { + if (this._hasPushState || !this._wantsHashChange || forcePushState) { + fragment = this.location.pathname; + var root = this.root.replace(trailingSlash, ''); + if (!fragment.indexOf(root)) fragment = fragment.substr(root.length); + } else { + fragment = this.getHash(); + } + } + return fragment.replace(routeStripper, ''); + }, + + // Start the hash change handling, returning `true` if the current URL matches + // an existing route, and `false` otherwise. + start: function(options) { + if (History.started) throw new Error("Backbone.history has already been started"); + History.started = true; + + // Figure out the initial configuration. Do we need an iframe? + // Is pushState desired ... is it available? + this.options = _.extend({}, {root: '/'}, this.options, options); + this.root = this.options.root; + this._wantsHashChange = this.options.hashChange !== false; + this._wantsPushState = !!this.options.pushState; + this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); + var fragment = this.getFragment(); + var docMode = document.documentMode; + var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); + + // Normalize root to always include a leading and trailing slash. + this.root = ('/' + this.root + '/').replace(rootStripper, '/'); + + if (oldIE && this._wantsHashChange) { + this.iframe = Backbone.$('