diff options
83 files changed, 677 insertions, 435 deletions
diff --git a/.travis.yml b/.travis.yml index b97bd8fd32..1e354a8fb0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,7 @@ before_install: rvm: - 1.9.3 - 2.0.0 - - rbx-2.1.1 + - rbx-2.2.1 - jruby-19mode env: - "GEM=railties" @@ -16,7 +16,7 @@ env: - "GEM=ar:postgresql" matrix: allow_failures: - - rvm: rbx-2.1.1 + - rvm: rbx-2.2.1 - rvm: jruby-19mode notifications: email: false @@ -12,7 +12,7 @@ gem 'bcrypt-ruby', '~> 3.1.2' gem 'jquery-rails', '~> 2.2.0' gem 'turbolinks' gem 'coffee-rails', '~> 4.0.0' -gem 'arel', github: 'rails/arel', branch: 'master' +gem 'arel', github: 'rails/arel' # This needs to be with require false to avoid # it being automatically loaded by sprockets @@ -79,10 +79,8 @@ platforms :jruby do end platforms :rbx do - gem 'psych' - gem 'rubysl-mathn' - gem 'rubysl-matrix' - gem 'rubysl-rexml' + gem 'psych', '~> 2.0' + gem 'rubysl', '~> 2.0' end # gems that are necessary for ActiveRecord tests with Oracle database diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index d84b95e6e9..dc8c6bdf74 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -1,12 +1,14 @@ -* Instrument the generation of Action Mailer messages. The time it takes to - generate a message is written to the log. +* Instrument the generation of Action Mailer messages. The time it takes to + generate a message is written to the log. - *Daniel Schierbeck* + *Daniel Schierbeck* -* invoke mailer defaults as procs only if they are procs, do not convert - with to_proc. That an object is convertible to a proc does not mean it's - meant to be always used as a proc. Fixes #11533 +* Invoke mailer defaults as procs only if they are procs, do not convert with + `to_proc`. That an object is convertible to a proc does not mean it's meant + to be always used as a proc. - *Alex Tsukernik* + Fixes #11533. + + *Alex Tsukernik* Please check [4-0-stable](https://github.com/rails/rails/blob/4-0-stable/actionmailer/CHANGELOG.md) for previous changes. diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc index 96dd0b1a2e..c3dcd3c3e4 100644 --- a/actionmailer/README.rdoc +++ b/actionmailer/README.rdoc @@ -74,7 +74,7 @@ Or you can just chain the methods together like: == Setting defaults -It is possible to set default values that will be used in every method in your Action Mailer class. To implement this functionality, you just call the public class method <tt>default</tt> which you get for free from ActionMailer::Base. This method accepts a Hash as the parameter. You can use any of the headers e-mail messages has, like <tt>:from</tt> as the key. You can also pass in a string as the key, like "Content-Type", but Action Mailer does this out of the box for you, so you won't need to worry about that. Finally, it is also possible to pass in a Proc that will get evaluated when it is needed. +It is possible to set default values that will be used in every method in your Action Mailer class. To implement this functionality, you just call the public class method <tt>default</tt> which you get for free from <tt>ActionMailer::Base</tt>. This method accepts a Hash as the parameter. You can use any of the headers e-mail messages has, like <tt>:from</tt> as the key. You can also pass in a string as the key, like "Content-Type", but Action Mailer does this out of the box for you, so you won't need to worry about that. Finally, it is also possible to pass in a Proc that will get evaluated when it is needed. Note that every value you set with this method will get overwritten if you use the same key in your mailer method. diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 19eb098d16..e649847990 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,4 +1,16 @@ -* Take a hash with options inside array in #url_for +* Better error message for typos in assert_response argument. + + When the response type argument to `assert_response` is not a known + response type, `assert_response` now throws an ArgumentError with a clear + message. This is intended to help debug typos in the response type. + + *Victor Costan* + +* Fix formatting for `rake routes` when a section is shorter than a header. + + *Sıtkı Bağdat* + +* Take a hash with options inside array in `#url_for`. Example: @@ -222,11 +234,13 @@ *Yves Senn*, *Andrew White* -* ActionView extracted from ActionPack +* ActionView extracted from ActionPack. *Piotr Sarnacki*, *Łukasz Strzałkowski* -* Fix removing trailing slash for mounted apps #3215 +* Fix removing trailing slash for mounted apps. + + Fixes #3215. *Piotr Sarnacki* diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb index cffb814e1e..120bc54333 100644 --- a/actionpack/lib/action_dispatch/routing/inspector.rb +++ b/actionpack/lib/action_dispatch/routing/inspector.rb @@ -179,7 +179,8 @@ module ActionDispatch private def draw_section(routes) - name_width, verb_width, path_width = widths(routes) + header_lengths = ['Prefix', 'Verb', 'URI Pattern'].map(&:length) + name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max) routes.map do |r| "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}" diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 3d3299afb3..846a6345cb 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -389,7 +389,7 @@ module ActionDispatch # The namespace for :controller. # # match 'path', to: 'c#a', module: 'sekret', controller: 'posts' - # #=> Sekret::PostsController + # # => Sekret::PostsController # # See <tt>Scoping#namespace</tt> for its scope equivalent. # diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index 93f9fab9c2..68feb26936 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -27,6 +27,9 @@ module ActionDispatch assert @response.send("#{type}?"), message else code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type] + if code.nil? + raise ArgumentError, "Invalid response type :#{type}" + end assert_equal code, @response.response_code, message end else diff --git a/actionpack/test/assertions/response_assertions_test.rb b/actionpack/test/assertions/response_assertions_test.rb index ca1d58765d..8eec98e916 100644 --- a/actionpack/test/assertions/response_assertions_test.rb +++ b/actionpack/test/assertions/response_assertions_test.rb @@ -50,6 +50,14 @@ module ActionDispatch assert_response :success } end + + def test_assert_response_sym_typo + @response = FakeResponse.new 200 + + assert_raises(ArgumentError) { + assert_response :succezz + } + end end end end diff --git a/actionpack/test/controller/new_base/render_streaming_test.rb b/actionpack/test/controller/new_base/render_streaming_test.rb index 2b36a399bb..4c9126ca8c 100644 --- a/actionpack/test/controller/new_base/render_streaming_test.rb +++ b/actionpack/test/controller/new_base/render_streaming_test.rb @@ -4,7 +4,7 @@ module RenderStreaming class BasicController < ActionController::Base self.view_paths = [ActionView::FixtureResolver.new( "render_streaming/basic/hello_world.html.erb" => "Hello world", - "render_streaming/basic/boom.html.erb" => "<%= nil.invalid! %>", + "render_streaming/basic/boom.html.erb" => "<%= raise 'Ruby was here!' %>", "layouts/application.html.erb" => "<%= yield %>, I'm here!", "layouts/boom.html.erb" => "<body class=\"<%= nil.invalid! %>\"<%= yield %></body>" )] @@ -90,7 +90,7 @@ module RenderStreaming begin get "/render_streaming/basic/template_exception" io.rewind - assert_match "(undefined method `invalid!' for nil:NilClass)", io.read + assert_match "Ruby was here!", io.read ensure ActionView::Base.logger = _old end diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb index 6b2ae2b2a9..b7a9cf92f2 100644 --- a/actionpack/test/controller/new_base/render_template_test.rb +++ b/actionpack/test/controller/new_base/render_template_test.rb @@ -14,7 +14,7 @@ module RenderTemplate "test/with_json.html.erb" => "<%= render :template => 'test/with_json', :formats => [:json] %>", "test/with_json.json.erb" => "<%= render :template => 'test/final', :formats => [:json] %>", "test/final.json.erb" => "{ final: json }", - "test/with_error.html.erb" => "<%= idontexist %>" + "test/with_error.html.erb" => "<%= raise 'i do not exist' %>" )] def index @@ -132,7 +132,7 @@ module RenderTemplate test "rendering a template with error properly excerts the code" do get :with_error assert_status 500 - assert_match "undefined local variable or method `idontexist", response.body + assert_match "i do not exist", response.body end end diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb index 4f97d28d2b..c8038bbd7c 100644 --- a/actionpack/test/dispatch/routing/inspector_test.rb +++ b/actionpack/test/dispatch/routing/inspector_test.rb @@ -46,11 +46,11 @@ module ActionDispatch assert_equal [ " Prefix Verb URI Pattern Controller#Action", - "custom_assets GET /custom/assets(.:format) custom_assets#show", - " blog /blog Blog::Engine", + "custom_assets GET /custom/assets(.:format) custom_assets#show", + " blog /blog Blog::Engine", "", "Routes for Blog::Engine:", - "cart GET /cart(.:format) cart#show" + " cart GET /cart(.:format) cart#show" ], output end @@ -61,7 +61,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - "cart GET /cart(.:format) cart#show" + " cart GET /cart(.:format) cart#show" ], output end @@ -72,7 +72,7 @@ module ActionDispatch assert_equal [ " Prefix Verb URI Pattern Controller#Action", - "custom_assets GET /custom/assets(.:format) custom_assets#show" + "custom_assets GET /custom/assets(.:format) custom_assets#show" ], output end @@ -101,7 +101,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - "root GET / pages#main" + " root GET / pages#main" ], output end @@ -112,7 +112,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - " GET /api/:action(.:format) api#:action" + " GET /api/:action(.:format) api#:action" ], output end @@ -123,7 +123,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - " GET /:controller/:action(.:format) :controller#:action" + " GET /:controller/:action(.:format) :controller#:action" ], output end @@ -134,7 +134,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - " GET /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}" + " GET /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}" ], output end @@ -145,7 +145,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - %Q[ GET /photos/:id(.:format) photos#show {:format=>"jpg"}] + %Q[ GET /photos/:id(.:format) photos#show {:format=>"jpg"}] ], output end @@ -156,7 +156,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - " GET /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}" + " GET /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}" ], output end @@ -172,7 +172,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - " GET /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}" + " GET /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}" ], output end @@ -191,7 +191,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - " /foo #{RackApp.name} {:constraint=>( my custom constraint )}" + " /foo #{RackApp.name} {:constraint=>( my custom constraint )}" ], output end @@ -212,9 +212,9 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - " foo GET /foo(.:format) redirect(301, /foo/bar) {:subdomain=>\"admin\"}", - " bar GET /bar(.:format) redirect(307, path: /foo/bar)", - "foobar GET /foobar(.:format) redirect(301)" + " foo GET /foo(.:format) redirect(301, /foo/bar) {:subdomain=>\"admin\"}", + " bar GET /bar(.:format) redirect(307, path: /foo/bar)", + "foobar GET /foobar(.:format) redirect(301)" ], output end @@ -241,7 +241,7 @@ module ActionDispatch end assert_equal ["Prefix Verb URI Pattern Controller#Action", - " GET /:controller(/:action) (?-mix:api\\/[^\\/]+)#:action"], output + " GET /:controller(/:action) (?-mix:api\\/[^\\/]+)#:action"], output end end end diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb index d8de1d95df..ffa67649da 100644 --- a/actionview/lib/action_view/layouts.rb +++ b/actionview/lib/action_view/layouts.rb @@ -221,7 +221,7 @@ module ActionView # This module is mixed in if layout conditions are provided. This means # that if no layout conditions are used, this method is not used module LayoutConditions # :nodoc: - private + private # Determines whether the current action has a layout definition by # checking the action name against the :only and :except conditions @@ -269,15 +269,6 @@ module ActionView _write_layout_method end - # If no layout is supplied, look for a template named the return - # value of this method. - # - # ==== Returns - # * <tt>String</tt> - A template name - def _implied_layout_name # :nodoc: - controller_path - end - # Creates a _layout method to be called by _default_layout . # # If a layout is not explicitly mentioned then look for a layout with the controller's name. @@ -335,6 +326,17 @@ module ActionView private :_layout RUBY end + + private + + # If no layout is supplied, look for a template named the return + # value of this method. + # + # ==== Returns + # * <tt>String</tt> - A template name + def _implied_layout_name # :nodoc: + controller_path + end end def _normalize_options(options) # :nodoc: diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb index 821026268a..36f17f01fd 100644 --- a/actionview/lib/action_view/renderer/partial_renderer.rb +++ b/actionview/lib/action_view/renderer/partial_renderer.rb @@ -159,7 +159,7 @@ module ActionView # </div> # # If a collection is given, the layout will be rendered once for each item in - # the collection. Just think these two snippets have the same output: + # the collection. For example, these two snippets have the same output: # # <%# app/views/users/_user.html.erb %> # Name: <%= user.name %> diff --git a/actionview/lib/action_view/rendering.rb b/actionview/lib/action_view/rendering.rb index 18a0788f8e..82db9e26df 100644 --- a/actionview/lib/action_view/rendering.rb +++ b/actionview/lib/action_view/rendering.rb @@ -77,13 +77,6 @@ module ActionView @_view_renderer ||= ActionView::Renderer.new(lookup_context) end - # Find and renders a template based on the options given. - # :api: private - def _render_template(options) #:nodoc: - lookup_context.rendered_format = nil if options[:formats] - view_renderer.render(view_context, options) - end - def render_to_body(options = {}) _process_options(options) _render_template(options) @@ -95,6 +88,13 @@ module ActionView private + # Find and renders a template based on the options given. + # :api: private + def _render_template(options) #:nodoc: + lookup_context.rendered_format = nil if options[:formats] + view_renderer.render(view_context, options) + end + # Assign the rendered format to lookup context. def _process_format(format) #:nodoc: super diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb index 198efc5088..11ebfe6cc0 100644 --- a/activemodel/lib/active_model/naming.rb +++ b/activemodel/lib/active_model/naming.rb @@ -262,10 +262,10 @@ module ActiveModel # namespaced models regarding whether it's inside isolated engine. # # # For isolated engine: - # ActiveModel::Naming.singular_route_key(Blog::Post) #=> "post" + # ActiveModel::Naming.singular_route_key(Blog::Post) # => "post" # # # For shared engine: - # ActiveModel::Naming.singular_route_key(Blog::Post) #=> "blog_post" + # ActiveModel::Naming.singular_route_key(Blog::Post) # => "blog_post" def self.singular_route_key(record_or_class) model_name_from_record_or_class(record_or_class).singular_route_key end @@ -274,10 +274,10 @@ module ActiveModel # namespaced models regarding whether it's inside isolated engine. # # # For isolated engine: - # ActiveModel::Naming.route_key(Blog::Post) #=> "posts" + # ActiveModel::Naming.route_key(Blog::Post) # => "posts" # # # For shared engine: - # ActiveModel::Naming.route_key(Blog::Post) #=> "blog_posts" + # ActiveModel::Naming.route_key(Blog::Post) # => "blog_posts" # # The route key also considers if the noun is uncountable and, in # such cases, automatically appends _index. @@ -289,10 +289,10 @@ module ActiveModel # namespaced models regarding whether it's inside isolated engine. # # # For isolated engine: - # ActiveModel::Naming.param_key(Blog::Post) #=> "post" + # ActiveModel::Naming.param_key(Blog::Post) # => "post" # # # For shared engine: - # ActiveModel::Naming.param_key(Blog::Post) #=> "blog_post" + # ActiveModel::Naming.param_key(Blog::Post) # => "blog_post" def self.param_key(record_or_class) model_name_from_record_or_class(record_or_class).param_key end diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 0bef057836..43651c9b48 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,10 +1,18 @@ -* Checks to see if the record contains the foreign key to set the inverse automatically. +* Fix validation on uniqueness of empty association. - *Edo Balvers* + *Evgeny Li* + +* Make `ActiveRecord::Relation#unscope` affect relations it is merged in to. + + *Jon Leighton* -* Exit with non-zero status for failed database rake tasks. +* Use strings to represent non-string `order_values`. - *Jay Hayes* + *Yves Senn* + +* Checks to see if the record contains the foreign key to set the inverse automatically. + + *Edo Balvers* * Added `ActiveRecord::Base.to_param` for convenient "pretty" URLs derived from a model's attribute or method. diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index 9986ded904..e1c5b05c36 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -24,5 +24,5 @@ Gem::Specification.new do |s| s.add_dependency 'activesupport', version s.add_dependency 'activemodel', version - s.add_dependency 'arel', '~> 4.0.0' + s.add_dependency 'arel', '~> 5.0.0' end diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 2e70a07962..0b37ecf5b7 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -787,12 +787,12 @@ module ActiveRecord # has_many :pets # end # - # person.pets.count #=> 1 - # person.pets.many? #=> false + # person.pets.count # => 1 + # person.pets.many? # => false # # person.pets << Pet.new(name: 'Snoopy') - # person.pets.count #=> 2 - # person.pets.many? #=> true + # person.pets.count # => 2 + # person.pets.many? # => true # # You can also pass a block to define criteria. The # behavior is the same, it returns true if the collection diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index c3ac0680ea..3e743c4bfe 100644 --- a/activerecord/lib/active_record/associations/join_dependency.rb +++ b/activerecord/lib/active_record/associations/join_dependency.rb @@ -83,14 +83,14 @@ module ActiveRecord # end # # If I execute `@physician.patients.to_a` then - # base #=> Physician - # associations #=> [] - # joins #=> [#<Arel::Nodes::InnerJoin: ...] + # base # => Physician + # associations # => [] + # joins # => [#<Arel::Nodes::InnerJoin: ...] # # However if I execute `Physician.joins(:appointments).to_a` then - # base #=> Physician - # associations #=> [:appointments] - # joins #=> [] + # base # => Physician + # associations # => [:appointments] + # joins # => [] # def initialize(base, associations, joins) @alias_tracker = AliasTracker.new(base.connection, joins) diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb index 191d430636..84e18684d8 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb @@ -86,11 +86,11 @@ module ActiveRecord # end # # If I execute `Physician.joins(:appointments).to_a` then - # reflection #=> #<ActiveRecord::Reflection::AssociationReflection @macro=:has_many ...> - # table #=> #<Arel::Table @name="appointments" ...> - # key #=> physician_id - # foreign_table #=> #<Arel::Table @name="physicians" ...> - # foreign_key #=> id + # reflection # => #<ActiveRecord::Reflection::AssociationReflection @macro=:has_many ...> + # table # => #<Arel::Table @name="appointments" ...> + # key # => physician_id + # foreign_table # => #<Arel::Table @name="physicians" ...> + # foreign_key # => id # def build_constraint(klass, table, key, foreign_table, foreign_key) constraint = table[key].eq(foreign_table[foreign_key]) diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index d010f23517..a4247fb6f4 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -896,7 +896,7 @@ module ActiveRecord validate(@migrations) - ActiveRecord::SchemaMigration.create_table + Base.connection.initialize_schema_migrations_table end def current_version diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 3ca66223b6..52b3d3e5e6 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -8,47 +8,31 @@ db_namespace = namespace :db do namespace :create do task :all => :load_config do - begin - ActiveRecord::Tasks::DatabaseTasks.create_all - rescue - exit(1) - end + ActiveRecord::Tasks::DatabaseTasks.create_all end end desc 'Create the database from DATABASE_URL or config/database.yml for the current Rails.env (use db:create:all to create all databases in the config)' task :create => [:load_config] do - begin - if ENV['DATABASE_URL'] - ActiveRecord::Tasks::DatabaseTasks.create_database_url - else - ActiveRecord::Tasks::DatabaseTasks.create_current - end - rescue - exit(1) + if ENV['DATABASE_URL'] + ActiveRecord::Tasks::DatabaseTasks.create_database_url + else + ActiveRecord::Tasks::DatabaseTasks.create_current end end namespace :drop do task :all => :load_config do - begin - ActiveRecord::Tasks::DatabaseTasks.drop_all - rescue - exit(1) - end + ActiveRecord::Tasks::DatabaseTasks.drop_all end end desc 'Drops the database using DATABASE_URL or the current Rails.env (use db:drop:all to drop all databases)' task :drop => [:load_config] do - begin - if ENV['DATABASE_URL'] - ActiveRecord::Tasks::DatabaseTasks.drop_database_url - else - ActiveRecord::Tasks::DatabaseTasks.drop_current - end - rescue - exit(1) + if ENV['DATABASE_URL'] + ActiveRecord::Tasks::DatabaseTasks.drop_database_url + else + ActiveRecord::Tasks::DatabaseTasks.drop_current end end diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 6e0669a77f..745c6cf349 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -7,7 +7,7 @@ module ActiveRecord MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group, :order, :joins, :where, :having, :bind, :references, - :extending] + :extending, :unscope] SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering, :reverse_order, :distinct, :create_with, :uniq] diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 62c555f6d6..cacc787eba 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -341,13 +341,19 @@ module ActiveRecord # User.where(name: "John", active: true).unscope(where: :name) # == User.where(active: true) # - # Note that this method is more generalized than ActiveRecord::SpawnMethods#except - # because #except will only affect a particular relation's values. It won't wipe - # the order, grouping, etc. when that relation is merged. For example: + # This method is similar to <tt>except</tt>, but unlike + # <tt>except</tt>, it persists across merges: # - # Post.comments.except(:order) + # User.order('email').merge(User.except(:order)) + # == User.order('email') + # + # User.order('email').merge(User.unscope(:order)) + # == User.all + # + # This means it can be used in association definitions: + # + # has_many :comments, -> { unscope where: :trashed } # - # will still have an order if it comes from the default_scope on Comment. def unscope(*args) check_if_method_has_arguments!(:unscope, args) spawn.unscope!(*args) @@ -355,6 +361,7 @@ module ActiveRecord def unscope!(*args) # :nodoc: args.flatten! + self.unscope_values += args args.each do |scope| case scope @@ -552,9 +559,9 @@ module ActiveRecord # Allows you to change a previously set where condition for a given attribute, instead of appending to that condition. # - # Post.where(trashed: true).where(trashed: false) #=> WHERE `trashed` = 1 AND `trashed` = 0 - # Post.where(trashed: true).rewhere(trashed: false) #=> WHERE `trashed` = 0 - # Post.where(active: true).where(trashed: true).rewhere(trashed: false) #=> WHERE `active` = 1 AND `trashed` = 0 + # Post.where(trashed: true).where(trashed: false) # => WHERE `trashed` = 1 AND `trashed` = 0 + # Post.where(trashed: true).rewhere(trashed: false) # => WHERE `trashed` = 0 + # Post.where(active: true).where(trashed: true).rewhere(trashed: false) # => WHERE `active` = 1 AND `trashed` = 0 # # This is short-hand for unscope(where: conditions.keys).where(conditions). Note that unlike reorder, we're only unscoping # the named conditions -- not the entire where statement. @@ -701,7 +708,7 @@ module ActiveRecord # Specifies table from which the records will be fetched. For example: # # Topic.select('title').from('posts') - # #=> SELECT title FROM posts + # # => SELECT title FROM posts # # Can accept other relation objects. For example: # @@ -995,12 +1002,6 @@ module ActiveRecord s.strip! s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC') end - when Symbol - { o => :desc } - when Hash - o.each_with_object({}) do |(field, dir), memo| - memo[field] = (dir == :asc ? :desc : :asc ) - end else o end @@ -1016,17 +1017,6 @@ module ActiveRecord orders.reject!(&:blank?) orders = reverse_sql_order(orders) if reverse_order_value - orders = orders.flat_map do |order| - case order - when Symbol - table[order].asc - when Hash - order.map { |field, dir| table[field].send(dir) } - else - order - end - end - arel.order(*orders) unless orders.empty? end @@ -1048,8 +1038,17 @@ module ActiveRecord # if a symbol is given we prepend the quoted table name order_args.map! do |arg| - arg.is_a?(Symbol) ? Arel::Nodes::Ascending.new(klass.arel_table[arg]) : arg - end + case arg + when Symbol + table[arg].asc + when Hash + arg.map { |field, dir| + table[field].send(dir) + } + else + arg + end + end.flatten! end # Checks to make sure that the arguments are not blank. Note that if some diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index 0b6a49ac85..be7d496d15 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -69,11 +69,9 @@ module ActiveRecord class_for_adapter(configuration['adapter']).new(*arguments).create rescue DatabaseAlreadyExists $stderr.puts "#{configuration['database']} already exists" - raise rescue Exception => error $stderr.puts error, *(error.backtrace) $stderr.puts "Couldn't create database for #{configuration.inspect}" - raise end def create_all @@ -97,7 +95,6 @@ module ActiveRecord rescue Exception => error $stderr.puts error, *(error.backtrace) $stderr.puts "Couldn't drop #{configuration['database']}" - raise end def drop_all diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb index b55af692d6..38f37f5c8a 100644 --- a/activerecord/lib/active_record/validations/uniqueness.rb +++ b/activerecord/lib/active_record/validations/uniqueness.rb @@ -48,7 +48,7 @@ module ActiveRecord def build_relation(klass, table, attribute, value) #:nodoc: if reflection = klass.reflect_on_association(attribute) attribute = reflection.foreign_key - value = value.attributes[reflection.primary_key_column.name] + value = value.attributes[reflection.primary_key_column.name] unless value.nil? end column = klass.columns_hash[attribute.to_s] diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index b11d27467b..359bcfba5f 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1761,4 +1761,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 1, speedometer.minivans.to_a.size, "Only one association should be present:\n#{speedometer.minivans.to_a}" assert_equal 1, speedometer.reload.minivans.to_a.size end + + test "can unscope the default scope of the associated model" do + car = Car.create! + bulb1 = Bulb.create! name: "defaulty", car: car + bulb2 = Bulb.create! name: "other", car: car + + assert_equal [bulb1], car.bulbs + assert_equal [bulb1, bulb2], car.all_bulbs.sort_by(&:id) + end end diff --git a/activerecord/test/cases/mixin_test.rb b/activerecord/test/cases/mixin_test.rb index f927c13979..ad0d5cce27 100644 --- a/activerecord/test/cases/mixin_test.rb +++ b/activerecord/test/cases/mixin_test.rb @@ -3,42 +3,11 @@ require "cases/helper" class Mixin < ActiveRecord::Base end -# Let us control what Time.now returns for the TouchTest suite -class Time - @@forced_now_time = nil - cattr_accessor :forced_now_time - - class << self - def now_with_forcing - if @@forced_now_time - @@forced_now_time - else - now_without_forcing - end - end - alias_method_chain :now, :forcing - end -end - - class TouchTest < ActiveRecord::TestCase fixtures :mixins def setup - Time.forced_now_time = Time.now - end - - def teardown - Time.forced_now_time = nil - end - - def test_time_mocking - five_minutes_ago = 5.minutes.ago - Time.forced_now_time = five_minutes_ago - assert_equal five_minutes_ago, Time.now - - Time.forced_now_time = nil - assert_not_equal five_minutes_ago, Time.now + travel_to Time.now end def test_update @@ -68,12 +37,13 @@ class TouchTest < ActiveRecord::TestCase old_updated_at = stamped.updated_at - Time.forced_now_time = 5.minutes.from_now - stamped.lft_will_change! - stamped.save + travel 5.minutes do + stamped.lft_will_change! + stamped.save - assert_equal Time.now, stamped.updated_at - assert_equal old_updated_at, stamped.created_at + assert_equal Time.now, stamped.updated_at + assert_equal old_updated_at, stamped.created_at + end end def test_create_turned_off diff --git a/activerecord/test/cases/relation/merging_test.rb b/activerecord/test/cases/relation/merging_test.rb index 9f9244f9b2..23500bf5d8 100644 --- a/activerecord/test/cases/relation/merging_test.rb +++ b/activerecord/test/cases/relation/merging_test.rb @@ -146,5 +146,17 @@ class MergingDifferentRelationsTest < ActiveRecord::TestCase merge(Author.order(:name)).pluck("authors.name") assert_equal ["Bob", "Bob", "David"], posts_by_author_name + + posts_by_author_name = Post.limit(3).joins(:author). + merge(Author.order("name")).pluck("authors.name") + + assert_equal ["Bob", "Bob", "David"], posts_by_author_name + end + + test "merging order relations (using a hash argument)" do + posts_by_author_name = Post.limit(4).joins(:author). + merge(Author.order(name: :desc)).pluck("authors.name") + + assert_equal ["Mary", "Mary", "Mary", "David"], posts_by_author_name end end diff --git a/activerecord/test/cases/relation/mutation_test.rb b/activerecord/test/cases/relation/mutation_test.rb index 020fb24afa..7cb2a19bee 100644 --- a/activerecord/test/cases/relation/mutation_test.rb +++ b/activerecord/test/cases/relation/mutation_test.rb @@ -7,10 +7,6 @@ module ActiveRecord extend ActiveRecord::Delegation::DelegateCache inherited self - def arel_table - Post.arel_table - end - def connection Post.connection end @@ -21,10 +17,10 @@ module ActiveRecord end def relation - @relation ||= Relation.new FakeKlass.new('posts'), :b + @relation ||= Relation.new FakeKlass.new('posts'), Post.arel_table end - (Relation::MULTI_VALUE_METHODS - [:references, :extending, :order]).each do |method| + (Relation::MULTI_VALUE_METHODS - [:references, :extending, :order, :unscope]).each do |method| test "##{method}!" do assert relation.public_send("#{method}!", :foo).equal?(relation) assert_equal [:foo], relation.public_send("#{method}_values") diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb index 2fbe19ab06..11dd32bfb8 100644 --- a/activerecord/test/cases/scoping/default_scoping_test.rb +++ b/activerecord/test/cases/scoping/default_scoping_test.rb @@ -262,6 +262,12 @@ class DefaultScopingTest < ActiveRecord::TestCase end end + def test_unscope_merging + merged = Developer.where(name: "Jamis").merge(Developer.unscope(:where)) + assert merged.where_values.empty? + assert !merged.where(name: "Jon").where_values.empty? + end + def test_order_in_default_scope_should_not_prevail expected = Developer.all.merge!(order: 'salary desc').to_a.collect { |dev| dev.salary } received = DeveloperOrderedBySalary.all.merge!(order: 'salary').to_a.collect { |dev| dev.salary } diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb index 75adbb70e8..3e3a2828f3 100644 --- a/activerecord/test/cases/tasks/mysql_rake_test.rb +++ b/activerecord/test/cases/tasks/mysql_rake_test.rb @@ -1,5 +1,4 @@ require 'cases/helper' -require 'active_record/tasks/database_tasks' module ActiveRecord class MysqlDBCreateTest < ActiveRecord::TestCase @@ -62,9 +61,7 @@ module ActiveRecord ActiveRecord::StatementInvalid.new("Can't create database 'dev'; database exists:") ) - assert_raises(ActiveRecord::Tasks::DatabaseAlreadyExists) do - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration end end diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb index c01c6de593..6ea225178f 100644 --- a/activerecord/test/cases/tasks/postgresql_rake_test.rb +++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb @@ -1,5 +1,4 @@ require 'cases/helper' -require 'active_record/tasks/database_tasks' module ActiveRecord class PostgreSQLDBCreateTest < ActiveRecord::TestCase @@ -60,9 +59,7 @@ module ActiveRecord $stderr.expects(:puts). with("Couldn't create database for #{@configuration.inspect}") - assert_raises(Exception) do - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration end def test_create_when_database_exists_outputs_info_to_stderr @@ -72,9 +69,7 @@ module ActiveRecord ActiveRecord::StatementInvalid.new('database "my-app-db" already exists') ) - assert_raises(ActiveRecord::Tasks::DatabaseAlreadyExists) do - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration end end diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb index 102bddf6a6..da3471adf9 100644 --- a/activerecord/test/cases/tasks/sqlite_rake_test.rb +++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb @@ -1,6 +1,5 @@ require 'cases/helper' require 'pathname' -require 'active_record/tasks/database_tasks' module ActiveRecord class SqliteDBCreateTest < ActiveRecord::TestCase @@ -28,9 +27,7 @@ module ActiveRecord $stderr.expects(:puts).with("#{@database} already exists") - assert_raises(ActiveRecord::Tasks::DatabaseAlreadyExists) do - ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' end def test_db_create_with_file_does_nothing @@ -39,9 +36,7 @@ module ActiveRecord ActiveRecord::Base.expects(:establish_connection).never - assert_raises(ActiveRecord::Tasks::DatabaseAlreadyExists) do - ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' end def test_db_create_establishes_a_connection @@ -57,9 +52,7 @@ module ActiveRecord $stderr.expects(:puts). with("Couldn't create database for #{@configuration.inspect}") - assert_raises(Exception) do - ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' end end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 8c45f2a3f8..2953b2b2be 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -326,31 +326,31 @@ class TimestampTest < ActiveRecord::TestCase def test_timestamp_attributes_for_create toy = Toy.first - assert_equal toy.send(:timestamp_attributes_for_create), [:created_at, :created_on] + assert_equal [:created_at, :created_on], toy.send(:timestamp_attributes_for_create) end def test_timestamp_attributes_for_update toy = Toy.first - assert_equal toy.send(:timestamp_attributes_for_update), [:updated_at, :updated_on] + assert_equal [:updated_at, :updated_on], toy.send(:timestamp_attributes_for_update) end def test_all_timestamp_attributes toy = Toy.first - assert_equal toy.send(:all_timestamp_attributes), [:created_at, :created_on, :updated_at, :updated_on] + assert_equal [:created_at, :created_on, :updated_at, :updated_on], toy.send(:all_timestamp_attributes) end def test_timestamp_attributes_for_create_in_model toy = Toy.first - assert_equal toy.send(:timestamp_attributes_for_create_in_model), [:created_at] + assert_equal [:created_at], toy.send(:timestamp_attributes_for_create_in_model) end def test_timestamp_attributes_for_update_in_model toy = Toy.first - assert_equal toy.send(:timestamp_attributes_for_update_in_model), [:updated_at] + assert_equal [:updated_at], toy.send(:timestamp_attributes_for_update_in_model) end def test_all_timestamp_attributes_in_model toy = Toy.first - assert_equal toy.send(:all_timestamp_attributes_in_model), [:created_at, :updated_at] + assert_equal [:created_at, :updated_at], toy.send(:all_timestamp_attributes_in_model) end end diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb index 56d8db0be9..71cb9d7b1e 100644 --- a/activerecord/test/cases/validations/uniqueness_validation_test.rb +++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb @@ -35,6 +35,11 @@ class Employee < ActiveRecord::Base validates_uniqueness_of :nicknames end +class TopicWithUniqEvent < Topic + belongs_to :event, foreign_key: :parent_id + validates :event, uniqueness: true +end + class UniquenessValidationTest < ActiveRecord::TestCase fixtures :topics, 'warehouse-things', :developers @@ -376,4 +381,18 @@ class UniquenessValidationTest < ActiveRecord::TestCase assert_equal ["has already been taken"], e2.errors[:nicknames], "Should have uniqueness message for nicknames" end end + + def test_validate_uniqueness_on_existing_relation + event = Event.create + assert TopicWithUniqEvent.create(event: event).valid? + + topic = TopicWithUniqEvent.new(event: event) + assert_not topic.valid? + assert_equal ['has already been taken'], topic.errors[:event] + end + + def test_validate_uniqueness_on_empty_relation + topic = TopicWithUniqEvent.new + assert topic.valid? + end end diff --git a/activerecord/test/models/car.rb b/activerecord/test/models/car.rb index 6d257dbe7e..8f3b70a7c6 100644 --- a/activerecord/test/models/car.rb +++ b/activerecord/test/models/car.rb @@ -1,5 +1,6 @@ class Car < ActiveRecord::Base has_many :bulbs + has_many :all_bulbs, -> { unscope where: :name }, class_name: "Bulb" has_many :funky_bulbs, class_name: 'FunkyBulb', dependent: :destroy has_many :foo_bulbs, -> { where(:name => 'foo') }, :class_name => "Bulb" diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 95253567c0..104b5eafa1 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,42 @@ +* Add `ActiveSupport::Testing::TimeHelpers#travel` and `#travel_to`. These methods change current + time to the given time or time difference by stubbing `Time.now` and `Date.today` to return the + time or date after the difference calculation, or the time or date that got passed into the + method respectively. These methods also accept a block, which will return current time back to + its original state at the end of the block. + + Example for `#travel`: + + Time.now # => 2013-11-09 15:34:49 -05:00 + travel 1.day + Time.now # => 2013-11-10 15:34:49 -05:00 + Date.today # => Sun, 10 Nov 2013 + + Example for `#travel_to`: + + Time.now # => 2013-11-09 15:34:49 -05:00 + travel_to Time.new(2004, 11, 24, 01, 04, 44) + Time.now # => 2004-11-24 01:04:44 -05:00 + Date.today # => Wed, 24 Nov 2004 + + Both of these methods also accept a block, which will return the current time back to its + original state at the end of the block: + + Time.now # => 2013-11-09 15:34:49 -05:00 + + travel 1.day do + User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00 + end + + travel_to Time.new(2004, 11, 24, 01, 04, 44) do + User.create.created_at # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + end + + Time.now # => 2013-11-09 15:34:49 -05:00 + + This module is included in `ActiveSupport::TestCase` automatically. + + *Prem Sichanugrist*, *DHH* + * Unify `cattr_*` interface: allow to pass a block to `cattr_reader`. Example: diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 29e2440288..5c1d473161 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -361,7 +361,7 @@ module ActiveSupport # # cache.write("bim", "bam") # cache.fetch_multi("bim", "boom") {|key| key * 2 } - # #=> ["bam", "boomboom"] + # # => ["bam", "boomboom"] # def fetch_multi(*names) options = names.extract_options! diff --git a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb index 6daa828b24..0cf955b889 100644 --- a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb +++ b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb @@ -173,7 +173,7 @@ class Class # end # end # - # Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red] + # Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red] def cattr_accessor(*syms, &blk) cattr_reader(*syms) cattr_writer(*syms, &blk) diff --git a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb index 42fece6c28..dc86c92003 100644 --- a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb +++ b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb @@ -4,8 +4,8 @@ class Hash # h1 = { x: { y: [4, 5, 6] }, z: [7, 8, 9] } # h2 = { x: { y: [7, 8, 9] }, z: 'xyz' } # - # h1.deep_merge(h2) # => {:x=>{:y=>[7, 8, 9]}, :z=>"xyz"} - # h2.deep_merge(h1) # => {:x=>{:y=>[4, 5, 6]}, :z=>[7, 8, 9]} + # h1.deep_merge(h2) # => {x: {y: [7, 8, 9]}, z: "xyz"} + # h2.deep_merge(h1) # => {x: {y: [4, 5, 6]}, z: [7, 8, 9]} # h1.deep_merge(h2) { |key, old, new| Array.wrap(old) + Array.wrap(new) } # # => {:x=>{:y=>[4, 5, 6, 7, 8, 9]}, :z=>[7, 8, 9, "xyz"]} def deep_merge(other_hash, &block) diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb index 1845e74c45..f35c2be4c2 100644 --- a/activesupport/lib/active_support/core_ext/hash/keys.rb +++ b/activesupport/lib/active_support/core_ext/hash/keys.rb @@ -27,7 +27,7 @@ class Hash # hash = { name: 'Rob', age: '28' } # # hash.stringify_keys - # # => {"name"=>"Rob", "age"=>"28"} + # # => { "name" => "Rob", "age" => "28" } def stringify_keys transform_keys{ |key| key.to_s } end @@ -44,7 +44,7 @@ class Hash # hash = { 'name' => 'Rob', 'age' => '28' } # # hash.symbolize_keys - # # => {"name"=>"Rob", "age"=>"28"} + # # => { name: "Rob", age: "28" } def symbolize_keys transform_keys{ |key| key.to_sym rescue key } end diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb index 8a5eb4bc93..f9ff4d9567 100644 --- a/activesupport/lib/active_support/core_ext/object/blank.rb +++ b/activesupport/lib/active_support/core_ext/object/blank.rb @@ -90,7 +90,7 @@ class String # ' '.blank? # => true # ' something here '.blank? # => false def blank? - self !~ /[^[:space:]]/ + self =~ /\A[[:space:]]*\z/ end end diff --git a/activesupport/lib/active_support/core_ext/object/deep_dup.rb b/activesupport/lib/active_support/core_ext/object/deep_dup.rb index 1d639f3af6..2e99f4a1b8 100644 --- a/activesupport/lib/active_support/core_ext/object/deep_dup.rb +++ b/activesupport/lib/active_support/core_ext/object/deep_dup.rb @@ -8,8 +8,8 @@ class Object # dup = object.deep_dup # dup.instance_variable_set(:@a, 1) # - # object.instance_variable_defined?(:@a) #=> false - # dup.instance_variable_defined?(:@a) #=> true + # object.instance_variable_defined?(:@a) # => false + # dup.instance_variable_defined?(:@a) # => true def deep_dup duplicable? ? dup : self end @@ -22,8 +22,8 @@ class Array # dup = array.deep_dup # dup[1][2] = 4 # - # array[1][2] #=> nil - # dup[1][2] #=> 4 + # array[1][2] # => nil + # dup[1][2] # => 4 def deep_dup map { |it| it.deep_dup } end @@ -36,8 +36,8 @@ class Hash # dup = hash.deep_dup # dup[:a][:c] = 'c' # - # hash[:a][:c] #=> nil - # dup[:a][:c] #=> "c" + # hash[:a][:c] # => nil + # dup[:a][:c] # => "c" def deep_dup each_with_object(dup) do |(key, value), hash| hash[key.deep_dup] = value.deep_dup diff --git a/activesupport/lib/active_support/core_ext/object/json.rb b/activesupport/lib/active_support/core_ext/object/json.rb index 5157b0402f..7c11d44f57 100644 --- a/activesupport/lib/active_support/core_ext/object/json.rb +++ b/activesupport/lib/active_support/core_ext/object/json.rb @@ -133,7 +133,7 @@ class BigDecimal # BigDecimal, it still has the chance to post-process the string and get the # real value. # - # Use <tt>ActiveSupport.use_standard_json_big_decimal_format = true</tt> to + # Use <tt>ActiveSupport.encode_big_decimal_as_string = true</tt> to # override this behavior. def as_json(options = nil) #:nodoc: if finite? @@ -164,7 +164,7 @@ end class Array def as_json(options = nil) #:nodoc: - map { |v| v.as_json(options && options.dup) } + map { |v| options ? v.as_json(options.dup) : v.as_json } end def encode_json(encoder) #:nodoc: @@ -187,7 +187,7 @@ class Hash self end - Hash[subset.map { |k, v| [k.to_s, v.as_json(options && options.dup)] }] + Hash[subset.map { |k, v| [k.to_s, options ? v.as_json(options.dup) : v.as_json] }] end def encode_json(encoder) #:nodoc: diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb index ee3b6d2b3f..d94e1bfca2 100644 --- a/activesupport/lib/active_support/core_ext/string/access.rb +++ b/activesupport/lib/active_support/core_ext/string/access.rb @@ -8,22 +8,22 @@ class String # the beginning of the range is greater than the end of the string. # # str = "hello" - # str.at(0) #=> "h" - # str.at(1..3) #=> "ell" - # str.at(-2) #=> "l" - # str.at(-2..-1) #=> "lo" - # str.at(5) #=> nil - # str.at(5..-1) #=> "" + # str.at(0) # => "h" + # str.at(1..3) # => "ell" + # str.at(-2) # => "l" + # str.at(-2..-1) # => "lo" + # str.at(5) # => nil + # str.at(5..-1) # => "" # # If a Regexp is given, the matching portion of the string is returned. # If a String is given, that given string is returned if it occurs in # the string. In both cases, nil is returned if there is no match. # # str = "hello" - # str.at(/lo/) #=> "lo" - # str.at(/ol/) #=> nil - # str.at("lo") #=> "lo" - # str.at("ol") #=> nil + # str.at(/lo/) # => "lo" + # str.at(/ol/) # => nil + # str.at("lo") # => "lo" + # str.at("ol") # => nil def at(position) self[position] end @@ -32,15 +32,15 @@ class String # If the position is negative, it is counted from the end of the string. # # str = "hello" - # str.from(0) #=> "hello" - # str.from(3) #=> "lo" - # str.from(-2) #=> "lo" + # str.from(0) # => "hello" + # str.from(3) # => "lo" + # str.from(-2) # => "lo" # # You can mix it with +to+ method and do fun things like: # # str = "hello" - # str.from(0).to(-1) #=> "hello" - # str.from(1).to(-2) #=> "ell" + # str.from(0).to(-1) # => "hello" + # str.from(1).to(-2) # => "ell" def from(position) self[position..-1] end @@ -49,15 +49,15 @@ class String # If the position is negative, it is counted from the end of the string. # # str = "hello" - # str.to(0) #=> "h" - # str.to(3) #=> "hell" - # str.to(-2) #=> "hell" + # str.to(0) # => "h" + # str.to(3) # => "hell" + # str.to(-2) # => "hell" # # You can mix it with +from+ method and do fun things like: # # str = "hello" - # str.from(0).to(-1) #=> "hello" - # str.from(1).to(-2) #=> "ell" + # str.from(0).to(-1) # => "hello" + # str.from(1).to(-2) # => "ell" def to(position) self[0, position + 1] end @@ -67,11 +67,11 @@ class String # given limit is greater than or equal to the string length, returns self. # # str = "hello" - # str.first #=> "h" - # str.first(1) #=> "h" - # str.first(2) #=> "he" - # str.first(0) #=> "" - # str.first(6) #=> "hello" + # str.first # => "h" + # str.first(1) # => "h" + # str.first(2) # => "he" + # str.first(0) # => "" + # str.first(6) # => "hello" def first(limit = 1) if limit == 0 '' @@ -87,11 +87,11 @@ class String # the given limit is greater than or equal to the string length, returns self. # # str = "hello" - # str.last #=> "o" - # str.last(1) #=> "o" - # str.last(2) #=> "lo" - # str.last(0) #=> "" - # str.last(6) #=> "hello" + # str.last # => "o" + # str.last(1) # => "o" + # str.last(2) # => "lo" + # str.last(0) # => "" + # str.last(6) # => "hello" def last(limit = 1) if limit == 0 '' diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index 6691fc0995..3e0cb8a7ac 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -36,20 +36,20 @@ class String # Converts a string to a Date value. # - # "1-1-2012".to_date #=> Sun, 01 Jan 2012 - # "01/01/2012".to_date #=> Sun, 01 Jan 2012 - # "2012-12-13".to_date #=> Thu, 13 Dec 2012 - # "12/13/2012".to_date #=> ArgumentError: invalid date + # "1-1-2012".to_date # => Sun, 01 Jan 2012 + # "01/01/2012".to_date # => Sun, 01 Jan 2012 + # "2012-12-13".to_date # => Thu, 13 Dec 2012 + # "12/13/2012".to_date # => ArgumentError: invalid date def to_date ::Date.parse(self, false) unless blank? end # Converts a string to a DateTime value. # - # "1-1-2012".to_datetime #=> Sun, 01 Jan 2012 00:00:00 +0000 - # "01/01/2012 23:59:59".to_datetime #=> Sun, 01 Jan 2012 23:59:59 +0000 - # "2012-12-13 12:50".to_datetime #=> Thu, 13 Dec 2012 12:50:00 +0000 - # "12/13/2012".to_datetime #=> ArgumentError: invalid date + # "1-1-2012".to_datetime # => Sun, 01 Jan 2012 00:00:00 +0000 + # "01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000 + # "2012-12-13 12:50".to_datetime # => Thu, 13 Dec 2012 12:50:00 +0000 + # "12/13/2012".to_datetime # => ArgumentError: invalid date def to_datetime ::DateTime.parse(self, false) unless blank? end diff --git a/activesupport/lib/active_support/core_ext/string/exclude.rb b/activesupport/lib/active_support/core_ext/string/exclude.rb index 114bcb87f0..0ac684f6ee 100644 --- a/activesupport/lib/active_support/core_ext/string/exclude.rb +++ b/activesupport/lib/active_support/core_ext/string/exclude.rb @@ -2,9 +2,9 @@ class String # The inverse of <tt>String#include?</tt>. Returns true if the string # does not include the other string. # - # "hello".exclude? "lo" #=> false - # "hello".exclude? "ol" #=> true - # "hello".exclude? ?h #=> false + # "hello".exclude? "lo" # => false + # "hello".exclude? "ol" # => true + # "hello".exclude? ?h # => false def exclude?(string) !include?(string) end diff --git a/activesupport/lib/active_support/core_ext/thread.rb b/activesupport/lib/active_support/core_ext/thread.rb index e80f442973..d5a420301a 100644 --- a/activesupport/lib/active_support/core_ext/thread.rb +++ b/activesupport/lib/active_support/core_ext/thread.rb @@ -39,8 +39,8 @@ class Thread # Thread.current.thread_variable_set(:cat, 'meow') # Thread.current.thread_variable_set("dog", 'woof') # end - # thr.join #=> #<Thread:0x401b3f10 dead> - # thr.thread_variables #=> [:dog, :cat] + # thr.join # => #<Thread:0x401b3f10 dead> + # thr.thread_variables # => [:dog, :cat] # # Note that these are not fiber local variables. Please see Thread#thread_variable_get # for more details. @@ -53,8 +53,8 @@ class Thread # # me = Thread.current # me.thread_variable_set(:oliver, "a") - # me.thread_variable?(:oliver) #=> true - # me.thread_variable?(:stanley) #=> false + # me.thread_variable?(:oliver) # => true + # me.thread_variable?(:stanley) # => false # # Note that these are not fiber local variables. Please see Thread#thread_variable_get # for more details. diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index 3da99872c0..f690eab604 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -207,7 +207,7 @@ module ActiveSupport # Replaces the contents of this hash with other_hash. # # h = { "a" => 100, "b" => 200 } - # h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400} + # h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400} def replace(other_hash) super(self.class.new_from_hash_copying_default(other_hash)) end diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb index c96debb93f..eda0edff28 100644 --- a/activesupport/lib/active_support/inflector/inflections.rb +++ b/activesupport/lib/active_support/inflector/inflections.rb @@ -52,21 +52,21 @@ module ActiveSupport # into a non-delimited single lowercase word when passed to +underscore+. # # acronym 'HTML' - # titleize 'html' #=> 'HTML' - # camelize 'html' #=> 'HTML' - # underscore 'MyHTML' #=> 'my_html' + # titleize 'html' # => 'HTML' + # camelize 'html' # => 'HTML' + # underscore 'MyHTML' # => 'my_html' # # The acronym, however, must occur as a delimited unit and not be part of # another word for conversions to recognize it: # # acronym 'HTTP' - # camelize 'my_http_delimited' #=> 'MyHTTPDelimited' - # camelize 'https' #=> 'Https', not 'HTTPs' - # underscore 'HTTPS' #=> 'http_s', not 'https' + # camelize 'my_http_delimited' # => 'MyHTTPDelimited' + # camelize 'https' # => 'Https', not 'HTTPs' + # underscore 'HTTPS' # => 'http_s', not 'https' # # acronym 'HTTPS' - # camelize 'https' #=> 'HTTPS' - # underscore 'HTTPS' #=> 'https' + # camelize 'https' # => 'HTTPS' + # underscore 'HTTPS' # => 'https' # # Note: Acronyms that are passed to +pluralize+ will no longer be # recognized, since the acronym will not occur as a delimited unit in the @@ -74,25 +74,25 @@ module ActiveSupport # form as an acronym as well: # # acronym 'API' - # camelize(pluralize('api')) #=> 'Apis' + # camelize(pluralize('api')) # => 'Apis' # # acronym 'APIs' - # camelize(pluralize('api')) #=> 'APIs' + # camelize(pluralize('api')) # => 'APIs' # # +acronym+ may be used to specify any word that contains an acronym or # otherwise needs to maintain a non-standard capitalization. The only # restriction is that the word must begin with a capital letter. # # acronym 'RESTful' - # underscore 'RESTful' #=> 'restful' - # underscore 'RESTfulController' #=> 'restful_controller' - # titleize 'RESTfulController' #=> 'RESTful Controller' - # camelize 'restful' #=> 'RESTful' - # camelize 'restful_controller' #=> 'RESTfulController' + # underscore 'RESTful' # => 'restful' + # underscore 'RESTfulController' # => 'restful_controller' + # titleize 'RESTfulController' # => 'RESTful Controller' + # camelize 'restful' # => 'RESTful' + # camelize 'restful_controller' # => 'RESTfulController' # # acronym 'McDonald' - # underscore 'McDonald' #=> 'mcdonald' - # camelize 'mcdonald' #=> 'McDonald' + # underscore 'McDonald' # => 'mcdonald' + # camelize 'mcdonald' # => 'McDonald' def acronym(word) @acronyms[word.downcase] = word @acronym_regex = /#{@acronyms.values.join("|")}/ diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index e193163d17..2fb5c04316 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -7,6 +7,7 @@ require 'active_support/testing/deprecation' require 'active_support/testing/declarative' require 'active_support/testing/isolation' require 'active_support/testing/constant_lookup' +require 'active_support/testing/time_helpers' require 'active_support/core_ext/kernel/reporting' require 'active_support/deprecation' @@ -34,6 +35,7 @@ module ActiveSupport include ActiveSupport::Testing::SetupAndTeardown include ActiveSupport::Testing::Assertions include ActiveSupport::Testing::Deprecation + include ActiveSupport::Testing::TimeHelpers extend ActiveSupport::Testing::Declarative # test/unit backwards compatibility methods diff --git a/activesupport/lib/active_support/testing/time_helpers.rb b/activesupport/lib/active_support/testing/time_helpers.rb new file mode 100644 index 0000000000..94230e56ba --- /dev/null +++ b/activesupport/lib/active_support/testing/time_helpers.rb @@ -0,0 +1,55 @@ +module ActiveSupport + module Testing + # Containing helpers that helps you test passage of time. + module TimeHelpers + # Change current time to the time in the future or in the past by a given time difference by + # stubbing +Time.now+ and +Date.today+. Note that the stubs are automatically removed + # at the end of each test. + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # travel 1.day + # Time.current # => Sun, 10 Nov 2013 15:34:49 EST -05:00 + # Date.current # => Sun, 10 Nov 2013 + # + # This method also accepts a block, which will return the current time back to its original + # state at the end of the block: + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # travel 1.day do + # User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00 + # end + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + def travel(duration, &block) + travel_to Time.now + duration, &block + end + + # Change current time to the given time by stubbing +Time.now+ and +Date.today+ to return the + # time or date passed into this method. Note that the stubs are automatically removed + # at the end of each test. + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # travel_to Time.new(2004, 11, 24, 01, 04, 44) + # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + # Date.current # => Wed, 24 Nov 2004 + # + # This method also accepts a block, which will return the current time back to its original + # state at the end of the block: + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # travel_to Time.new(2004, 11, 24, 01, 04, 44) do + # User.create.created_at # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + # end + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + def travel_to(date_or_time, &block) + Time.stubs now: date_or_time.to_time + Date.stubs today: date_or_time.to_date + + if block_given? + block.call + Time.unstub :now + Date.unstub :today + end + end + end + end +end diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 39da760bf2..00f43be6d4 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -32,6 +32,12 @@ class TestJSONEncoding < ActiveSupport::TestCase end end + class OptionsTest + def as_json(options = :default) + options + end + end + class HashWithAsJson < Hash attr_accessor :as_json_called @@ -332,6 +338,16 @@ class TestJSONEncoding < ActiveSupport::TestCase "other_hash" => {"foo"=>"other_foo","test"=>"other_test"}}, ActiveSupport::JSON.decode(hash.to_json)) end + def test_hash_as_json_without_options + json = { foo: OptionsTest.new }.as_json + assert_equal({"foo" => :default}, json) + end + + def test_array_as_json_without_options + json = [ OptionsTest.new ].as_json + assert_equal([:default], json) + end + def test_struct_encoding Struct.new('UserNameAndEmail', :name, :email) Struct.new('UserNameAndDate', :name, :date) diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb index 0c8cc1f883..5ed2da7e8b 100644 --- a/activesupport/test/test_test.rb +++ b/activesupport/test/test_test.rb @@ -1,4 +1,6 @@ require 'abstract_unit' +require 'active_support/core_ext/date' +require 'active_support/core_ext/numeric/time' class AssertDifferenceTest < ActiveSupport::TestCase def setup @@ -122,7 +124,6 @@ class SetupAndTeardownTest < ActiveSupport::TestCase end end - class SubclassSetupAndTeardownTest < SetupAndTeardownTest setup :bar teardown :bar @@ -143,7 +144,6 @@ class SubclassSetupAndTeardownTest < SetupAndTeardownTest end end - class TestCaseTaggedLoggingTest < ActiveSupport::TestCase def before_setup require 'stringio' @@ -156,3 +156,49 @@ class TestCaseTaggedLoggingTest < ActiveSupport::TestCase assert_match "#{self.class}: #{name}\n", @out.string end end + +class TimeHelperTest < ActiveSupport::TestCase + setup do + Time.stubs now: Time.now + end + + def test_time_helper_travel + expected_time = Time.now + 1.day + travel 1.day + + assert_equal expected_time, Time.now + assert_equal expected_time.to_date, Date.today + end + + def test_time_helper_travel_with_block + expected_time = Time.now + 1.day + + travel 1.day do + assert_equal expected_time, Time.now + assert_equal expected_time.to_date, Date.today + end + + assert_not_equal expected_time, Time.now + assert_not_equal expected_time.to_date, Date.today + end + + def test_time_helper_travel_to + expected_time = Time.new(2004, 11, 24, 01, 04, 44) + travel_to expected_time + + assert_equal expected_time, Time.now + assert_equal Date.new(2004, 11, 24), Date.today + end + + def test_time_helper_travel_to_with_block + expected_time = Time.new(2004, 11, 24, 01, 04, 44) + + travel_to expected_time do + assert_equal expected_time, Time.now + assert_equal Date.new(2004, 11, 24), Date.today + end + + assert_not_equal expected_time, Time.now + assert_not_equal Date.new(2004, 11, 24), Date.today + end +end diff --git a/guides/source/2_2_release_notes.md b/guides/source/2_2_release_notes.md index 7db4cf07e7..c11d1240c4 100644 --- a/guides/source/2_2_release_notes.md +++ b/guides/source/2_2_release_notes.md @@ -327,7 +327,7 @@ Other features of memoization include `unmemoize`, `unmemoize_all`, and `memoize The `each_with_object` method provides an alternative to `inject`, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block. ```ruby -%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'} +%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } # => {'foo' => 'FOO', 'bar' => 'BAR'} ``` Lead Contributor: [Adam Keys](http://therealadam.com/) diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index 0c06e36de9..de9ead78a6 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -348,7 +348,7 @@ For most stores, this ID is used to look up the session data on the server, e.g. The CookieStore can store around 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. -If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time. +If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using `ActionDispatch::Session::CacheStore`. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time. Read more about session storage in the [Security Guide](security.html). diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index cf0249a400..94b8453f04 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -473,7 +473,7 @@ In the case of a belongs_to relationship, an association key can be used to spec ```ruby Post.where(author: author) -Author.joins(:posts).where(posts: {author: author}) +Author.joins(:posts).where(posts: { author: author }) ``` NOTE: The values cannot be symbols. For example, you cannot do `Client.where(status: :active)`. @@ -685,9 +685,9 @@ This will return single order objects for each day, but only those that are orde Overriding Conditions --------------------- -### `except` +### `unscope` -You can specify certain conditions to be excepted by using the `except` method. For example: +You can specify certain conditions to be removed using the `unscope` method. For example: ```ruby Post.where('id > 10').limit(20).order('id asc').except(:order) @@ -698,30 +698,24 @@ The SQL that would be executed: ```sql SELECT * FROM posts WHERE id > 10 LIMIT 20 -# Original query without `except` +# Original query without `unscope` SELECT * FROM posts WHERE id > 10 ORDER BY id asc LIMIT 20 ``` -### `unscope` - -The `except` method does not work when the relation is merged. For example: - -```ruby -Post.comments.except(:order) -``` - -will still have an order if the order comes from a default scope on Comment. In order to remove all ordering, even from relations which are merged in, use unscope as follows: +You can additionally unscope specific where clauses. For example: ```ruby -Post.order('id DESC').limit(20).unscope(:order) = Post.limit(20) -Post.order('id DESC').limit(20).unscope(:order, :limit) = Post.all +Post.where(id: 10, trashed: false).unscope(where: :id) +# => SELECT "posts".* FROM "posts" WHERE trashed = 0 ``` -You can additionally unscope specific where clauses. For example: +A relation which has used `unscope` will affect any relation it is +merged in to: ```ruby -Post.where(id: 10).limit(1).unscope({ where: :id }, :limit).order('id DESC') = Post.order('id DESC') +Post.order('id asc').merge(Post.unscope(:order)) +# => SELECT "posts".* FROM "posts" ``` ### `only` @@ -796,6 +790,32 @@ SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC This method accepts **no** arguments. +### `rewhere` + +The `rewhere` method overrides an existing, named where condition. For example: + +```ruby +Post.where(trashed: true).rewhere(trashed: false) +``` + +The SQL that would be executed: + +```sql +SELECT * FROM posts WHERE `trashed` = 0 +``` + +In case the `rewhere` clause is not used, + +```ruby +Post.where(trashed: true).where(trashed: false) +``` + +the SQL executed would be: + +```sql +SELECT * FROM posts WHERE `trashed` = 1 AND `trashed` = 0 +``` + Null Relation ------------- @@ -1022,7 +1042,7 @@ Or, in English: "return all posts that have a comment made by a guest." #### Joining Nested Associations (Multiple Level) ```ruby -Category.joins(posts: [{comments: :guest}, :tags]) +Category.joins(posts: [{ comments: :guest }, :tags]) ``` This produces: @@ -1048,7 +1068,7 @@ An alternative and cleaner syntax is to nest the hash conditions: ```ruby time_range = (Time.now.midnight - 1.day)..Time.now.midnight -Client.joins(:orders).where(orders: {created_at: time_range}) +Client.joins(:orders).where(orders: { created_at: time_range }) ``` This will find all clients who have orders that were created yesterday, again using a `BETWEEN` SQL expression. @@ -1109,7 +1129,7 @@ This loads all the posts and the associated category and comments for each post. #### Nested Associations Hash ```ruby -Category.includes(posts: [{comments: :guest}, :tags]).find(1) +Category.includes(posts: [{ comments: :guest }, :tags]).find(1) ``` This will find the category with id 1 and eager load all of the associated posts, the associated posts' tags and comments, and every comment's guest association. @@ -1610,7 +1630,7 @@ Client.where(first_name: 'Ryan').count You can also use various finder methods on a relation for performing complex calculations: ```ruby -Client.includes("orders").where(first_name: 'Ryan', orders: {status: 'received'}).count +Client.includes("orders").where(first_name: 'Ryan', orders: { status: 'received' }).count ``` Which will execute: diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index 0df52a655f..cbd1ac9bdf 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -175,28 +175,28 @@ class Person < ActiveRecord::Base end >> p = Person.new -#=> #<Person id: nil, name: nil> +# => #<Person id: nil, name: nil> >> p.errors.messages -#=> {} +# => {} >> p.valid? -#=> false +# => false >> p.errors.messages -#=> {name:["can't be blank"]} +# => {name:["can't be blank"]} >> p = Person.create -#=> #<Person id: nil, name: nil> +# => #<Person id: nil, name: nil> >> p.errors.messages -#=> {name:["can't be blank"]} +# => {name:["can't be blank"]} >> p.save -#=> false +# => false >> p.save! -#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank +# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank >> Person.create! -#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank +# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank ``` `invalid?` is simply the inverse of `valid?`. It triggers your validations, diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 84a169b3b9..452ddf01eb 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -179,14 +179,14 @@ duplicate = array.dup duplicate.push 'another-string' # the object was duplicated, so the element was added only to the duplicate -array #=> ['string'] -duplicate #=> ['string', 'another-string'] +array # => ['string'] +duplicate # => ['string', 'another-string'] duplicate.first.gsub!('string', 'foo') # first element was not duplicated, it will be changed in both arrays -array #=> ['foo'] -duplicate #=> ['foo', 'another-string'] +array # => ['foo'] +duplicate # => ['foo', 'another-string'] ``` As you can see, after duplicating the `Array` instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since `dup` does not make deep copy, the string inside the array is still the same object. @@ -199,8 +199,8 @@ duplicate = array.deep_dup duplicate.first.gsub!('string', 'foo') -array #=> ['string'] -duplicate #=> ['foo'] +array # => ['string'] +duplicate # => ['foo'] ``` If the object is not duplicable, `deep_dup` will just return it: @@ -1554,7 +1554,7 @@ ActiveSupport::Inflector.inflections do |inflect| inflect.acronym 'SSL' end -"SSLError".underscore.camelize #=> "SSLError" +"SSLError".underscore.camelize # => "SSLError" ``` `camelize` is aliased to `camelcase`. diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index b0ab88bf59..0d45e5fb28 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -189,7 +189,7 @@ The main methods to call are `read`, `write`, `delete`, `exist?`, and `fetch`. T There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries. -* `:namespace` - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. The default value will include the application name and Rails environment. +* `:namespace` - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. * `:compress` - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network. diff --git a/guides/source/engines.md b/guides/source/engines.md index af48768fe9..2266b1fd7f 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -253,7 +253,7 @@ The helper inside `app/helpers/blorgh/posts_helper.rb` is also namespaced: ```ruby module Blorgh - class PostsHelper + module PostsHelper ... end end diff --git a/guides/source/i18n.md b/guides/source/i18n.md index 6b36f67874..6f79b3ddd7 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -101,7 +101,7 @@ This means, that in the `:en` locale, the key _hello_ will map to the _Hello wor The I18n library will use **English** as a **default locale**, i.e. if you don't set a different locale, `:en` will be used for looking up translations. -NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Various [Rails I18n plugins](http://rails-i18n.org/wiki) such as [Globalize3](https://github.com/svenfuchs/globalize3) may help you implement it. +NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en)), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Various [Rails I18n plugins](http://rails-i18n.org/wiki) such as [Globalize3](https://github.com/svenfuchs/globalize3) may help you implement it. The **translations load path** (`I18n.load_path`) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you. @@ -1035,7 +1035,7 @@ If you found this guide useful, please consider recommending its authors on [wor Footnotes --------- -[^1]: Or, to quote [Wikipedia](http://en.wikipedia.org/wiki/Internationalization_and_localization:) _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_ +[^1]: Or, to quote [Wikipedia](http://en.wikipedia.org/wiki/Internationalization_and_localization): _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_ [^2]: Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. diff --git a/guides/source/initialization.md b/guides/source/initialization.md index 33eb74dcd9..5e2e0ad3e3 100644 --- a/guides/source/initialization.md +++ b/guides/source/initialization.md @@ -126,7 +126,9 @@ A standard Rails application depends on several gems, specifically: ### `rails/commands.rb` -Once `config/boot.rb` has finished, the next file that is required is `rails/commands` which will execute a command based on the arguments passed in. In this case, the `ARGV` array simply contains `server` which is extracted into the `command` variable using these lines: +Once `config/boot.rb` has finished, the next file that is required is +`rails/commands`, which helps in expanding aliases. In the current case, the +`ARGV` array simply contains `server` which will be passed over: ```ruby ARGV << '--help' if ARGV.empty? @@ -142,31 +144,64 @@ aliases = { command = ARGV.shift command = aliases[command] || command + +require 'rails/commands/commands_tasks' + +Rails::CommandsTasks.new(ARGV).run_command!(command) ``` TIP: As you can see, an empty ARGV list will make Rails show the help snippet. -If we used `s` rather than `server`, Rails will use the `aliases` defined in the file and match them to their respective commands. With the `server` command, Rails will run this code: +If we had used `s` rather than `server`, Rails would have used the `aliases` +defined here to find the matching command. + +### `rails/commands/command_tasks.rb` + +When one types an incorrect rails command, the `run_command` is responsible for +throwing an error message. If the command is valid, a method of the same name +is called. + +```ruby +COMMAND_WHITELIST = %(plugin generate destroy console server dbconsole application runner new version help) + +def run_command!(command) + if COMMAND_WHITELIST.include?(command) + send(command) + else + write_error_message(command) + end +end +``` + +With the `server` command, Rails will further run the following code: ```ruby -when 'server' - # Change to the application's path if there is no config.ru file in current directory. - # This allows us to run `rails server` from other directories, but still get - # the main config.ru and properly set the tmp directory. - Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exist?(File.expand_path("config.ru")) +def set_application_directory! + Dir.chdir(File.expand_path('../../', APP_PATH)) unless + File.exist?(File.expand_path("config.ru")) +end + +def server + set_application_directory! + require_command!("server") - require 'rails/commands/server' Rails::Server.new.tap do |server| - # We need to require application after the server sets environment, - # otherwise the --environment option given to the server won't propagate. require APP_PATH Dir.chdir(Rails.application.root) server.start end +end + +def require_command!(command) + require "rails/commands/#{command}" +end ``` -This file will change into the Rails root directory (a path two directories up from `APP_PATH` which points at `config/application.rb`), but only if the `config.ru` file isn't found. This then requires `rails/commands/server` which sets up the `Rails::Server` class. +This file will change into the Rails root directory (a path two directories up +from `APP_PATH` which points at `config/application.rb`), but only if the +`config.ru` file isn't found. This then requires `rails/commands/server` which +sets up the `Rails::Server` class. ```ruby require 'fileutils' @@ -294,37 +329,43 @@ and it's free for you to change based on your needs. ### `Rails::Server#start` -After `config/application` is loaded, `server.start` is called. This method is defined like this: +After `config/application` is loaded, `server.start` is called. This method is +defined like this: ```ruby def start - url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}" - puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" - puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}" - puts "=> Run `rails server -h` for more startup options" + print_boot_information trap(:INT) { exit } - puts "=> Ctrl-C to shutdown server" unless options[:daemonize] + create_tmp_directories + log_to_stdout if options[:log_stdout] + + super + ... +end - #Create required tmp directories if not found - %w(cache pids sessions sockets).each do |dir_to_make| - FileUtils.mkdir_p(Rails.root.join('tmp', dir_to_make)) +private + + def print_boot_information + ... + puts "=> Run `rails server -h` for more startup options" + puts "=> Ctrl-C to shutdown server" unless options[:daemonize] + end + + def create_tmp_directories + %w(cache pids sessions sockets).each do |dir_to_make| + FileUtils.mkdir_p(File.join(Rails.root, 'tmp', dir_to_make)) + end end - unless options[:daemonize] + def log_to_stdout wrapped_app # touch the app so the logger is set up console = ActiveSupport::Logger.new($stdout) console.formatter = Rails.logger.formatter + console.level = Rails.logger.level Rails.logger.extend(ActiveSupport::Logger.broadcast(console)) end - - super -ensure - # The '-h' option calls exit before @options is set. - # If we call 'options' with it unset, we get double help banners. - puts 'Exiting' unless @options && options[:daemonize] -end ``` This is where the first output of the Rails initialization happens. This diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 7ef54a45bc..b42c8fb81b 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -182,18 +182,17 @@ You can swap an existing middleware in the middleware stack using `config.middle config.middleware.swap ActionDispatch::ShowExceptions, Lifo::ShowExceptions ``` -#### Middleware Stack is an Enumerable +#### Deleting a Middleware -The middleware stack behaves just like a normal `Enumerable`. You can use any `Enumerable` methods to manipulate or interrogate the stack. The middleware stack also implements some `Array` methods including `[]`, `unshift` and `delete`. Methods described in the section above are just convenience methods. - -Append following lines to your application configuration: +Add the following lines to your application configuration: ```ruby # config/application.rb config.middleware.delete "Rack::Lock" ``` -And now if you inspect the middleware stack, you'll find that `Rack::Lock` will not be part of it. +And now if you inspect the middleware stack, you'll find that `Rack::Lock` is +not a part of it. ```bash $ rake middleware @@ -319,26 +318,6 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol TIP: It's possible to use any of the above middlewares in your custom Rack stack. -### Using Rack Builder - -The following shows how to replace use `Rack::Builder` instead of the Rails supplied `MiddlewareStack`. - -<strong>Clear the existing Rails middleware stack</strong> - -```ruby -# config/application.rb -config.middleware.clear -``` - -<br> -<strong>Add a `config.ru` file to `Rails.root`</strong> - -```ruby -# config.ru -use MyOwnStackFromScratch -run Rails.application -``` - Resources --------- diff --git a/guides/source/ruby_on_rails_guides_guidelines.md b/guides/source/ruby_on_rails_guides_guidelines.md index 5564b0648b..8faf03e58c 100644 --- a/guides/source/ruby_on_rails_guides_guidelines.md +++ b/guides/source/ruby_on_rails_guides_guidelines.md @@ -51,7 +51,7 @@ Use the same typography as in regular text: API Documentation Guidelines ---------------------------- -The guides and the API should be coherent and consistent where appropriate. Please have a look at these particular sections of the [API Documentation Guidelines](api_documentation_guidelines.html:) +The guides and the API should be coherent and consistent where appropriate. Please have a look at these particular sections of the [API Documentation Guidelines](api_documentation_guidelines.html): * [Wording](api_documentation_guidelines.html#wording) * [Example Code](api_documentation_guidelines.html#example-code) diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index 3822486412..21ac596ab9 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,3 +1,12 @@ +* Remove turbolinks when generating a new application based on a template that skips it. + + Example: + + Skips turbolinks adding `add_gem_entry_filter { |gem| gem.name != "turbolinks" }` + to the template. + + *Lauro Caetano* + * Instrument an `load_config_initializer.railties` event on each load of configuration initializer from `config/initializers`. Subscribers should be attached before `load_config_initializers` initializer completed. diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb index 2b77d5d387..dd2ee5639e 100644 --- a/railties/lib/rails/commands/runner.rb +++ b/railties/lib/rails/commands/runner.rb @@ -50,5 +50,5 @@ elsif File.exist?(code_or_file) $0 = code_or_file Kernel.load code_or_file else - eval(code_or_file) + eval(code_or_file, binding, __FILE__, __LINE__) end diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 3f109debdc..54a0f1c002 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -260,7 +260,7 @@ module Rails # # class FooController < ApplicationController # def index - # my_engine.root_url #=> /my_engine/ + # my_engine.root_url # => /my_engine/ # end # end # @@ -269,7 +269,7 @@ module Rails # module MyEngine # class BarController # def index - # main_app.foo_path #=> /foo + # main_app.foo_path # => /foo # end # end # end diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index d79cf2b2f0..2022b4ed3d 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -113,7 +113,7 @@ module Rails end def add_gem_entry_filter - @gem_filter = lambda { |next_filter,entry| + @gem_filter = lambda { |next_filter, entry| yield(entry) && next_filter.call(entry) }.curry[@gem_filter] end diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt index 8b91313e51..07ea09cdbd 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt @@ -13,6 +13,8 @@ <% unless options[:skip_javascript] -%> //= require <%= options[:javascript] %> //= require <%= options[:javascript] %>_ujs +<% if gemfile_entries.any? { |m| m.name == "turbolinks" } -%> //= require turbolinks <% end -%> +<% end -%> //= require_tree . diff --git a/railties/lib/rails/generators/rails/app/templates/public/404.html b/railties/lib/rails/generators/rails/app/templates/public/404.html index 7d99be2ecf..b612547fc2 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/404.html +++ b/railties/lib/rails/generators/rails/app/templates/public/404.html @@ -58,10 +58,10 @@ <!-- This file lives in public/404.html --> <div class="dialog"> <div> - <h1>The page you were looking for doesn't exist.</h1> - <p>You may have mistyped the address or the page may have moved.</p> + <h1>The page you were looking for doesn't exist.</h1> + <p>You may have mistyped the address or the page may have moved.</p> </div> - <p>If you are the application owner check the logs for more information.</p> + <p>If you are the application owner check the logs for more information.</p> </div> </body> </html> diff --git a/railties/lib/rails/generators/rails/app/templates/public/422.html b/railties/lib/rails/generators/rails/app/templates/public/422.html index ee18eeb10c..a21f82b3bd 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/422.html +++ b/railties/lib/rails/generators/rails/app/templates/public/422.html @@ -58,10 +58,10 @@ <!-- This file lives in public/422.html --> <div class="dialog"> <div> - <h1>The change you wanted was rejected.</h1> - <p>Maybe you tried to change something you didn't have access to.</p> + <h1>The change you wanted was rejected.</h1> + <p>Maybe you tried to change something you didn't have access to.</p> </div> - <p>If you are the application owner check the logs for more information.</p> + <p>If you are the application owner check the logs for more information.</p> </div> </body> </html> diff --git a/railties/lib/rails/generators/rails/app/templates/public/500.html b/railties/lib/rails/generators/rails/app/templates/public/500.html index e4161c3ce5..061abc587d 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/500.html +++ b/railties/lib/rails/generators/rails/app/templates/public/500.html @@ -58,9 +58,9 @@ <!-- This file lives in public/500.html --> <div class="dialog"> <div> - <h1>We're sorry, but something went wrong.</h1> + <h1>We're sorry, but something went wrong.</h1> </div> - <p>If you are the application owner check the logs for more information.</p> + <p>If you are the application owner check the logs for more information.</p> </div> </body> </html> diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index fa5668a5b5..85ea11b4e7 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -13,10 +13,12 @@ class Rails::InfoController < ActionController::Base # :nodoc: def properties @info = Rails::Info.to_html + @page_title = 'Properties' end def routes @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes) + @page_title = 'Routes' end protected diff --git a/railties/lib/rails/templates/layouts/application.html.erb b/railties/lib/rails/templates/layouts/application.html.erb index 7352d48e7b..50a4755e45 100644 --- a/railties/lib/rails/templates/layouts/application.html.erb +++ b/railties/lib/rails/templates/layouts/application.html.erb @@ -2,7 +2,7 @@ <html lang="en"> <head> <meta charset="utf-8" /> - <title>Routes</title> + <title><%= @page_title %></title> <style> body { background-color: #fff; color: #333; } diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb index 9145cb6936..42096cfec4 100644 --- a/railties/test/application/middleware/exceptions_test.rb +++ b/railties/test/application/middleware/exceptions_test.rb @@ -73,7 +73,7 @@ module ApplicationTests assert_nothing_raised(ActionController::RoutingError) do get '/foo' - assert_match "The page you were looking for doesn't exist.", last_response.body + assert_match "The page you were looking for doesn't exist.", last_response.body end end diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index 2169304aa4..08316d80e6 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -111,7 +111,7 @@ module ApplicationTests RUBY output = Dir.chdir(app_path){ `rake routes` } - assert_equal "Prefix Verb URI Pattern Controller#Action\ncart GET /cart(.:format) cart#show\n", output + assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output end def test_rake_routes_with_controller_environment @@ -124,7 +124,7 @@ module ApplicationTests ENV['CONTROLLER'] = 'cart' output = Dir.chdir(app_path){ `rake routes` } - assert_equal "Prefix Verb URI Pattern Controller#Action\ncart GET /cart(.:format) cart#show\n", output + assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output end def test_rake_routes_displays_message_when_no_routes_are_defined diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index e6cda07ae5..6f03cf3083 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -29,6 +29,7 @@ DEFAULT_APP_FILES = %w( lib/tasks lib/assets log + test/test_helper.rb test/fixtures test/controllers test/models @@ -37,6 +38,8 @@ DEFAULT_APP_FILES = %w( test/integration vendor vendor/assets + vendor/assets/stylesheets + vendor/assets/javascripts tmp/cache tmp/cache/assets ) @@ -58,6 +61,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file("app/views/layouts/application.html.erb", /stylesheet_link_tag\s+"application", media: "all", "data-turbolinks-track" => true/) assert_file("app/views/layouts/application.html.erb", /javascript_include_tag\s+"application", "data-turbolinks-track" => true/) assert_file("app/assets/stylesheets/application.css") + assert_file("app/assets/javascripts/application.js") end def test_invalid_application_name_raises_an_error @@ -182,7 +186,7 @@ class AppGeneratorTest < Rails::Generators::TestCase template.unlink end - def test_application_html_checks_gems + def test_skip_turbolinks_when_it_is_not_on_gemfile template = Tempfile.open 'my_template' template.puts 'add_gem_entry_filter { |gem| gem.name != "turbolinks" }' template.flush @@ -191,10 +195,16 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "Gemfile" do |contents| assert_no_match 'turbolinks', contents end - assert_file "Gemfile" do |contents| + + assert_file "app/views/layouts/application.html.erb" do |contents| assert_no_match 'turbolinks', contents end + assert_file "app/views/layouts/application.html.erb" do |contents| + assert_no_match('data-turbolinks-track', contents) + end + + assert_file "app/assets/javascripts/application.js" do |contents| assert_no_match 'turbolinks', contents end ensure @@ -312,33 +322,13 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_creation_of_a_test_directory - run_generator - assert_file 'test' - end - - def test_creation_of_app_assets_images_directory - run_generator - assert_file "app/assets/images" - end - - def test_creation_of_vendor_assets_javascripts_directory - run_generator - assert_file "vendor/assets/javascripts" - end - - def test_creation_of_vendor_assets_stylesheets_directory - run_generator - assert_file "vendor/assets/stylesheets" - end - def test_jquery_is_the_default_javascript_library run_generator assert_file "app/assets/javascripts/application.js" do |contents| assert_match %r{^//= require jquery}, contents assert_match %r{^//= require jquery_ujs}, contents end - assert_file "Gemfile", /^gem 'jquery-rails'/ + assert_gem "jquery-rails" end def test_other_javascript_libraries @@ -363,6 +353,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "Gemfile" do |content| assert_no_match(/coffee-rails/, content) + assert_no_match(/jquery-rails/, content) end end diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb index 9c664a903a..2268f04839 100644 --- a/railties/test/generators/controller_generator_test.rb +++ b/railties/test/generators/controller_generator_test.rb @@ -43,6 +43,12 @@ class ControllerGeneratorTest < Rails::Generators::TestCase assert_file "app/assets/stylesheets/account.css" end + def test_does_not_invoke_assets_if_required + run_generator ["account", "--skip-assets"] + assert_no_file "app/assets/javascripts/account.js" + assert_no_file "app/assets/stylesheets/account.css" + end + def test_invokes_default_test_framework run_generator assert_file "test/controllers/account_controller_test.rb" diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index 068eb66bc6..c6b91e7cba 100644 --- a/railties/test/generators/plugin_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -293,7 +293,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_file "Gemfile" do |contents| assert_no_match('gemspec', contents) assert_match(/gem "rails", "~> #{Rails.version}"/, contents) - assert_match(/group :development do\n gem "sqlite3"\nend/, contents) + assert_match_sqlite3(contents) assert_no_match(/# gem "jquery-rails"/, contents) end end @@ -304,7 +304,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_file "Gemfile" do |contents| assert_no_match('gemspec', contents) assert_match(/gem "rails", "~> #{Rails.version}"/, contents) - assert_match(/group :development do\n gem "sqlite3"\nend/, contents) + assert_match_sqlite3(contents) end end @@ -347,4 +347,12 @@ protected def default_files ::DEFAULT_PLUGIN_FILES end + + def assert_match_sqlite3(contents) + unless defined?(JRUBY_VERSION) + assert_match(/group :development do\n gem "sqlite3"\nend/, contents) + else + assert_match(/group :development do\n gem "activerecord-jdbcsqlite3-adapter"\nend/, contents) + end + end end diff --git a/railties/test/generators/task_generator_test.rb b/railties/test/generators/task_generator_test.rb index 9399be9510..d5bd44b9db 100644 --- a/railties/test/generators/task_generator_test.rb +++ b/railties/test/generators/task_generator_test.rb @@ -7,6 +7,18 @@ class TaskGeneratorTest < Rails::Generators::TestCase def test_task_is_created run_generator - assert_file "lib/tasks/feeds.rake", /namespace :feeds/ + assert_file "lib/tasks/feeds.rake" do |content| + assert_match(/namespace :feeds/, content) + assert_match(/task foo:/, content) + assert_match(/task bar:/, content) + end + end + + def test_task_on_revoke + task_path = 'lib/tasks/feeds.rake' + run_generator + assert_file task_path + run_generator ['feeds'], behavior: :revoke + assert_no_file task_path end end |