diff options
51 files changed, 714 insertions, 317 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index b11154b352..ecbdfd51ed 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,3 +1,9 @@ +* Do not break params filtering on `nil` values. + + Fixes #12149. + + *Vasiliy Ermolovich* + * Separate Action View completely from Action Pack. *Łukasz Strzałkowski* diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb index ae600b1ebe..b495ab3f0f 100644 --- a/actionpack/lib/action_controller/metal/strong_parameters.rb +++ b/actionpack/lib/action_controller/metal/strong_parameters.rb @@ -421,7 +421,7 @@ module ActionController # Slicing filters out non-declared keys. slice(*filter.keys).each do |key, value| - return unless value + next unless value if filter[key] == EMPTY_ARRAY # Declaration { comment_ids: [] }. diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 600c49e442..db9c993590 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -433,10 +433,10 @@ module ActionDispatch # # match 'json_only', constraints: { format: 'json' } # - # class Blacklist + # class Whitelist # def matches?(request) request.remote_ip == '1.2.3.4' end # end - # match 'path', to: 'c#a', constraints: Blacklist.new + # match 'path', to: 'c#a', constraints: Whitelist.new # # See <tt>Scoping#constraints</tt> for more examples with its scope # equivalent. @@ -1067,18 +1067,18 @@ module ActionDispatch # a singular resource to map /profile (rather than /profile/:id) to # the show action: # - # resource :geocoder + # resource :profile # # creates six different routes in your application, all mapping to - # the +GeoCoders+ controller (note that the controller is named after + # the +Profiles+ controller (note that the controller is named after # the plural): # - # GET /geocoder/new - # POST /geocoder - # GET /geocoder - # GET /geocoder/edit - # PATCH/PUT /geocoder - # DELETE /geocoder + # GET /profile/new + # POST /profile + # GET /profile + # GET /profile/edit + # PATCH/PUT /profile + # DELETE /profile # # === Options # Takes same options as +resources+. diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb index d751e04e6a..68094f129f 100644 --- a/actionpack/lib/action_dispatch/routing/redirection.rb +++ b/actionpack/lib/action_dispatch/routing/redirection.rb @@ -17,7 +17,7 @@ module ActionDispatch def call(env) req = Request.new(env) - # If any of the path parameters has a invalid encoding then + # If any of the path parameters has an invalid encoding then # raise since it's likely to trigger errors further on. req.symbolized_path_parameters.each do |key, value| unless value.valid_encoding? diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 943fc15026..b8abdabca5 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -28,7 +28,7 @@ module ActionDispatch def call(env) params = env[PARAMETERS_KEY] - # If any of the path parameters has a invalid encoding then + # If any of the path parameters has an invalid encoding then # raise since it's likely to trigger errors further on. params.each do |key, value| next unless value.respond_to?(:valid_encoding?) diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index a67dff5436..57b45b8f7b 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -20,7 +20,7 @@ class FragmentCachingMetalTest < ActionController::TestCase @controller = FragmentCachingMetalTestController.new @controller.perform_caching = true @controller.cache_store = @store - @params = { controller: 'posts', action: 'index'} + @params = { controller: 'posts', action: 'index' } @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @controller.params = @params @@ -40,7 +40,7 @@ class CachingController < ActionController::Base end class FragmentCachingTestController < CachingController - def some_action; end; + def some_action; end end class FragmentCachingTest < ActionController::TestCase diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb index 437da43d9b..84e007b5d0 100644 --- a/actionpack/test/controller/parameters/parameters_permit_test.rb +++ b/actionpack/test/controller/parameters/parameters_permit_test.rb @@ -107,6 +107,15 @@ class ParametersPermitTest < ActiveSupport::TestCase assert_equal [], permitted[:id] end + test 'do not break params filtering on nil values' do + params = ActionController::Parameters.new(a: 1, b: [1, 2, 3], c: nil) + + permitted = params.permit(:a, c: [], b: []) + assert_equal 1, permitted[:a] + assert_equal [1, 2, 3], permitted[:b] + assert_equal nil, permitted[:c] + end + test 'key to empty array: arrays of permitted scalars pass' do [['foo'], [1], ['foo', 'bar'], [1, 2, 3]].each do |array| params = ActionController::Parameters.new(id: array) diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index 6240dc6ac6..53142a835e 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,14 @@ +* Fix `form_for` when both `namespace` and `as` options are present + + `as` option no longer overwrites `namespace` option when generating + html id attribute of the form element + + *Adam Niedzielski* + +* Fix `excerpt` when `:separator` is `nil`. + + *Paul Nikitochkin* + * Only cache template digests if `config.cache_template_loading` id true. *Josh Lauer*, *Justin Ridgewell* diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb index 8a4830d887..ead7871fc5 100644 --- a/actionview/lib/action_view/helpers/form_helper.rb +++ b/actionview/lib/action_view/helpers/form_helper.rb @@ -442,10 +442,11 @@ module ActionView object = convert_to_model(object) as = options[:as] + namespace = options[:namespace] action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :patch] : [:new, :post] options[:html].reverse_merge!( class: as ? "#{action}_#{as}" : dom_class(object, action), - id: as ? "#{action}_#{as}" : [options[:namespace], dom_id(object, action)].compact.join("_").presence, + id: (as ? [namespace, action, as] : [namespace, dom_id(object, action)]).compact.join("_").presence, method: method ) diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb index 3fc64fa8a5..c23d605c5f 100644 --- a/actionview/lib/action_view/helpers/text_helper.rb +++ b/actionview/lib/action_view/helpers/text_helper.rb @@ -150,7 +150,7 @@ module ActionView def excerpt(text, phrase, options = {}) return unless text && phrase - separator = options.fetch(:separator, "") + separator = options[:separator] || '' phrase = Regexp.escape(phrase) regex = /#{phrase}/i @@ -171,7 +171,8 @@ module ActionView prefix, first_part = cut_excerpt_part(:first, first_part, separator, options) postfix, second_part = cut_excerpt_part(:second, second_part, separator, options) - prefix + (first_part + separator + phrase + separator + second_part).strip + postfix + affix = [first_part, separator, phrase, separator, second_part].join.strip + [prefix, affix, postfix].join end # Attempts to pluralize the +singular+ word unless +count+ is 1. If diff --git a/actionview/test/template/form_collections_helper_test.rb b/actionview/test/template/form_collections_helper_test.rb index 5b8afddc41..b56847396d 100644 --- a/actionview/test/template/form_collections_helper_test.rb +++ b/actionview/test/template/form_collections_helper_test.rb @@ -17,14 +17,14 @@ class FormCollectionsHelperTest < ActionView::TestCase end # COLLECTION RADIO BUTTONS - test 'collection radio accepts a collection and generate inputs from value method' do + test 'collection radio accepts a collection and generates inputs from value method' do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s assert_select 'input[type=radio][value=true]#user_active_true' assert_select 'input[type=radio][value=false]#user_active_false' end - test 'collection radio accepts a collection and generate inputs from label method' do + test 'collection radio accepts a collection and generates inputs from label method' do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s assert_select 'label[for=user_active_true]', 'true' diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb index 8cca43d7ca..944884c9dd 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -1681,6 +1681,18 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_form_for_with_namespace_and_as_option + form_for(@post, namespace: 'namespace', as: 'custom_name') do |f| + concat f.text_field(:title) + end + + expected = whole_form('/posts/123', 'namespace_edit_custom_name', 'edit_custom_name', method: 'patch') do + "<input id='namespace_custom_name_title' name='custom_name[title]' type='text' value='Hello World' />" + end + + assert_dom_equal expected, output_buffer + end + def test_two_form_for_with_namespace form_for(@post, namespace: 'namespace_1') do |f| concat f.label(:title) diff --git a/actionview/test/template/text_helper_test.rb b/actionview/test/template/text_helper_test.rb index 1b2234f4e2..c2999fcb85 100644 --- a/actionview/test/template/text_helper_test.rb +++ b/actionview/test/template/text_helper_test.rb @@ -314,6 +314,9 @@ class TextHelperTest < ActionView::TestCase options = { :separator => "\n", :radius => 1 } assert_equal("...very\nvery long\nstring", excerpt("my very\nvery\nvery long\nstring", 'long', options)) + + assert_equal excerpt('This is a beautiful morning', 'a'), + excerpt('This is a beautiful morning', 'a', separator: nil) end def test_word_wrap diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 691c684d76..0cf50c512e 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,22 @@ +* Deprecate the delegation of Array bang methods for associations. + To use them, instead first call `#to_a` on the association to access the + array to be acted on. + + *Ben Woosley* + +* `CollectionAssociation#first`/`#last` (e.g. `has_many`) use a `LIMIT`ed + query to fetch results rather than loading the entire collection. + + *Lann Martin* + +* Make possible to run SQLite rake tasks without the `Rails` constant defined. + + *Damien Mathieu* + +* Allow Relation#from to accept other relations with bind values. + + *Ryan Wallace* + * Fix inserts with prepared statements disabled. Fixes #12023. diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 8744a57355..e32c0b0377 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -528,15 +528,13 @@ module ActiveRecord # * target already loaded # * owner is new record # * target contains new or changed record(s) - # * the first arg is an integer (which indicates the number of records to be returned) def fetch_first_or_last_using_find?(args) if args.first.is_a?(Hash) true else !(loaded? || owner.new_record? || - target.any? { |record| record.new_record? || record.changed? } || - args.first.kind_of?(Integer)) + target.any? { |record| record.new_record? || record.changed? }) end end diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index 269f9f975b..eef08aea88 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -46,6 +46,7 @@ module ActiveRecord ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration ActiveRecord::Tasks::DatabaseTasks.migrations_paths = Rails.application.paths['db/migrate'].to_a ActiveRecord::Tasks::DatabaseTasks.fixtures_path = File.join Rails.root, 'test', 'fixtures' + ActiveRecord::Tasks::DatabaseTasks.root = Rails.root if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH) if engine.paths['db/migrate'].existent diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb index e28938f9d0..1e15bddcdf 100644 --- a/activerecord/lib/active_record/relation/delegation.rb +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -1,4 +1,5 @@ require 'active_support/concern' +require 'active_support/deprecation' module ActiveRecord module Delegation # :nodoc: @@ -83,7 +84,7 @@ module ActiveRecord if @klass.respond_to?(method) self.class.delegate_to_scoped_klass(method) scoping { @klass.send(method, *args, &block) } - elsif Array.method_defined?(method) + elsif array_delegable?(method) self.class.delegate method, :to => :to_a to_a.send(method, *args, &block) elsif arel.respond_to?(method) @@ -108,17 +109,27 @@ module ActiveRecord end def respond_to?(method, include_private = false) - super || Array.method_defined?(method) || + super || array_delegable?(method) || @klass.respond_to?(method, include_private) || arel.respond_to?(method, include_private) end protected + def array_delegable?(method) + defined = Array.method_defined?(method) + if defined && method.to_s.ends_with?('!') + ActiveSupport::Deprecation.warn( + "Association will no longer delegate #{method} to #to_a as of Rails 4.2. You instead must first call #to_a on the association to expose the array to be acted on." + ) + end + defined + end + def method_missing(method, *args, &block) if @klass.respond_to?(method) scoping { @klass.send(method, *args, &block) } - elsif Array.method_defined?(method) + elsif array_delegable?(method) to_a.send(method, *args, &block) elsif arel.respond_to?(method) arel.send(method, *args, &block) diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 1c6ea94c0b..9916c597ee 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -915,6 +915,7 @@ module ActiveRecord case opts when Relation name ||= 'subquery' + self.bind_values = opts.bind_values + self.bind_values opts.arel.as(name.to_s) else opts diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index 5ff594fdca..b91bbeb412 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -23,6 +23,7 @@ module ActiveRecord # * +fixtures_path+: a path to fixtures directory. # * +migrations_paths+: a list of paths to directories with migrations. # * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method. + # * +root+: a path to the root of the application. # # Example usage of +DatabaseTasks+ outside Rails could look as such: # @@ -37,7 +38,7 @@ module ActiveRecord attr_writer :current_config attr_accessor :database_configuration, :migrations_paths, :seed_loader, :db_dir, - :fixtures_path, :env + :fixtures_path, :env, :root LOCAL_HOSTS = ['127.0.0.1', 'localhost'] diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb index de8b16627e..5688931db2 100644 --- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb @@ -3,7 +3,7 @@ module ActiveRecord class SQLiteDatabaseTasks # :nodoc: delegate :connection, :establish_connection, to: ActiveRecord::Base - def initialize(configuration, root = Rails.root) + def initialize(configuration, root = ActiveRecord::Tasks::DatabaseTasks.root) @configuration, @root = configuration, root end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 4c0fa88917..ebeead0dc2 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1414,15 +1414,17 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end end - def test_calling_first_or_last_with_integer_on_association_should_load_association + def test_calling_first_or_last_with_integer_on_association_should_not_load_association firm = companies(:first_firm) + firm.clients.create(:name => 'Foo') + assert !firm.clients.loaded? - assert_queries 1 do + assert_queries 2 do firm.clients.first(2) firm.clients.last(2) end - assert firm.clients.loaded? + assert !firm.clients.loaded? end def test_calling_many_should_count_instead_of_loading_association diff --git a/activerecord/test/cases/relation/delegation_test.rb b/activerecord/test/cases/relation/delegation_test.rb new file mode 100644 index 0000000000..71ade0bcc2 --- /dev/null +++ b/activerecord/test/cases/relation/delegation_test.rb @@ -0,0 +1,97 @@ +require 'cases/helper' +require 'models/post' +require 'models/comment' + +module ActiveRecord + class DelegationTest < ActiveRecord::TestCase + fixtures :posts + + def assert_responds(target, method) + assert target.respond_to?(method) + assert_nothing_raised do + case target.to_a.method(method).arity + when 0 + target.send(method) + when -1 + if method == :shuffle! + target.send(method) + else + target.send(method, 1) + end + else + raise NotImplementedError + end + end + end + end + + class DelegationAssociationTest < DelegationTest + def target + Post.first.comments + end + + [:map, :collect].each do |method| + test "##{method} is delgated" do + assert_responds(target, method) + assert_equal(target.pluck(:body), target.send(method) {|post| post.body }) + end + + test "##{method}! is not delgated" do + assert_deprecated do + assert_responds(target, "#{method}!") + end + end + end + + [:compact!, :flatten!, :reject!, :reverse!, :rotate!, + :shuffle!, :slice!, :sort!, :sort_by!].each do |method| + test "##{method} delegation is deprecated" do + assert_deprecated do + assert_responds(target, method) + end + end + end + + [:select!, :uniq!].each do |method| + test "##{method} is implemented" do + assert_responds(target, method) + end + end + end + + class DelegationRelationTest < DelegationTest + def target + Comment.where.not(body: nil) + end + + [:map, :collect].each do |method| + test "##{method} is delgated" do + assert_responds(target, method) + assert_equal(target.pluck(:body), target.send(method) {|post| post.body }) + end + + test "##{method}! is not delgated" do + assert_deprecated do + assert_responds(target, "#{method}!") + end + end + end + + [:compact!, :flatten!, :reject!, :reverse!, :rotate!, + :shuffle!, :slice!, :sort!, :sort_by!].each do |method| + test "##{method} delegation is deprecated" do + assert_deprecated do + assert_responds(target, method) + end + end + end + + [:select!, :uniq!].each do |method| + test "##{method} is triggers an immutable error" do + assert_raises ActiveRecord::ImmutableRelation do + assert_responds(target, method) + end + end + end + end +end diff --git a/activerecord/test/cases/relation/mutation_test.rb b/activerecord/test/cases/relation/mutation_test.rb new file mode 100644 index 0000000000..020fb24afa --- /dev/null +++ b/activerecord/test/cases/relation/mutation_test.rb @@ -0,0 +1,148 @@ +require 'cases/helper' +require 'models/post' + +module ActiveRecord + class RelationMutationTest < ActiveSupport::TestCase + class FakeKlass < Struct.new(:table_name, :name) + extend ActiveRecord::Delegation::DelegateCache + inherited self + + def arel_table + Post.arel_table + end + + def connection + Post.connection + end + + def relation_delegate_class(klass) + self.class.relation_delegate_class(klass) + end + end + + def relation + @relation ||= Relation.new FakeKlass.new('posts'), :b + end + + (Relation::MULTI_VALUE_METHODS - [:references, :extending, :order]).each do |method| + test "##{method}!" do + assert relation.public_send("#{method}!", :foo).equal?(relation) + assert_equal [:foo], relation.public_send("#{method}_values") + end + end + + test '#order!' do + assert relation.order!('name ASC').equal?(relation) + assert_equal ['name ASC'], relation.order_values + end + + test '#order! with symbol prepends the table name' do + assert relation.order!(:name).equal?(relation) + node = relation.order_values.first + assert node.ascending? + assert_equal :name, node.expr.name + assert_equal "posts", node.expr.relation.name + end + + test '#order! on non-string does not attempt regexp match for references' do + obj = Object.new + obj.expects(:=~).never + assert relation.order!(obj) + assert_equal [obj], relation.order_values + end + + test '#references!' do + assert relation.references!(:foo).equal?(relation) + assert relation.references_values.include?('foo') + end + + test 'extending!' do + mod, mod2 = Module.new, Module.new + + assert relation.extending!(mod).equal?(relation) + assert_equal [mod], relation.extending_values + assert relation.is_a?(mod) + + relation.extending!(mod2) + assert_equal [mod, mod2], relation.extending_values + end + + test 'extending! with empty args' do + relation.extending! + assert_equal [], relation.extending_values + end + + (Relation::SINGLE_VALUE_METHODS - [:from, :lock, :reordering, :reverse_order, :create_with]).each do |method| + test "##{method}!" do + assert relation.public_send("#{method}!", :foo).equal?(relation) + assert_equal :foo, relation.public_send("#{method}_value") + end + end + + test '#from!' do + assert relation.from!('foo').equal?(relation) + assert_equal ['foo', nil], relation.from_value + end + + test '#lock!' do + assert relation.lock!('foo').equal?(relation) + assert_equal 'foo', relation.lock_value + end + + test '#reorder!' do + relation = self.relation.order('foo') + + assert relation.reorder!('bar').equal?(relation) + assert_equal ['bar'], relation.order_values + assert relation.reordering_value + end + + test '#reorder! with symbol prepends the table name' do + assert relation.reorder!(:name).equal?(relation) + node = relation.order_values.first + + assert node.ascending? + assert_equal :name, node.expr.name + assert_equal "posts", node.expr.relation.name + end + + test 'reverse_order!' do + assert relation.reverse_order!.equal?(relation) + assert relation.reverse_order_value + relation.reverse_order! + assert !relation.reverse_order_value + end + + test 'create_with!' do + assert relation.create_with!(foo: 'bar').equal?(relation) + assert_equal({foo: 'bar'}, relation.create_with_value) + end + + test 'test_merge!' do + assert relation.merge!(where: :foo).equal?(relation) + assert_equal [:foo], relation.where_values + end + + test 'merge with a proc' do + assert_equal [:foo], relation.merge(-> { where(:foo) }).where_values + end + + test 'none!' do + assert relation.none!.equal?(relation) + assert_equal [NullRelation], relation.extending_values + assert relation.is_a?(NullRelation) + end + + test 'distinct!' do + relation.distinct! :foo + assert_equal :foo, relation.distinct_value + assert_equal :foo, relation.uniq_value # deprecated access + end + + test 'uniq! was replaced by distinct!' do + relation.uniq! :foo + assert_equal :foo, relation.distinct_value + assert_equal :foo, relation.uniq_value # deprecated access + end + end +end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index e77de19ac3..70d113fb39 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -223,148 +223,4 @@ module ActiveRecord end end - - class RelationMutationTest < ActiveSupport::TestCase - class FakeKlass < Struct.new(:table_name, :name) - extend ActiveRecord::Delegation::DelegateCache - inherited self - - def arel_table - Post.arel_table - end - - def connection - Post.connection - end - - def relation_delegate_class(klass) - self.class.relation_delegate_class(klass) - end - end - - def relation - @relation ||= Relation.new FakeKlass.new('posts'), :b - end - - (Relation::MULTI_VALUE_METHODS - [:references, :extending, :order]).each do |method| - test "##{method}!" do - assert relation.public_send("#{method}!", :foo).equal?(relation) - assert_equal [:foo], relation.public_send("#{method}_values") - end - end - - test "#order!" do - assert relation.order!('name ASC').equal?(relation) - assert_equal ['name ASC'], relation.order_values - end - - test "#order! with symbol prepends the table name" do - assert relation.order!(:name).equal?(relation) - node = relation.order_values.first - assert node.ascending? - assert_equal :name, node.expr.name - assert_equal "posts", node.expr.relation.name - end - - test "#order! on non-string does not attempt regexp match for references" do - obj = Object.new - obj.expects(:=~).never - assert relation.order!(obj) - assert_equal [obj], relation.order_values - end - - test '#references!' do - assert relation.references!(:foo).equal?(relation) - assert relation.references_values.include?('foo') - end - - test 'extending!' do - mod, mod2 = Module.new, Module.new - - assert relation.extending!(mod).equal?(relation) - assert_equal [mod], relation.extending_values - assert relation.is_a?(mod) - - relation.extending!(mod2) - assert_equal [mod, mod2], relation.extending_values - end - - test 'extending! with empty args' do - relation.extending! - assert_equal [], relation.extending_values - end - - (Relation::SINGLE_VALUE_METHODS - [:from, :lock, :reordering, :reverse_order, :create_with]).each do |method| - test "##{method}!" do - assert relation.public_send("#{method}!", :foo).equal?(relation) - assert_equal :foo, relation.public_send("#{method}_value") - end - end - - test '#from!' do - assert relation.from!('foo').equal?(relation) - assert_equal ['foo', nil], relation.from_value - end - - test '#lock!' do - assert relation.lock!('foo').equal?(relation) - assert_equal 'foo', relation.lock_value - end - - test '#reorder!' do - relation = self.relation.order('foo') - - assert relation.reorder!('bar').equal?(relation) - assert_equal ['bar'], relation.order_values - assert relation.reordering_value - end - - test '#reorder! with symbol prepends the table name' do - assert relation.reorder!(:name).equal?(relation) - node = relation.order_values.first - - assert node.ascending? - assert_equal :name, node.expr.name - assert_equal "posts", node.expr.relation.name - end - - test 'reverse_order!' do - assert relation.reverse_order!.equal?(relation) - assert relation.reverse_order_value - relation.reverse_order! - assert !relation.reverse_order_value - end - - test 'create_with!' do - assert relation.create_with!(foo: 'bar').equal?(relation) - assert_equal({foo: 'bar'}, relation.create_with_value) - end - - def test_merge! - assert relation.merge!(where: :foo).equal?(relation) - assert_equal [:foo], relation.where_values - end - - test 'merge with a proc' do - assert_equal [:foo], relation.merge(-> { where(:foo) }).where_values - end - - test 'none!' do - assert relation.none!.equal?(relation) - assert_equal [NullRelation], relation.extending_values - assert relation.is_a?(NullRelation) - end - - test "distinct!" do - relation.distinct! :foo - assert_equal :foo, relation.distinct_value - assert_equal :foo, relation.uniq_value # deprecated access - end - - test "uniq! was replaced by distinct!" do - relation.uniq! :foo - assert_equal :foo, relation.distinct_value - assert_equal :foo, relation.uniq_value # deprecated access - end - end end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index b3ca45c4c8..88a12c61df 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -139,6 +139,13 @@ class RelationTest < ActiveRecord::TestCase assert_equal relation.to_a, Topic.select('a.*').from(relation, :a).to_a end + def test_finding_with_subquery_with_binds + relation = Post.first.comments + assert_equal relation.to_a, Comment.select('*').from(relation).to_a + assert_equal relation.to_a, Comment.select('subquery.*').from(relation).to_a + assert_equal relation.to_a, Comment.select('a.*').from(relation, :a).to_a + end + def test_finding_with_conditions assert_equal ["David"], Author.where(:name => 'David').map(&:name) assert_equal ['Mary'], Author.where(["name = ?", 'Mary']).map(&:name) diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index 24c5f330a1..7fe065ee88 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -243,10 +243,7 @@ class SerializedAttributeTest < ActiveRecord::TestCase myobj = MyObject.new('value1', 'value2') Topic.create(content: myobj) Topic.create(content: myobj) - - Topic.all.each do |topic| - type = Topic.column_types["content"] - assert !type.instance_variable_get("@column").is_a?(ActiveRecord::AttributeMethods::Serialization::Type) - end + type = Topic.column_types["content"] + assert !type.instance_variable_get("@column").is_a?(ActiveRecord::AttributeMethods::Serialization::Type) end end diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index f15297f279..9ab81c73c8 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,13 @@ +* Add `Date#middle_of_day`, `DateTime#middle_of_day` and `Time#middle_of_day` methods. + + Also added `midday`, `noon`, `at_midday`, `at_noon` and `at_middle_of_day` as aliases. + + *Anatoli Makarevich* + +* Fix ActiveSupport::Cache::FileStore#cleanup to no longer rely on missing each_key method. + + *Murray Steele* + * Ensure that autoloaded constants in all-caps nestings are marked as autoloaded. diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb index 472f23c1c5..10d39463ec 100644 --- a/activesupport/lib/active_support/cache/file_store.rb +++ b/activesupport/lib/active_support/cache/file_store.rb @@ -33,7 +33,8 @@ module ActiveSupport # Premptively iterates through all stored keys and removes the ones which have expired. def cleanup(options = nil) options = merged_options(options) - each_key(options) do |key| + search_dir(cache_path) do |fname| + key = file_path_key(fname) entry = read_entry(key, options) delete_entry(key, options) if entry && entry.expired? end diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb index 2533ff43e1..21de09c1cc 100644 --- a/activesupport/lib/active_support/json/decoding.rb +++ b/activesupport/lib/active_support/json/decoding.rb @@ -14,7 +14,7 @@ module ActiveSupport # ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}") # => {"team" => "rails", "players" => "36"} def decode(json, options = {}) - data = ::JSON.parse(json, options.merge(create_additions: false)) + data = ::JSON.parse(json, options.merge(create_additions: false, quirks_mode: true)) if ActiveSupport.parse_json_times convert_dates_from(data) else diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index df570d485a..16d087ab9d 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -709,6 +709,18 @@ class FileStoreTest < ActiveSupport::TestCase @cache.send(:read_entry, "winston", {}) assert @buffer.string.present? end + + def test_cleanup_removes_all_expired_entries + time = Time.now + @cache.write('foo', 'bar', expires_in: 10) + @cache.write('baz', 'qux') + @cache.write('quux', 'corge', expires_in: 20) + Time.stubs(:now).returns(time + 15) + @cache.cleanup + assert_not @cache.exist?('foo') + assert @cache.exist?('baz') + assert @cache.exist?('quux') + end end class MemoryStoreTest < ActiveSupport::TestCase diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 3ec9b06d6a..e9780b36e4 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -59,7 +59,16 @@ class TestJSONDecoding < ActiveSupport::TestCase %q({"a":"\n"}) => {"a"=>"\n"}, %q({"a":"\u000a"}) => {"a"=>"\n"}, %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"}, - %q({"json_class":"TestJSONDecoding::Foo"}) => {"json_class"=>"TestJSONDecoding::Foo"} + # prevent json unmarshalling + %q({"json_class":"TestJSONDecoding::Foo"}) => {"json_class"=>"TestJSONDecoding::Foo"}, + # json "fragments" - these are invalid JSON, but ActionPack relies on this + %q("a string") => "a string", + %q(1.1) => 1.1, + %q(1) => 1, + %q(-1) => -1, + %q(true) => true, + %q(false) => false, + %q(null) => nil } TESTS.each_with_index do |(json, expected), index| @@ -83,7 +92,10 @@ class TestJSONDecoding < ActiveSupport::TestCase end def test_failed_json_decoding + assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%(undefined)) } + assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({a: 1})) } assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({: 1})) } + assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%()) } end def test_cannot_force_json_unmarshalling diff --git a/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md index 76fcca98f8..babdc5050e 100644 --- a/guides/source/3_2_release_notes.md +++ b/guides/source/3_2_release_notes.md @@ -227,7 +227,7 @@ Action Pack #### Deprecations -* Deprecated implied layout lookup in controllers whose parent had a explicit layout set: +* Deprecated implied layout lookup in controllers whose parent had an explicit layout set: ```ruby class ApplicationController @@ -254,7 +254,7 @@ Action Pack * Added `ActionDispatch::RequestId` middleware that'll make a unique X-Request-Id header available to the response and enables the `ActionDispatch::Request#uuid` method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog. -* The `ShowExceptions` middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in `env["action_dispatch.exception"]` and with the `PATH_INFO` rewritten to the status code. +* The `ShowExceptions` middleware now accepts an exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in `env["action_dispatch.exception"]` and with the `PATH_INFO` rewritten to the status code. * Allow rescue responses to be configured through a railtie as in `config.action_dispatch.rescue_responses`. diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index 072be49412..c4ca1e921f 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -116,7 +116,7 @@ Documentation Railties -------- -Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railties/CHANGELOG.md) for detailed changes. +Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/railties/CHANGELOG.md) for detailed changes. ### Notable changes @@ -139,7 +139,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railt Action Mailer ------------- -Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actionmailer/CHANGELOG.md) for detailed changes. +Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/actionmailer/CHANGELOG.md) for detailed changes. ### Notable changes @@ -148,7 +148,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actio Active Model ------------ -Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activemodel/CHANGELOG.md) for detailed changes. +Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/activemodel/CHANGELOG.md) for detailed changes. ### Notable changes @@ -161,7 +161,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ Active Support -------------- -Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activesupport/CHANGELOG.md) for detailed changes. +Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/activesupport/CHANGELOG.md) for detailed changes. ### Notable changes @@ -203,7 +203,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ Action Pack ----------- -Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actionpack/CHANGELOG.md) for detailed changes. +Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/actionpack/CHANGELOG.md) for detailed changes. ### Notable changes @@ -215,7 +215,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actio Active Record ------------- -Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activerecord/CHANGELOG.md) for detailed changes. +Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/activerecord/CHANGELOG.md) for detailed changes. ### Notable changes diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index a80c3b6c8e..ad08cb01f7 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -86,7 +86,7 @@ by underscores. Examples: | ------------- | -------------- | | `Post` | `posts` | | `LineItem` | `line_items` | -| `Deer` | `deer` | +| `Deer` | `deers` | | `Mouse` | `mice` | | `Person` | `people` | diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 5aa935a155..28013beeae 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -943,7 +943,7 @@ WARNING: This method only works with `INNER JOIN`. Active Record lets you use the names of the [associations](association_basics.html) defined on the model as a shortcut for specifying `JOIN` clause for those associations when using the `joins` method. -For example, consider the following `Category`, `Post`, `Comments` and `Guest` models: +For example, consider the following `Category`, `Post`, `Comment`, `Guest` and `Tag` models: ```ruby class Category < ActiveRecord::Base @@ -1536,18 +1536,21 @@ Person.ids Existence of Objects -------------------- -If you simply want to check for the existence of the object there's a method called `exists?`. This method will query the database using the same query as `find`, but instead of returning an object or collection of objects it will return either `true` or `false`. +If you simply want to check for the existence of the object there's a method called `exists?`. +This method will query the database using the same query as `find`, but instead of returning an +object or collection of objects it will return either `true` or `false`. ```ruby Client.exists?(1) ``` -The `exists?` method also takes multiple ids, but the catch is that it will return true if any one of those records exists. +The `exists?` method also takes multiple values, but the catch is that it will return `true` if any +one of those records exists. ```ruby -Client.exists?(1,2,3) +Client.exists?(id: [1,2,3]) # or -Client.exists?([1,2,3]) +Client.exists?(name: ['John', 'Sergei']) ``` It's even possible to use `exists?` without any arguments on a model or a relation. @@ -1556,7 +1559,8 @@ It's even possible to use `exists?` without any arguments on a model or a relati Client.where(first_name: 'Ryan').exists? ``` -The above returns `true` if there is at least one client with the `first_name` 'Ryan' and `false` otherwise. +The above returns `true` if there is at least one client with the `first_name` 'Ryan' and `false` +otherwise. ```ruby Client.exists? diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index fa32fc898e..e6b849e4c9 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -420,7 +420,7 @@ NOTE: Defined in `active_support/core_ext/object/with_options.rb`. ### JSON support -Active Support provides a better implemention of `to_json` than the +json+ gem ordinarily provides for Ruby objects. This is because some classes, like +Hash+ and +OrderedHash+ needs special handling in order to provide a proper JSON representation. +Active Support provides a better implementation of `to_json` than the +json+ gem ordinarily provides for Ruby objects. This is because some classes, like +Hash+ and +OrderedHash+ needs special handling in order to provide a proper JSON representation. Active Support also provides an implementation of `as_json` for the <tt>Process::Status</tt> class. diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index d3d25f4d4e..b0ab88bf59 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -327,7 +327,7 @@ class ProductsController < ApplicationController end ``` -Instead of a options hash, you can also simply pass in a model, Rails will use the `updated_at` and `cache_key` methods for setting `last_modified` and `etag`: +Instead of an options hash, you can also simply pass in a model, Rails will use the `updated_at` and `cache_key` methods for setting `last_modified` and `etag`: ```ruby class ProductsController < ApplicationController diff --git a/guides/source/command_line.md b/guides/source/command_line.md index f11e08a0c1..6f792be8ae 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -493,7 +493,9 @@ The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp` ### Custom Rake Tasks -Custom rake tasks have a `.rake` extension and are placed in `Rails.root/lib/tasks`. +Custom rake tasks have a `.rake` extension and are placed in +`Rails.root/lib/tasks`. You can create these custom rake tasks with the +`bin/rails generate task` command. ```ruby desc "I am short, but comprehensive description for my cool task" diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 3cf5cdd71f..5f170474ee 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -103,7 +103,7 @@ numbers. New applications filter out passwords by adding the following `config.f * `config.force_ssl` forces all requests to be under HTTPS protocol by using `ActionDispatch::SSL` middleware. -* `config.log_formatter` defines the formatter of the Rails logger. This option defaults to a instance of `ActiveSupport::Logger::SimpleFormatter` for all modes except production, where it defaults to `Logger::Formatter`. +* `config.log_formatter` defines the formatter of the Rails logger. This option defaults to an instance of `ActiveSupport::Logger::SimpleFormatter` for all modes except production, where it defaults to `Logger::Formatter`. * `config.log_level` defines the verbosity of the Rails logger. This option defaults to `:debug` for all modes except production, where it defaults to `:info`. diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index fc6b2f992a..b2b08c82c6 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -219,7 +219,7 @@ When working with documentation, please take into account the [API Documentation NOTE: As explained earlier, ordinary code patches should have proper documentation coverage. Docrails is only used for isolated documentation improvements. -NOTE: To help our CI servers you can add [ci skip] to your documentation commit message to skip build on that commit. Please remember to use it for commits containing only documentation changes. +NOTE: To help our CI servers you should add [ci skip] to your documentation commit message to skip build on that commit. Please remember to use it for commits containing only documentation changes. WARNING: Docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails. Also, CHANGELOGs should never be edited in docrails. diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index 3099ccae97..226137c89a 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -233,7 +233,7 @@ only evaluated if the output level is the same or included in the allowed level (i.e. lazy loading). The same code rewritten would be: ```ruby -logger.debug {"Person attibutes hash: #{@person.attributes.inspect}"} +logger.debug {"Person attributes hash: #{@person.attributes.inspect}"} ``` The contents of the block, and therefore the string interpolation, is only diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md index 39852cb00a..0287b3df73 100644 --- a/guides/source/form_helpers.md +++ b/guides/source/form_helpers.md @@ -67,7 +67,7 @@ To create this form you will use `form_tag`, `label_tag`, `text_field_tag`, and This will generate the following HTML: ```html -<form accept-charset="UTF-8" action="/search" method="get"> +<form accept-charset="UTF-8" action="/search" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div> <label for="q">Search for:</label> <input id="q" name="q" type="text" /> <input name="commit" type="submit" value="Search" /> diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 81e57aee34..e5bc5ef038 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -54,9 +54,11 @@ learned elsewhere, you may have a less happy experience. The Rails philosophy includes two major guiding principles: -* DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing. -* Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to -do it, rather than requiring you to specify every little thing through endless configuration files. +* DRY - "Don't Repeat Yourself" - suggests that writing the same code over and + over again is a bad thing. +* Convention Over Configuration - means that Rails makes assumptions about what + you want to do and how you're going to do it, rather than requiring you to + specify every little thing through endless configuration files. Creating a New Rails Project ---------------------------- @@ -94,10 +96,11 @@ $ gem install rails ``` TIP. A number of tools exist to help you quickly install Ruby and Ruby -on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org), while Mac OS X users can use -[Rails One Click](http://railsoneclick.com). +on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org), +while Mac OS X users can use [Rails One Click](http://railsoneclick.com). -To verify that you have everything installed correctly, you should be able to run the following: +To verify that you have everything installed correctly, you should be able to +run the following: ```bash $ rails --version @@ -107,29 +110,38 @@ If it says something like "Rails 4.0.0", you are ready to continue. ### Creating the Blog Application -Rails comes with a number of scripts called generators that are designed to make your development life easier by creating everything that's necessary to start working on a particular task. One of these is the new application generator, which will provide you with the foundation of a fresh Rails application so that you don't have to write it yourself. +Rails comes with a number of scripts called generators that are designed to make +your development life easier by creating everything that's necessary to start +working on a particular task. One of these is the new application generator, +which will provide you with the foundation of a fresh Rails application so that +you don't have to write it yourself. -To use this generator, open a terminal, navigate to a directory where you have rights to create files, and type: +To use this generator, open a terminal, navigate to a directory where you have +rights to create files, and type: ```bash $ rails new blog ``` -This will create a Rails application called Blog in a directory called blog and install the gem dependencies that are already mentioned in `Gemfile` using `bundle install`. +This will create a Rails application called Blog in a directory called blog and +install the gem dependencies that are already mentioned in `Gemfile` using +`bundle install`. -TIP: You can see all of the command line options that the Rails -application builder accepts by running `rails new -h`. +TIP: You can see all of the command line options that the Rails application +builder accepts by running `rails new -h`. -After you create the blog application, switch to its folder to continue work directly in that application: +After you create the blog application, switch to its folder to continue work +directly in that application: ```bash $ cd blog ``` -The `rails new blog` command we ran above created a folder in your -working directory called `blog`. The `blog` directory has a number of -auto-generated files and folders that make up the structure of a Rails -application. Most of the work in this tutorial will happen in the `app/` folder, but here's a basic rundown on the function of each of the files and folders that Rails created by default: +The `rails new blog` command we ran above created a folder in your working +directory called `blog`. The `blog` directory has a number of auto-generated +files and folders that make up the structure of a Rails application. Most of the +work in this tutorial will happen in the `app/` folder, but here's a basic +rundown on the function of each of the files and folders that Rails created by default: | File/Folder | Purpose | | ----------- | ------- | @@ -151,35 +163,65 @@ application. Most of the work in this tutorial will happen in the `app/` folder, Hello, Rails! ------------- -To begin with, let's get some text up on screen quickly. To do this, you need to get your Rails application server running. +To begin with, let's get some text up on screen quickly. To do this, you need to +get your Rails application server running. ### Starting up the Web Server -You actually have a functional Rails application already. To see it, you need to start a web server on your development machine. You can do this by running the following in the root directory of your rails application: +You actually have a functional Rails application already. To see it, you need to +start a web server on your development machine. You can do this by running the +following in the root directory of your rails application: ```bash $ rails server ``` -TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an `execjs` error. Usually Mac OS X and Windows come with a JavaScript runtime installed. Rails adds the `therubyracer` gem to Gemfile in a commented line for new apps and you can uncomment if you need it. `therubyrhino` is the recommended runtime for JRuby users and is added by default to Gemfile in apps generated under JRuby. You can investigate about all the supported runtimes at [ExecJS](https://github.com/sstephenson/execjs#readme). +TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the +absence of a runtime will give you an `execjs` error. Usually Mac OS X and +Windows come with a JavaScript runtime installed. Rails adds the `therubyracer` +gem to Gemfile in a commented line for new apps and you can uncomment if you +need it. `therubyrhino` is the recommended runtime for JRuby users and is added +by default to Gemfile in apps generated under JRuby. You can investigate about +all the supported runtimes at [ExecJS](https://github.com/sstephenson/execjs#readme). -This will fire up WEBrick, a webserver built into Ruby by default. To see your application in action, open a browser window and navigate to <http://localhost:3000>. You should see the Rails default information page: +This will fire up WEBrick, a webserver built into Ruby by default. To see your +application in action, open a browser window and navigate to <http://localhost:3000>. +You should see the Rails default information page: ![Welcome Aboard screenshot](images/getting_started/rails_welcome.png) -TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. To verify the server has stopped you should see your command prompt cursor again. For most UNIX-like systems including Mac OS X this will be a dollar sign `$`. In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server. +TIP: To stop the web server, hit Ctrl+C in the terminal window where it's +running. To verify the server has stopped you should see your command prompt +cursor again. For most UNIX-like systems including Mac OS X this will be a +dollar sign `$`. In development mode, Rails does not generally require you to +restart the server; changes you make in files will be automatically picked up by +the server. -The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. You can also click on the _About your application's environment_ link to see a summary of your application's environment. +The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it +makes sure that you have your software configured correctly enough to serve a +page. You can also click on the _About your application's environment_ link to +see a summary of your application's environment. ### Say "Hello", Rails -To get Rails saying "Hello", you need to create at minimum a _controller_ and a _view_. +To get Rails saying "Hello", you need to create at minimum a _controller_ and a +_view_. -A controller's purpose is to receive specific requests for the application. _Routing_ decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different _actions_. Each action's purpose is to collect information to provide it to a view. +A controller's purpose is to receive specific requests for the application. +_Routing_ decides which controller receives which requests. Often, there is more +than one route to each controller, and different routes can be served by +different _actions_. Each action's purpose is to collect information to provide +it to a view. -A view's purpose is to display this information in a human readable format. An important distinction to make is that it is the _controller_, not the view, where information is collected. The view should just display that information. By default, view templates are written in a language called ERB (Embedded Ruby) which is converted by the request cycle in Rails before being sent to the user. +A view's purpose is to display this information in a human readable format. An +important distinction to make is that it is the _controller_, not the view, +where information is collected. The view should just display that information. +By default, view templates are written in a language called ERB (Embedded Ruby) +which is converted by the request cycle in Rails before being sent to the user. -To create a new controller, you will need to run the "controller" generator and tell it you want a controller called "welcome" with an action called "index", just like this: +To create a new controller, you will need to run the "controller" generator and +tell it you want a controller called "welcome" with an action called "index", +just like this: ```bash $ rails generate controller welcome index @@ -206,9 +248,12 @@ invoke scss create app/assets/stylesheets/welcome.css.scss ``` -Most important of these are of course the controller, located at `app/controllers/welcome_controller.rb` and the view, located at `app/views/welcome/index.html.erb`. +Most important of these are of course the controller, located at `app/controllers/welcome_controller.rb` +and the view, located at `app/views/welcome/index.html.erb`. -Open the `app/views/welcome/index.html.erb` file in your text editor. Delete all of the existing code in the file, and replace it with the following single line of code: +Open the `app/views/welcome/index.html.erb` file in your text editor. Delete all +of the existing code in the file, and replace it with the following single line +of code: ```html <h1>Hello, Rails!</h1> @@ -216,7 +261,10 @@ Open the `app/views/welcome/index.html.erb` file in your text editor. Delete all ### Setting the Application Home Page -Now that we have made the controller and view, we need to tell Rails when we want Hello Rails! to show up. In our case, we want it to show up when we navigate to the root URL of our site, <http://localhost:3000>. At the moment, "Welcome Aboard" is occupying that spot. +Now that we have made the controller and view, we need to tell Rails when we +want Hello Rails! to show up. In our case, we want it to show up when we +navigate to the root URL of our site, <http://localhost:3000>. At the moment, +"Welcome Aboard" is occupying that spot. Next, you have to tell Rails where your actual home page is located. @@ -233,27 +281,44 @@ Blog::Application.routes.draw do # root "welcome#index" ``` -This is your application's _routing file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with `root` and uncomment it. It should look something like the following: +This is your application's _routing file_ which holds entries in a special DSL +(domain-specific language) that tells Rails how to connect incoming requests to +controllers and actions. This file contains many sample routes on commented +lines, and one of them actually shows you how to connect the root of your site +to a specific controller and action. Find the line beginning with `root` and +uncomment it. It should look something like the following: ```ruby root "welcome#index" ``` -The `root "welcome#index"` tells Rails to map requests to the root of the application to the welcome controller's index action and `get "welcome/index"` tells Rails to map requests to <http://localhost:3000/welcome/index> to the welcome controller's index action. This was created earlier when you ran the controller generator (`rails generate controller welcome index`). +The `root "welcome#index"` tells Rails to map requests to the root of the +application to the welcome controller's index action and `get "welcome/index"` +tells Rails to map requests to <http://localhost:3000/welcome/index> to the +welcome controller's index action. This was created earlier when you ran the +controller generator (`rails generate controller welcome index`). -If you navigate to <http://localhost:3000> in your browser, you'll see the `Hello, Rails!` message you put into `app/views/welcome/index.html.erb`, indicating that this new route is indeed going to `WelcomeController`'s `index` action and is rendering the view correctly. +If you navigate to <http://localhost:3000> in your browser, you'll see the +`Hello, Rails!` message you put into `app/views/welcome/index.html.erb`, +indicating that this new route is indeed going to `WelcomeController`'s `index` +action and is rendering the view correctly. TIP: For more information about routing, refer to [Rails Routing from the Outside In](routing.html). Getting Up and Running ---------------------- -Now that you've seen how to create a controller, an action and a view, let's create something with a bit more substance. +Now that you've seen how to create a controller, an action and a view, let's +create something with a bit more substance. -In the Blog application, you will now create a new _resource_. A resource is the term used for a collection of similar objects, such as posts, people or animals. You can create, read, update and destroy items for a resource and these operations are referred to as _CRUD_ operations. +In the Blog application, you will now create a new _resource_. A resource is the +term used for a collection of similar objects, such as posts, people or animals. +You can create, read, update and destroy items for a resource and these +operations are referred to as _CRUD_ operations. -Rails provides a `resources` method which can be used to declare a standard REST resource. -Here's what `config/routes.rb` should look like after the _post resource_ is declared. +Rails provides a `resources` method which can be used to declare a standard REST +resource. Here's what `config/routes.rb` should look like after the _post resource_ +is declared. ```ruby Blog::Application.routes.draw do @@ -283,32 +348,45 @@ edit_post GET /posts/:id/edit(.:format) posts#edit root / welcome#index ``` -In the next section, you will add the ability to create new posts in your application and be able to view them. This is the "C" and the "R" from CRUD: creation and reading. The form for doing this will look like this: +In the next section, you will add the ability to create new posts in your +application and be able to view them. This is the "C" and the "R" from CRUD: +creation and reading. The form for doing this will look like this: ![The new post form](images/getting_started/new_post.png) -It will look a little basic for now, but that's ok. We'll look at improving the styling for it afterwards. +It will look a little basic for now, but that's ok. We'll look at improving the +styling for it afterwards. ### Laying down the ground work -The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. With the route already defined, requests can now be made to `/posts/new` in the application. Navigate to <http://localhost:3000/posts/new> and you'll see a routing error: +The first thing that you are going to need to create a new post within the +application is a place to do that. A great place for that would be at `/posts/new`. +With the route already defined, requests can now be made to `/posts/new` in the +application. Navigate to <http://localhost:3000/posts/new> and you'll see a +routing error: ![Another routing error, uninitialized constant PostsController](images/getting_started/routing_error_no_controller.png) -This error occurs because the route needs to have a controller defined in order to serve the request. The solution to this particular problem is simple: create a controller called `PostsController`. You can do this by running this command: +This error occurs because the route needs to have a controller defined in order +to serve the request. The solution to this particular problem is simple: create +a controller called `PostsController`. You can do this by running this command: ```bash $ rails g controller posts ``` -If you open up the newly generated `app/controllers/posts_controller.rb` you'll see a fairly empty controller: +If you open up the newly generated `app/controllers/posts_controller.rb` you'll +see a fairly empty controller: ```ruby class PostsController < ApplicationController end ``` -A controller is simply a class that is defined to inherit from `ApplicationController`. It's inside this class that you'll define methods that will become the actions for this controller. These actions will perform CRUD operations on the posts within our system. +A controller is simply a class that is defined to inherit from `ApplicationController`. +It's inside this class that you'll define methods that will become the actions +for this controller. These actions will perform CRUD operations on the posts +within our system. NOTE: There are `public`, `private` and `protected` methods in `Ruby` (for more details you can check on [Programming Ruby](http://www.ruby-doc.org/docs/ProgrammingRuby/)). @@ -318,44 +396,77 @@ If you refresh <http://localhost:3000/posts/new> now, you'll get a new error: ![Unknown action new for PostsController!](images/getting_started/unknown_action_new_for_posts.png) -This error indicates that Rails cannot find the `new` action inside the `PostsController` that you just generated. This is because when controllers are generated in Rails they are empty by default, unless you tell it you wanted actions during the generation process. +This error indicates that Rails cannot find the `new` action inside the `PostsController` +that you just generated. This is because when controllers are generated in Rails +they are empty by default, unless you tell it you wanted actions during the +generation process. -To manually define an action inside a controller, all you need to do is to define a new method inside the controller. Open `app/controllers/posts_controller.rb` and inside the `PostsController` class, define a `new` method like this: +To manually define an action inside a controller, all you need to do is to +define a new method inside the controller. Open `app/controllers/posts_controller.rb` +and inside the `PostsController` class, define a `new` method like this: ```ruby def new end ``` -With the `new` method defined in `PostsController`, if you refresh <http://localhost:3000/posts/new> you'll see another error: +With the `new` method defined in `PostsController`, if you refresh <http://localhost:3000/posts/new> +you'll see another error: ![Template is missing for posts/new](images/getting_started/template_is_missing_posts_new.png) -You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails errors out. +You're getting this error now because Rails expects plain actions like this one +to have views associated with them to display their information. With no view +available, Rails errors out. -In the above image, the bottom line has been truncated. Let's see what the full thing looks like: +In the above image, the bottom line has been truncated. Let's see what the full +thing looks like: <blockquote> Missing template posts/new, application/new with {locale:[:en], formats:[:html], handlers:[:erb, :builder, :coffee]}. Searched in: * "/path/to/blog/app/views" </blockquote> -That's quite a lot of text! Let's quickly go through and understand what each part of it does. - -The first part identifies what template is missing. In this case, it's the `posts/new` template. Rails will first look for this template. If not found, then it will attempt to load a template called `application/new`. It looks for one here because the `PostsController` inherits from `ApplicationController`. - -The next part of the message contains a hash. The `:locale` key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English - or "en" - template. The next key, `:formats` specifies the format of template to be served in response. The default format is `:html`, and so Rails is looking for an HTML template. The final key, `:handlers`, is telling us what _template handlers_ could be used to render our template. `:erb` is most commonly used for HTML templates, `:builder` is used for XML templates, and `:coffee` uses CoffeeScript to build JavaScript templates. - -The final part of this message tells us where Rails has looked for the templates. Templates within a basic Rails application like this are kept in a single location, but in more complex applications it could be many different paths. - -The simplest template that would work in this case would be one located at `app/views/posts/new.html.erb`. The extension of this file name is key: the first extension is the _format_ of the template, and the second extension is the _handler_ that will be used. Rails is attempting to find a template called `posts/new` within `app/views` for the application. The format for this template can only be `html` and the handler must be one of `erb`, `builder` or `coffee`. Because you want to create a new HTML form, you will be using the `ERB` language. Therefore the file should be called `posts/new.html.erb` and needs to be located inside the `app/views` directory of the application. - -Go ahead now and create a new file at `app/views/posts/new.html.erb` and write this content in it: +That's quite a lot of text! Let's quickly go through and understand what each +part of it does. + +The first part identifies what template is missing. In this case, it's the +`posts/new` template. Rails will first look for this template. If not found, +then it will attempt to load a template called `application/new`. It looks for +one here because the `PostsController` inherits from `ApplicationController`. + +The next part of the message contains a hash. The `:locale` key in this hash +simply indicates what spoken language template should be retrieved. By default, +this is the English - or "en" - template. The next key, `:formats` specifies the +format of template to be served in response. The default format is `:html`, and +so Rails is looking for an HTML template. The final key, `:handlers`, is telling +us what _template handlers_ could be used to render our template. `:erb` is most +commonly used for HTML templates, `:builder` is used for XML templates, and +`:coffee` uses CoffeeScript to build JavaScript templates. + +The final part of this message tells us where Rails has looked for the templates. +Templates within a basic Rails application like this are kept in a single +location, but in more complex applications it could be many different paths. + +The simplest template that would work in this case would be one located at +`app/views/posts/new.html.erb`. The extension of this file name is key: the +first extension is the _format_ of the template, and the second extension is the +_handler_ that will be used. Rails is attempting to find a template called +`posts/new` within `app/views` for the application. The format for this template +can only be `html` and the handler must be one of `erb`, `builder` or `coffee`. +Because you want to create a new HTML form, you will be using the `ERB` +language. Therefore the file should be called `posts/new.html.erb` and needs to +be located inside the `app/views` directory of the application. + +Go ahead now and create a new file at `app/views/posts/new.html.erb` and write +this content in it: ```html <h1>New Post</h1> ``` -When you refresh <http://localhost:3000/posts/new> you'll now see that the page has a title. The route, controller, action and view are now working harmoniously! It's time to create the form for a new post. +When you refresh <http://localhost:3000/posts/new> you'll now see that the page +has a title. The route, controller, action and view are now working +harmoniously! It's time to create the form for a new post. ### The first form @@ -381,14 +492,21 @@ method called `form_for`. To use this method, add this code into `app/views/post <% end %> ``` -If you refresh the page now, you'll see the exact same form as in the example. Building forms in Rails is really just that easy! +If you refresh the page now, you'll see the exact same form as in the example. +Building forms in Rails is really just that easy! When you call `form_for`, you pass it an identifying object for this form. In this case, it's the symbol `:post`. This tells the `form_for` helper what this form is for. Inside the block for this method, the -`FormBuilder` object - represented by `f` - is used to build two labels and two text fields, one each for the title and text of a post. Finally, a call to `submit` on the `f` object will create a submit button for the form. +`FormBuilder` object - represented by `f` - is used to build two labels and two +text fields, one each for the title and text of a post. Finally, a call to +`submit` on the `f` object will create a submit button for the form. -There's one problem with this form though. If you inspect the HTML that is generated, by viewing the source of the page, you will see that the `action` attribute for the form is pointing at `/posts/new`. This is a problem because this route goes to the very page that you're on right at the moment, and that route should only be used to display the form for a new post. +There's one problem with this form though. If you inspect the HTML that is +generated, by viewing the source of the page, you will see that the `action` +attribute for the form is pointing at `/posts/new`. This is a problem because +this route goes to the very page that you're on right at the moment, and that +route should only be used to display the form for a new post. The form needs to use a different URL in order to go somewhere else. This can be done quite simply with the `:url` option of `form_for`. @@ -423,15 +541,21 @@ the form will (by default) send a `POST` request to that route. This is associated with the `create` action of the current controller, the `PostsController`. -With the form and its associated route defined, you will be able to fill in the form and then click the submit button to begin the process of creating a new post, so go ahead and do that. When you submit the form, you should see a familiar error: +With the form and its associated route defined, you will be able to fill in the +form and then click the submit button to begin the process of creating a new +post, so go ahead and do that. When you submit the form, you should see a +familiar error: ![Unknown action create for PostsController](images/getting_started/unknown_action_create_for_posts.png) -You now need to create the `create` action within the `PostsController` for this to work. +You now need to create the `create` action within the `PostsController` for this +to work. ### Creating posts -To make the "Unknown action" go away, you can define a `create` action within the `PostsController` class in `app/controllers/posts_controller.rb`, underneath the `new` action: +To make the "Unknown action" go away, you can define a `create` action within +the `PostsController` class in `app/controllers/posts_controller.rb`, underneath +the `new` action: ```ruby class PostsController < ApplicationController @@ -443,9 +567,14 @@ class PostsController < ApplicationController end ``` -If you re-submit the form now, you'll see another familiar error: a template is missing. That's ok, we can ignore that for now. What the `create` action should be doing is saving our new post to a database. +If you re-submit the form now, you'll see another familiar error: a template is +missing. That's ok, we can ignore that for now. What the `create` action should +be doing is saving our new post to a database. -When a form is submitted, the fields of the form are sent to Rails as _parameters_. These parameters can then be referenced inside the controller actions, typically to perform a particular task. To see what these parameters look like, change the `create` action to this: +When a form is submitted, the fields of the form are sent to Rails as +_parameters_. These parameters can then be referenced inside the controller +actions, typically to perform a particular task. To see what these parameters +look like, change the `create` action to this: ```ruby def create @@ -453,15 +582,23 @@ def create end ``` -The `render` method here is taking a very simple hash with a key of `text` and value of `params[:post].inspect`. The `params` method is the object which represents the parameters (or fields) coming in from the form. The `params` method returns an `ActiveSupport::HashWithIndifferentAccess` object, which allows you to access the keys of the hash using either strings or symbols. In this situation, the only parameters that matter are the ones from the form. +The `render` method here is taking a very simple hash with a key of `text` and +value of `params[:post].inspect`. The `params` method is the object which +represents the parameters (or fields) coming in from the form. The `params` +method returns an `ActiveSupport::HashWithIndifferentAccess` object, which +allows you to access the keys of the hash using either strings or symbols. In +this situation, the only parameters that matter are the ones from the form. -If you re-submit the form one more time you'll now no longer get the missing template error. Instead, you'll see something that looks like the following: +If you re-submit the form one more time you'll now no longer get the missing +template error. Instead, you'll see something that looks like the following: ```ruby {"title"=>"First post!", "text"=>"This is my first post."} ``` -This action is now displaying the parameters for the post that are coming in from the form. However, this isn't really all that helpful. Yes, you can see the parameters but nothing in particular is being done with them. +This action is now displaying the parameters for the post that are coming in +from the form. However, this isn't really all that helpful. Yes, you can see the +parameters but nothing in particular is being done with them. ### Creating the Post model @@ -603,8 +740,9 @@ private See the `permit`? It allows us to accept both `title` and `text` in this action. -TIP: Note that `def post_params` is private. This new approach prevents an attacker from -setting the model's attributes by manipulating the hash passed to the model. +TIP: Note that `def post_params` is private. This new approach prevents an +attacker from setting the model's attributes by manipulating the hash passed to +the model. For more information, refer to [this blog post about Strong Parameters](http://weblog.rubyonrails.org/2012/3/21/strong-parameters/). @@ -614,7 +752,8 @@ If you submit the form again now, Rails will complain about not finding the `show` action. That's not very useful though, so let's add the `show` action before proceeding. -As we have seen in the output of `rake routes`, the route for `show` action is as follows: +As we have seen in the output of `rake routes`, the route for `show` action is +as follows: ```ruby post GET /posts/:id(.:format) posts#show @@ -695,7 +834,8 @@ And then finally a view for this action, located at `app/views/posts/index.html. </table> ``` -Now if you go to `http://localhost:3000/posts` you will see a list of all the posts that you have created. +Now if you go to `http://localhost:3000/posts` you will see a list of all the +posts that you have created. ### Adding links @@ -713,13 +853,17 @@ The `link_to` method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for posts. -Let's add links to the other views as well, starting with adding this "New Post" link to `app/views/posts/index.html.erb`, placing it above the `<table>` tag: +Let's add links to the other views as well, starting with adding this "New Post" +link to `app/views/posts/index.html.erb`, placing it above the `<table>` tag: ```erb <%= link_to 'New post', new_post_path %> ``` -This link will allow you to bring up the form that lets you create a new post. You should also add a link to this template - `app/views/posts/new.html.erb` - to go back to the `index` action. Do this by adding this underneath the form in this template: +This link will allow you to bring up the form that lets you create a new post. +You should also add a link to this template - `app/views/posts/new.html.erb` - +to go back to the `index` action. Do this by adding this underneath the form in +this template: ```erb <%= form_for :post do |f| %> @@ -729,7 +873,9 @@ This link will allow you to bring up the form that lets you create a new post. Y <%= link_to 'Back', posts_path %> ``` -Finally, add another link to the `app/views/posts/show.html.erb` template to go back to the `index` action as well, so that people who are viewing a single post can go back and view the whole list again: +Finally, add another link to the `app/views/posts/show.html.erb` template to go +back to the `index` action as well, so that people who are viewing a single post +can go back and view the whole list again: ```html+erb <p> @@ -815,8 +961,11 @@ private The `new` action is now creating a new instance variable called `@post`, and you'll see why that is in just a few moments. -Notice that inside the `create` action we use `render` instead of `redirect_to` when `save` -returns `false`. The `render` method is used so that the `@post` object is passed back to the `new` template when it is rendered. This rendering is done within the same request as the form submission, whereas the `redirect_to` will tell the browser to issue another request. +Notice that inside the `create` action we use `render` instead of `redirect_to` +when `save` returns `false`. The `render` method is used so that the `@post` +object is passed back to the `new` template when it is rendered. This rendering +is done within the same request as the form submission, whereas the `redirect_to` +will tell the browser to issue another request. If you reload <http://localhost:3000/posts/new> and @@ -861,7 +1010,8 @@ A few things are going on. We check if there are any errors with errors with `@post.errors.full_messages`. `pluralize` is a rails helper that takes a number and a string as its -arguments. If the number is greater than one, the string will be automatically pluralized. +arguments. If the number is greater than one, the string will be automatically +pluralized. The reason why we added `@post = Post.new` in `posts_controller` is that otherwise `@post` would be `nil` in our view, and calling @@ -878,7 +1028,8 @@ attempt to do just that on the new post form [(http://localhost:3000/posts/new)] ### Updating Posts -We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating posts. +We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating +posts. The first step we'll take is adding an `edit` action to `posts_controller`. @@ -1053,8 +1204,8 @@ which URI and method to use. For more information about this use of `form_for`, see [Resource-oriented style](//api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for-label-Resource-oriented+style). -Now, let's update the `app/views/posts/new.html.erb` view to use this new partial, rewriting it -completely: +Now, let's update the `app/views/posts/new.html.erb` view to use this new +partial, rewriting it completely: ```html+erb <h1>New post</h1> @@ -1093,8 +1244,8 @@ people to craft malicious URLs like this: ``` We use the `delete` method for destroying resources, and this route is mapped to -the `destroy` action inside `app/controllers/posts_controller.rb`, which doesn't exist yet, but is -provided below: +the `destroy` action inside `app/controllers/posts_controller.rb`, which doesn't +exist yet, but is provided below: ```ruby def destroy @@ -1135,13 +1286,14 @@ together. </table> ``` -Here we're using `link_to` in a different way. We pass the named route as the second argument, -and then the options as another argument. The `:method` and `:'data-confirm'` -options are used as HTML5 attributes so that when the link is clicked, -Rails will first show a confirm dialog to the user, and then submit the link with method `delete`. -This is done via the JavaScript file `jquery_ujs` which is automatically included -into your application's layout (`app/views/layouts/application.html.erb`) when you -generated the application. Without this file, the confirmation dialog box wouldn't appear. +Here we're using `link_to` in a different way. We pass the named route as the +second argument, and then the options as another argument. The `:method` and +`:'data-confirm'` options are used as HTML5 attributes so that when the link is +clicked, Rails will first show a confirm dialog to the user, and then submit the +link with method `delete`. This is done via the JavaScript file `jquery_ujs` +which is automatically included into your application's layout +(`app/views/layouts/application.html.erb`) when you generated the application. +Without this file, the confirmation dialog box wouldn't appear. ![Confirm Dialog](images/getting_started/confirm_dialog.png) @@ -1156,8 +1308,8 @@ For more information about routing, see Adding a Second Model --------------------- -It's time to add a second model to the application. The second model will handle comments on -posts. +It's time to add a second model to the application. The second model will handle +comments on posts. ### Generating a Model @@ -1235,8 +1387,8 @@ this way: * One post can have many comments. In fact, this is very close to the syntax that Rails uses to declare this -association. You've already seen the line of code inside the `Comment` model (app/models/comment.rb) that -makes each comment belong to a Post: +association. You've already seen the line of code inside the `Comment` model +(app/models/comment.rb) that makes each comment belong to a Post: ```ruby class Comment < ActiveRecord::Base @@ -1681,7 +1833,7 @@ along with a number of others. ### Other Security Considerations Security, especially in web applications, is a broad and detailed area. Security -in your Rails application is covered in more depth in +in your Rails application is covered in more depth in The [Ruby on Rails Security Guide](security.html) @@ -1698,12 +1850,19 @@ free to consult these support resources: * The [Ruby on Rails mailing list](http://groups.google.com/group/rubyonrails-talk) * The [#rubyonrails](irc://irc.freenode.net/#rubyonrails) channel on irc.freenode.net -Rails also comes with built-in help that you can generate using the rake command-line utility: +Rails also comes with built-in help that you can generate using the rake +command-line utility: -* Running `rake doc:guides` will put a full copy of the Rails Guides in the `doc/guides` folder of your application. Open `doc/guides/index.html` in your web browser to explore the Guides. -* Running `rake doc:rails` will put a full copy of the API documentation for Rails in the `doc/api` folder of your application. Open `doc/api/index.html` in your web browser to explore the API documentation. +* Running `rake doc:guides` will put a full copy of the Rails Guides in the + `doc/guides` folder of your application. Open `doc/guides/index.html` in your + web browser to explore the Guides. +* Running `rake doc:rails` will put a full copy of the API documentation for + Rails in the `doc/api` folder of your application. Open `doc/api/index.html` + in your web browser to explore the API documentation. -TIP: To be able to generate the Rails Guides locally with the `doc:guides` rake task you need to install the RedCloth gem. Add it to your `Gemfile` and run `bundle install` and you're ready to go. +TIP: To be able to generate the Rails Guides locally with the `doc:guides` rake +task you need to install the RedCloth gem. Add it to your `Gemfile` and run +`bundle install` and you're ready to go. Configuration Gotchas --------------------- diff --git a/guides/source/i18n.md b/guides/source/i18n.md index c191db1df9..948b6f167c 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -316,6 +316,17 @@ end ``` ```ruby +# app/controllers/application_controller.rb +class ApplicationController < ActionController::Base + before_action :set_locale + + def set_locale + I18n.locale = params[:locale] || I18n.default_locale + end +end +``` + +```ruby # app/controllers/home_controller.rb class HomeController < ApplicationController def index @@ -884,15 +895,15 @@ Rails uses fixed strings and other localizations, such as format strings and oth #### Action View Helper Methods -* `distance_of_time_in_words` translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See [datetime.distance_in_words](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L51) translations. +* `distance_of_time_in_words` translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See [datetime.distance_in_words](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L4) translations. -* `datetime_select` and `select_month` use translated month names for populating the resulting select tag. See [date.month_names](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15) for translations. `datetime_select` also looks up the order option from [date.order](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18) (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the [datetime.prompts](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L83) scope if applicable. +* `datetime_select` and `select_month` use translated month names for populating the resulting select tag. See [date.month_names](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15) for translations. `datetime_select` also looks up the order option from [date.order](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18) (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the [datetime.prompts](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L39) scope if applicable. -* The `number_to_currency`, `number_with_precision`, `number_to_percentage`, `number_with_delimiter`, and `number_to_human_size` helpers use the number format settings located in the [number](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L2) scope. +* The `number_to_currency`, `number_with_precision`, `number_to_percentage`, `number_with_delimiter`, and `number_to_human_size` helpers use the number format settings located in the [number](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L37) scope. #### Active Model Methods -* `model_name.human` and `human_attribute_name` use translations for model names and attribute names if available in the [activerecord.models](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29) scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". +* `model_name.human` and `human_attribute_name` use translations for model names and attribute names if available in the [activerecord.models](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L36) scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". * `ActiveModel::Errors#generate_message` (which is used by Active Model validations but may also be used manually) uses `model_name.human` and `human_attribute_name` (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes". @@ -900,7 +911,7 @@ Rails uses fixed strings and other localizations, such as format strings and oth #### Active Support Methods -* `Array#to_sentence` uses format settings as given in the [support.array](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30) scope. +* `Array#to_sentence` uses format settings as given in the [support.array](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L33) scope. Customize your I18n Setup ------------------------- diff --git a/guides/source/migrations.md b/guides/source/migrations.md index 414ce46a4e..ab39b39a1c 100644 --- a/guides/source/migrations.md +++ b/guides/source/migrations.md @@ -305,7 +305,7 @@ braces. You can use the following modifiers: For instance, running ```bash -$ rails generate migration AddDetailsToProducts price:decimal{5,2} supplier:references{polymorphic} +$ rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic} ``` will produce a migration that looks like this diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 357918a73c..3daa10ea07 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -170,6 +170,7 @@ this gem such as `whitelist_attributes` or `mass_assignment_sanitizer` options. ``` * Rails 4.0 has deprecated `ActiveRecord::Fixtures` in favor of `ActiveRecord::FixtureSet`. + * Rails 4.0 has deprecated `ActiveRecord::TestCase` in favor of `ActiveSupport::TestCase`. * Rails 4.0 has deprecated the old-style hash based finder API. This means that diff --git a/railties/lib/rails/app_rails_loader.rb b/railties/lib/rails/app_rails_loader.rb index fbb83fa10e..71fcf83dae 100644 --- a/railties/lib/rails/app_rails_loader.rb +++ b/railties/lib/rails/app_rails_loader.rb @@ -49,7 +49,7 @@ EOS # call to generate a new application, so restore the original cwd. Dir.chdir(original_cwd) and return if Pathname.new(Dir.pwd).root? - # Otherwise keep moving upwards in search of a executable. + # Otherwise keep moving upwards in search of an executable. Dir.chdir('..') end end diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb index 11524c4ef5..59d2a0793e 100644 --- a/railties/lib/rails/commands/commands_tasks.rb +++ b/railties/lib/rails/commands/commands_tasks.rb @@ -51,6 +51,10 @@ EOT generate_or_destroy(:generate) end + def destroy + generate_or_destroy(:destroy) + end + def console require_command!("console") options = Rails::Console.parse_arguments(argv) diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 4de8fcaa38..035535ce22 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -293,7 +293,7 @@ module ApplicationTests test "precompile should handle utf8 filenames" do filename = "レイルズ.png" - app_file "app/assets/images/#{filename}", "not a image really" + app_file "app/assets/images/#{filename}", "not an image really" add_to_config "config.assets.precompile = [ /\.png$/, /application.(css|js)$/ ]" precompile! @@ -305,7 +305,7 @@ module ApplicationTests require "#{app_path}/config/environment" get "/assets/#{URI.parser.escape(asset_path)}" - assert_match "not a image really", last_response.body + assert_match "not an image really", last_response.body assert_file_exists("#{app_path}/public/assets/#{asset_path}") end diff --git a/railties/test/application/multiple_applications_test.rb b/railties/test/application/multiple_applications_test.rb index 03c343c475..5bfea599e0 100644 --- a/railties/test/application/multiple_applications_test.rb +++ b/railties/test/application/multiple_applications_test.rb @@ -110,7 +110,7 @@ module ApplicationTests assert_equal 0, $run_count, "Without loading the initializers, the count should be 0" - # Set config.eager_load to false so that a eager_load warning doesn't pop up + # Set config.eager_load to false so that an eager_load warning doesn't pop up AppTemplate::Application.new { config.eager_load = false }.initialize! assert_equal 3, $run_count, "There should have been three initializers that incremented the count" diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb index 12f18b9dbf..178c505865 100644 --- a/railties/test/paths_test.rb +++ b/railties/test/paths_test.rb @@ -180,7 +180,7 @@ class PathsTest < ActiveSupport::TestCase assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size end - test "paths added to a eager_load path should be added to the eager_load collection" do + test "paths added to an eager_load path should be added to the eager_load collection" do @root["app"] = "/app" @root["app"].eager_load! @root["app"] << "/app2" |