From d22e522179c1c90e658c3ed0e9b972ec62306209 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 6 Aug 2016 19:37:57 +0200 Subject: [PATCH] modernizes hash syntax in activerecord --- activerecord/Rakefile | 26 +- .../lib/active_record/associations.rb | 2 +- .../active_record/associations/association.rb | 2 +- .../associations/has_many_association.rb | 4 +- .../has_many_through_association.rb | 4 +- .../associations/join_dependency/join_part.rb | 2 +- .../associations/through_association.rb | 2 +- .../lib/active_record/autosave_association.rb | 6 +- activerecord/lib/active_record/callbacks.rb | 2 +- .../abstract/connection_pool.rb | 6 +- .../abstract/query_cache.rb | 2 +- .../abstract/schema_statements.rb | 2 +- .../abstract_mysql_adapter.rb | 4 +- .../connection_adapters/mysql2_adapter.rb | 4 +- .../connection_adapters/schema_cache.rb | 6 +- .../connection_adapters/sqlite3_adapter.rb | 12 +- .../lib/active_record/connection_handling.rb | 2 +- activerecord/lib/active_record/fixtures.rb | 4 +- activerecord/lib/active_record/integration.rb | 2 +- .../lib/active_record/locking/pessimistic.rb | 2 +- activerecord/lib/active_record/migration.rb | 2 +- .../lib/active_record/nested_attributes.rb | 2 +- activerecord/lib/active_record/railtie.rb | 4 +- .../lib/active_record/railties/databases.rake | 82 ++--- activerecord/lib/active_record/reflection.rb | 2 +- .../lib/active_record/relation/delegation.rb | 4 +- .../lib/active_record/tasks/database_tasks.rb | 2 +- .../migration/migration_generator.rb | 2 +- .../active_record/model/model_generator.rb | 2 +- activerecord/test/cases/adapter_test.rb | 14 +- .../adapters/mysql2/active_schema_test.rb | 30 +- .../adapters/mysql2/bind_parameter_test.rb | 4 +- .../adapters/mysql2/case_sensitivity_test.rb | 24 +- .../cases/adapters/mysql2/connection_test.rb | 4 +- .../adapters/mysql2/reserved_word_test.rb | 6 +- .../adapters/postgresql/active_schema_test.rb | 4 +- .../adapters/postgresql/bit_string_test.rb | 2 +- .../adapters/postgresql/connection_test.rb | 8 +- .../adapters/postgresql/geometric_test.rb | 20 +- .../cases/adapters/postgresql/hstore_test.rb | 6 +- .../postgresql/postgresql_adapter_test.rb | 4 +- .../postgresql/schema_authorization_test.rb | 4 +- .../cases/adapters/postgresql/schema_test.rb | 10 +- .../adapters/postgresql/timestamp_test.rb | 10 +- .../cases/adapters/sqlite3/copy_table_test.rb | 4 +- .../sqlite3/sqlite3_create_folder_test.rb | 6 +- activerecord/test/cases/aggregations_test.rb | 4 +- activerecord/test/cases/ar_schema_test.rb | 8 +- .../belongs_to_associations_test.rb | 102 +++--- .../test/cases/associations/callbacks_test.rb | 32 +- .../cascaded_eager_loading_test.rb | 44 +-- ...eager_load_includes_full_sti_class_test.rb | 6 +- .../eager_load_nested_include_test.rb | 40 +-- .../eager_singularization_test.rb | 28 +- .../test/cases/associations/eager_test.rb | 328 +++++++++--------- ...s_and_belongs_to_many_associations_test.rb | 92 ++--- .../has_many_associations_test.rb | 224 ++++++------ .../has_many_through_associations_test.rb | 152 ++++---- .../associations/has_one_associations_test.rb | 74 ++-- .../has_one_through_associations_test.rb | 48 +-- .../inner_join_association_test.rb | 10 +- .../associations/inverse_associations_test.rb | 50 +-- .../cases/associations/join_model_test.rb | 102 +++--- .../left_outer_join_association_test.rb | 6 +- .../nested_through_associations_test.rb | 4 +- activerecord/test/cases/associations_test.rb | 64 ++-- .../test/cases/autosave_association_test.rb | 132 +++---- activerecord/test/cases/base_test.rb | 106 +++--- activerecord/test/cases/batches_test.rb | 30 +- activerecord/test/cases/binary_test.rb | 4 +- .../test/cases/bind_parameter_test.rb | 8 +- activerecord/test/cases/calculations_test.rb | 36 +- activerecord/test/cases/callbacks_test.rb | 14 +- .../test/cases/column_definition_test.rb | 2 +- .../connection_specification_test.rb | 2 +- activerecord/test/cases/core_test.rb | 4 +- activerecord/test/cases/counter_cache_test.rb | 16 +- .../test/cases/custom_locking_test.rb | 2 +- activerecord/test/cases/defaults_test.rb | 14 +- activerecord/test/cases/dirty_test.rb | 42 +-- activerecord/test/cases/dup_test.rb | 4 +- activerecord/test/cases/explain_test.rb | 6 +- activerecord/test/cases/finder_test.rb | 37 +- activerecord/test/cases/fixtures_test.rb | 40 +-- .../test/cases/habtm_destroy_order_test.rb | 16 +- activerecord/test/cases/i18n_test.rb | 14 +- activerecord/test/cases/inheritance_test.rb | 54 +-- .../test/cases/json_serialization_test.rb | 52 +-- activerecord/test/cases/locking_test.rb | 24 +- .../cases/migration/change_schema_test.rb | 40 +-- .../test/cases/migration/change_table_test.rb | 20 +- .../cases/migration/column_attributes_test.rb | 28 +- .../migration/column_positioning_test.rb | 10 +- .../test/cases/migration/columns_test.rb | 38 +- .../cases/migration/compatibility_test.rb | 6 +- .../test/cases/migration/index_test.rb | 70 ++-- .../cases/migration/references_index_test.rb | 32 +- activerecord/test/cases/migration_test.rb | 70 ++-- activerecord/test/cases/migrator_test.rb | 6 +- activerecord/test/cases/modules_test.rb | 8 +- .../test/cases/nested_attributes_test.rb | 262 +++++++------- .../nested_attributes_with_callbacks_test.rb | 12 +- activerecord/test/cases/persistence_test.rb | 18 +- .../test/cases/pooled_connections_test.rb | 8 +- activerecord/test/cases/primary_keys_test.rb | 4 +- activerecord/test/cases/reflection_test.rb | 72 ++-- .../test/cases/relation/merging_test.rb | 6 +- activerecord/test/cases/relation/or_test.rb | 6 +- .../test/cases/relation/where_test.rb | 22 +- activerecord/test/cases/relation_test.rb | 10 +- activerecord/test/cases/relations_test.rb | 178 +++++----- activerecord/test/cases/sanitize_test.rb | 16 +- activerecord/test/cases/schema_dumper_test.rb | 4 +- .../cases/scoping/default_scoping_test.rb | 34 +- .../test/cases/scoping/named_scoping_test.rb | 24 +- .../cases/scoping/relation_scoping_test.rb | 32 +- activerecord/test/cases/serialization_test.rb | 20 +- .../test/cases/serialized_attribute_test.rb | 18 +- .../test/cases/statement_cache_test.rb | 4 +- activerecord/test/cases/store_test.rb | 2 +- .../test/cases/tasks/database_tasks_test.rb | 4 +- .../test/cases/tasks/mysql_rake_test.rb | 10 +- .../test/cases/tasks/postgresql_rake_test.rb | 12 +- .../test/cases/tasks/sqlite_rake_test.rb | 2 +- activerecord/test/cases/timestamp_test.rb | 12 +- .../test/cases/transaction_callbacks_test.rb | 12 +- activerecord/test/cases/transactions_test.rb | 38 +- activerecord/test/cases/type/integer_test.rb | 2 +- .../association_validation_test.rb | 12 +- .../i18n_generate_message_validation_test.rb | 18 +- .../cases/validations/i18n_validation_test.rb | 24 +- .../validations/uniqueness_validation_test.rb | 46 +-- activerecord/test/cases/validations_test.rb | 8 +- .../test/cases/yaml_serialization_test.rb | 6 +- .../decimal/1_give_me_big_numbers.rb | 8 +- .../magic/1_currencies_have_symbols.rb | 4 +- .../missing/4_innocent_jointable.rb | 2 +- .../migrations/valid/3_innocent_jointable.rb | 2 +- .../sub1/3_innocent_jointable.rb | 2 +- ...alid_with_timestamps_innocent_jointable.rb | 2 +- activerecord/test/models/admin/user.rb | 8 +- activerecord/test/models/aircraft.rb | 2 +- activerecord/test/models/author.rb | 181 +++++----- activerecord/test/models/bird.rb | 2 +- activerecord/test/models/book.rb | 2 +- activerecord/test/models/bulb.rb | 4 +- activerecord/test/models/car.rb | 8 +- activerecord/test/models/categorization.rb | 10 +- activerecord/test/models/category.rb | 28 +- activerecord/test/models/citation.rb | 2 +- activerecord/test/models/club.rb | 6 +- activerecord/test/models/comment.rb | 10 +- activerecord/test/models/company.rb | 114 +++--- activerecord/test/models/company_in_module.rb | 28 +- activerecord/test/models/computer.rb | 2 +- activerecord/test/models/contact.rb | 4 +- activerecord/test/models/contract.rb | 2 +- activerecord/test/models/customer.rb | 14 +- activerecord/test/models/developer.rb | 86 ++--- activerecord/test/models/edge.rb | 4 +- activerecord/test/models/engine.rb | 2 +- activerecord/test/models/essay.rb | 6 +- activerecord/test/models/face.rb | 10 +- activerecord/test/models/hotel.rb | 2 +- activerecord/test/models/interest.rb | 6 +- activerecord/test/models/invoice.rb | 2 +- activerecord/test/models/item.rb | 2 +- activerecord/test/models/job.rb | 6 +- activerecord/test/models/line_item.rb | 2 +- activerecord/test/models/man.rb | 14 +- activerecord/test/models/matey.rb | 2 +- activerecord/test/models/member.rb | 38 +- activerecord/test/models/minivan.rb | 2 +- activerecord/test/models/order.rb | 4 +- activerecord/test/models/organization.rb | 12 +- activerecord/test/models/parrot.rb | 6 +- activerecord/test/models/person.rb | 68 ++-- .../test/models/personal_legacy_thing.rb | 2 +- activerecord/test/models/pet.rb | 2 +- activerecord/test/models/pirate.rb | 74 ++-- activerecord/test/models/post.rb | 132 +++---- activerecord/test/models/price_estimate.rb | 2 +- activerecord/test/models/project.rb | 22 +- activerecord/test/models/rating.rb | 2 +- activerecord/test/models/reader.rb | 10 +- activerecord/test/models/reference.rb | 4 +- activerecord/test/models/reply.rb | 22 +- activerecord/test/models/ship.rb | 12 +- activerecord/test/models/ship_part.rb | 4 +- activerecord/test/models/shop.rb | 4 +- activerecord/test/models/sponsor.rb | 10 +- activerecord/test/models/subscriber.rb | 2 +- activerecord/test/models/subscription.rb | 2 +- activerecord/test/models/tag.rb | 4 +- activerecord/test/models/tagging.rb | 12 +- activerecord/test/models/topic.rb | 16 +- activerecord/test/models/treasure.rb | 4 +- activerecord/test/models/vegetables.rb | 2 +- activerecord/test/models/vertex.rb | 8 +- activerecord/test/models/wheel.rb | 2 +- activerecord/test/models/without_table.rb | 2 +- activerecord/test/models/zine.rb | 2 +- 202 files changed, 2398 insertions(+), 2402 deletions(-) diff --git a/activerecord/Rakefile b/activerecord/Rakefile index 5bf1c843af..543ab2eaba 100644 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -18,7 +18,7 @@ def run_without_aborting(*tasks) end desc "Run mysql2, sqlite, and postgresql tests by default" -task :default => :test +task default: :test task :package @@ -41,8 +41,8 @@ end desc "Build MySQL and PostgreSQL test databases" namespace :db do - task :create => ["db:mysql:build", "db:postgresql:build"] - task :drop => ["db:mysql:drop", "db:postgresql:drop"] + task create: ["db:mysql:build", "db:postgresql:build"] + task drop: ["db:mysql:drop", "db:postgresql:drop"] end %w( mysql2 postgresql sqlite3 sqlite3_mem db2 oracle jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter| @@ -73,8 +73,8 @@ end end namespace adapter do - task :test => "test_#{adapter}" - task :isolated_test => "isolated_test_#{adapter}" + task test: "test_#{adapter}" + task isolated_test: "isolated_test_#{adapter}" # Set the connection environment for the adapter task(:env) { ENV["ARCONN"] = adapter } @@ -102,7 +102,7 @@ namespace :db do end desc "Rebuild the MySQL test databases" - task :rebuild => [:drop, :build] + task rebuild: [:drop, :build] end namespace :postgresql do @@ -126,17 +126,17 @@ namespace :db do end desc "Rebuild the PostgreSQL test databases" - task :rebuild => [:drop, :build] + task rebuild: [:drop, :build] end end -task :build_mysql_databases => "db:mysql:build" -task :drop_mysql_databases => "db:mysql:drop" -task :rebuild_mysql_databases => "db:mysql:rebuild" +task build_mysql_databases: "db:mysql:build" +task drop_mysql_databases: "db:mysql:drop" +task rebuild_mysql_databases: "db:mysql:rebuild" -task :build_postgresql_databases => "db:postgresql:build" -task :drop_postgresql_databases => "db:postgresql:drop" -task :rebuild_postgresql_databases => "db:postgresql:rebuild" +task build_postgresql_databases: "db:postgresql:build" +task drop_postgresql_databases: "db:postgresql:drop" +task rebuild_postgresql_databases: "db:postgresql:rebuild" task :lines do load File.expand_path("..", File.dirname(__FILE__)) + "/tools/line_statistics" diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 61a26cf914..d1d71391e6 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -90,7 +90,7 @@ def initialize(reflection = nil) through_reflection = reflection.through_reflection source_reflection_names = reflection.source_reflection_names source_associations = reflection.through_reflection.klass._reflections.keys - super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => '. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?") + super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => '. Is it one of #{source_associations.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)}?") else super("Could not find the source association(s).") end diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index 74803d0ad5..8328286805 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -19,7 +19,7 @@ class Association #:nodoc: attr_reader :owner, :target, :reflection attr_accessor :inversed - delegate :options, :to => :reflection + delegate :options, to: :reflection def initialize(owner, reflection) reflection.check_validity! diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 4daafedcfb..6720578b2c 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -41,9 +41,9 @@ def insert_record(record, validate = true, raise = false) set_inverse_instance(record) if raise - record.save!(:validate => validate) + record.save!(validate: validate) else - record.save(:validate => validate) + record.save(validate: validate) end end diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 67510f18d4..d258eac0ed 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -39,9 +39,9 @@ def insert_record(record, validate = true, raise = false) ensure_not_nested if raise - record.save!(:validate => validate) + record.save!(validate: validate) else - return unless record.save(:validate => validate) + return unless record.save(validate: validate) end save_through_record(record) diff --git a/activerecord/lib/active_record/associations/join_dependency/join_part.rb b/activerecord/lib/active_record/associations/join_dependency/join_part.rb index 9c6573f913..551087f822 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_part.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_part.rb @@ -15,7 +15,7 @@ class JoinPart # :nodoc: # association. attr_reader :base_klass, :children - delegate :table_name, :column_names, :primary_key, :to => :base_klass + delegate :table_name, :column_names, :primary_key, to: :base_klass def initialize(base_klass, children) @base_klass = base_klass diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb index d0ec3e8015..cb10031015 100644 --- a/activerecord/lib/active_record/associations/through_association.rb +++ b/activerecord/lib/active_record/associations/through_association.rb @@ -3,7 +3,7 @@ module ActiveRecord module Associations module ThroughAssociation #:nodoc: - delegate :source_reflection, :through_reflection, :to => :reflection + delegate :source_reflection, :through_reflection, to: :reflection protected diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 06c7482bf9..6e6620aad5 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -400,7 +400,7 @@ def save_collection_association(reflection) association.insert_record(record) unless reflection.nested? end elsif autosave - saved = record.save(:validate => false) + saved = record.save(validate: false) end raise ActiveRecord::Rollback unless saved @@ -437,7 +437,7 @@ def save_has_one_association(reflection) record[reflection.foreign_key] = key end - saved = record.save(:validate => !autosave) + saved = record.save(validate: !autosave) raise ActiveRecord::Rollback if !saved && autosave saved end @@ -465,7 +465,7 @@ def save_belongs_to_association(reflection) self[reflection.foreign_key] = nil record.destroy elsif autosave != false - saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?) + saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?) if association.updated? association_id = record.send(reflection.options[:primary_key] || :id) diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index 95de6937af..c616733aa4 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -272,7 +272,7 @@ module ClassMethods # :nodoc: included do include ActiveModel::Validations::Callbacks - define_model_callbacks :initialize, :find, :touch, :only => :after + define_model_callbacks :initialize, :find, :touch, only: :after define_model_callbacks :save, :create, :update, :destroy end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 198a169df2..db798bc303 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -339,7 +339,7 @@ def initialize(spec) # that case +conn.owner+ attr should be consulted. # Access and modification of +@thread_cached_conns+ does not require # synchronization. - @thread_cached_conns = Concurrent::Map.new(:initial_capacity => @size) + @thread_cached_conns = Concurrent::Map.new(initial_capacity: @size) @connections = [] @automatic_reconnect = true @@ -833,8 +833,8 @@ def checkout_and_verify(c) class ConnectionHandler def initialize # These caches are keyed by spec.name (ConnectionSpecification#name). - @owner_to_pool = Concurrent::Map.new(:initial_capacity => 2) do |h,k| - h[k] = Concurrent::Map.new(:initial_capacity => 2) + @owner_to_pool = Concurrent::Map.new(initial_capacity: 2) do |h,k| + h[k] = Concurrent::Map.new(initial_capacity: 2) end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb index 0bdfd4f900..47f24df22f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb @@ -77,7 +77,7 @@ def cache_sql(sql, binds) result = if @query_cache[sql].key?(binds) ActiveSupport::Notifications.instrument("sql.active_record", - :sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id) + sql: sql, binds: binds, name: "CACHE", connection_id: object_id) @query_cache[sql][binds] else @query_cache[sql][binds] = yield diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index 77e97a6d1b..f2134fe035 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -762,7 +762,7 @@ def index_name(table_name, options) #:nodoc: raise ArgumentError, "You must specify the index name" end else - index_name(table_name, :column => options) + index_name(table_name, column: options) end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb index ee86e6e128..8ac8996d21 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -480,7 +480,7 @@ def rename_index(table_name, old_name, new_name) def change_column_default(table_name, column_name, default_or_changes) #:nodoc: default = extract_new_default_value(default_or_changes) column = column_for(table_name, column_name) - change_column table_name, column_name, column.sql_type, :default => default + change_column table_name, column_name, column.sql_type, default: default end def change_column_null(table_name, column_name, null, default = nil) #:nodoc: @@ -490,7 +490,7 @@ def change_column_null(table_name, column_name, null, default = nil) #:nodoc: execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") end - change_column table_name, column_name, column.sql_type, :null => null + change_column table_name, column_name, column.sql_type, null: null end def change_column(table_name, column_name, type, options = {}) #:nodoc: diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index cace451df2..154f0b2d3a 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -65,7 +65,7 @@ def supports_savepoints? def each_hash(result) # :nodoc: if block_given? - result.each(:as => :hash, :symbolize_keys => true) do |row| + result.each(as: :hash, symbolize_keys: true) do |row| yield row end else @@ -119,7 +119,7 @@ def connect end def configure_connection - @connection.query_options.merge!(:as => :array) + @connection.query_options.merge!(as: :array) super end diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb index eee142378c..d1708a6af8 100644 --- a/activerecord/lib/active_record/connection_adapters/schema_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb @@ -33,7 +33,7 @@ def data_source_exists?(name) @data_sources[name] = connection.data_source_exists?(name) end alias table_exists? data_source_exists? - deprecate :table_exists? => "use #data_source_exists? instead" + deprecate table_exists?: "use #data_source_exists? instead" # Add internal cache for table with +table_name+. @@ -49,7 +49,7 @@ def data_sources(name) @data_sources[name] end alias tables data_sources - deprecate :tables => "use #data_sources instead" + deprecate tables: "use #data_sources instead" # Get the columns for a table def columns(table_name) @@ -85,7 +85,7 @@ def clear_data_source_cache!(name) @data_sources.delete name end alias clear_table_cache! clear_data_source_cache! - deprecate :clear_table_cache! => "use #clear_data_source_cache! instead" + deprecate clear_table_cache!: "use #clear_data_source_cache! instead" def marshal_dump # if we get current version during initialization, it happens stack over flow. diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 47de43dfc3..4558e1f80f 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -26,7 +26,7 @@ def sqlite3_connection(config) db = SQLite3::Database.new( config[:database].to_s, - :results_as_hash => true + results_as_hash: true ) db.busy_timeout(ConnectionAdapters::SQLite3Adapter.type_cast_config_to_integer(config[:timeout])) if config[:timeout] @@ -205,7 +205,7 @@ def exec_query(sql, name = nil, binds = [], prepare: false) end else cache = @statements[sql] ||= { - :stmt => @connection.prepare(sql) + stmt: @connection.prepare(sql) } stmt = cache[:stmt] cols = cache[:cols] ||= stmt.columns @@ -436,7 +436,7 @@ def alter_table(table_name, options = {}) #:nodoc: transaction do move_table(table_name, altered_table_name, - options.merge(:temporary => true)) + options.merge(temporary: true)) move_table(altered_table_name, table_name, &caller) end end @@ -460,9 +460,9 @@ def copy_table(from, to, options = {}) #:nodoc: next if column_name == from_primary_key @definition.column(column_name, column.type, - :limit => column.limit, :default => column.default, - :precision => column.precision, :scale => column.scale, - :null => column.null, collation: column.collation) + limit: column.limit, default: column.default, + precision: column.precision, scale: column.scale, + null: column.null, collation: column.collation) end yield @definition if block_given? end diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb index 48e1dc1b0c..b4cd6cdd38 100644 --- a/activerecord/lib/active_record/connection_handling.rb +++ b/activerecord/lib/active_record/connection_handling.rb @@ -138,6 +138,6 @@ def clear_cache! # :nodoc: end delegate :clear_active_connections!, :clear_reloadable_connections!, - :clear_all_connections!, :to => :connection_handler + :clear_all_connections!, to: :connection_handler end end diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 601366bc38..babff9c284 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -535,7 +535,7 @@ def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {} update_all_loaded_fixtures fixtures_map - connection.transaction(:requires_new => true) do + connection.transaction(requires_new: true) do deleted_tables = Set.new fixture_sets.each do |fs| conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection @@ -859,7 +859,7 @@ def after_teardown # :nodoc: end included do - class_attribute :fixture_path, :instance_writer => false + class_attribute :fixture_path, instance_writer: false class_attribute :fixture_table_names class_attribute :fixture_class_names class_attribute :use_transactional_tests diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb index c16909bbb5..e4c7a55541 100644 --- a/activerecord/lib/active_record/integration.rb +++ b/activerecord/lib/active_record/integration.rb @@ -11,7 +11,7 @@ module Integration # Accepts any of the symbols in Time::DATE_FORMATS. # # This is +:usec+, by default. - class_attribute :cache_timestamp_format, :instance_writer => false + class_attribute :cache_timestamp_format, instance_writer: false self.cache_timestamp_format = :usec end diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb index 8ecdf76b72..e73cb4fc12 100644 --- a/activerecord/lib/active_record/locking/pessimistic.rb +++ b/activerecord/lib/active_record/locking/pessimistic.rb @@ -59,7 +59,7 @@ module Pessimistic # or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns # the locked record. def lock!(lock = true) - reload(:lock => lock) if persisted? + reload(lock: lock) if persisted? self end diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 400501fb3d..0066d30ca6 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -1242,7 +1242,7 @@ def validate(migrations) def record_version_state_after_migrating(version) if down? migrated.delete(version) - ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all + ActiveRecord::SchemaMigration.where(version: version.to_s).delete_all else migrated << version ActiveRecord::SchemaMigration.create!(version: version.to_s) diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index 819e181f61..c9fe1167e8 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -317,7 +317,7 @@ module ClassMethods # # creates avatar_attributes= and posts_attributes= # accepts_nested_attributes_for :avatar, :posts, allow_destroy: true def accepts_nested_attributes_for(*attr_names) - options = { :allow_destroy => false, :update_only => false } + options = { allow_destroy: false, update_only: false } options.update(attr_names.extract_options!) options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only) options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index 19bd1b8e65..35c19b27bb 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -13,8 +13,8 @@ module ActiveRecord class Railtie < Rails::Railtie # :nodoc: config.active_record = ActiveSupport::OrderedOptions.new - config.app_generators.orm :active_record, :migration => true, - :timestamps => true + config.app_generators.orm :active_record, migration: true, + timestamps: true config.action_dispatch.rescue_responses.merge!( "ActiveRecord::RecordNotFound" => :not_found, diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 9481e5f7aa..3532465fee 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -7,7 +7,7 @@ db_namespace = namespace :db do ActiveRecord::InternalMetadata[:environment] = ActiveRecord::Migrator.current_environment end - task :check_protected_environments => [:environment, :load_config] do + task check_protected_environments: [:environment, :load_config] do ActiveRecord::Tasks::DatabaseTasks.check_protected_environments! end @@ -17,24 +17,24 @@ db_namespace = namespace :db do end namespace :create do - task :all => :load_config do + task all: :load_config do ActiveRecord::Tasks::DatabaseTasks.create_all end end desc "Creates 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). Without RAILS_ENV or when RAILS_ENV is development, it defaults to creating the development and test databases." - task :create => [:load_config] do + task create: [:load_config] do ActiveRecord::Tasks::DatabaseTasks.create_current end namespace :drop do - task :all => [:load_config, :check_protected_environments] do + task all: [:load_config, :check_protected_environments] do ActiveRecord::Tasks::DatabaseTasks.drop_all end end desc "Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to dropping the development and test databases." - task :drop => [:load_config, :check_protected_environments] do + task drop: [:load_config, :check_protected_environments] do db_namespace["drop:_unsafe"].invoke end @@ -43,18 +43,18 @@ db_namespace = namespace :db do end namespace :purge do - task :all => [:load_config, :check_protected_environments] do + task all: [:load_config, :check_protected_environments] do ActiveRecord::Tasks::DatabaseTasks.purge_all end end # desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:purge:all to purge all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases." - task :purge => [:load_config, :check_protected_environments] do + task purge: [:load_config, :check_protected_environments] do ActiveRecord::Tasks::DatabaseTasks.purge_current end desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)." - task :migrate => [:environment, :load_config] do + task migrate: [:environment, :load_config] do ActiveRecord::Tasks::DatabaseTasks.migrate db_namespace["_dump"].invoke end @@ -76,7 +76,7 @@ db_namespace = namespace :db do namespace :migrate do # desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).' - task :redo => [:environment, :load_config] do + task redo: [:environment, :load_config] do if ENV["VERSION"] db_namespace["migrate:down"].invoke db_namespace["migrate:up"].invoke @@ -87,10 +87,10 @@ db_namespace = namespace :db do end # desc 'Resets your database using your migrations for the current environment' - task :reset => ["db:drop", "db:create", "db:migrate"] + task reset: ["db:drop", "db:create", "db:migrate"] # desc 'Runs the "up" for a given migration VERSION.' - task :up => [:environment, :load_config] do + task up: [:environment, :load_config] do version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil raise "VERSION is required" unless version ActiveRecord::Migrator.run(:up, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version) @@ -98,7 +98,7 @@ db_namespace = namespace :db do end # desc 'Runs the "down" for a given migration VERSION.' - task :down => [:environment, :load_config] do + task down: [:environment, :load_config] do version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil raise "VERSION is required - To go down one migration, run db:rollback" unless version ActiveRecord::Migrator.run(:down, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version) @@ -106,7 +106,7 @@ db_namespace = namespace :db do end desc "Display status of migrations" - task :status => [:environment, :load_config] do + task status: [:environment, :load_config] do unless ActiveRecord::SchemaMigration.table_exists? abort "Schema migrations table does not exist yet." end @@ -139,29 +139,29 @@ db_namespace = namespace :db do end desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)." - task :rollback => [:environment, :load_config] do + task rollback: [:environment, :load_config] do step = ENV["STEP"] ? ENV["STEP"].to_i : 1 ActiveRecord::Migrator.rollback(ActiveRecord::Tasks::DatabaseTasks.migrations_paths, step) db_namespace["_dump"].invoke end # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).' - task :forward => [:environment, :load_config] do + task forward: [:environment, :load_config] do step = ENV["STEP"] ? ENV["STEP"].to_i : 1 ActiveRecord::Migrator.forward(ActiveRecord::Tasks::DatabaseTasks.migrations_paths, step) db_namespace["_dump"].invoke end # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.' - task :reset => [ "db:drop", "db:setup" ] + task reset: [ "db:drop", "db:setup" ] # desc "Retrieves the charset for the current environment's database" - task :charset => [:environment, :load_config] do + task charset: [:environment, :load_config] do puts ActiveRecord::Tasks::DatabaseTasks.charset_current end # desc "Retrieves the collation for the current environment's database" - task :collation => [:environment, :load_config] do + task collation: [:environment, :load_config] do begin puts ActiveRecord::Tasks::DatabaseTasks.collation_current rescue NoMethodError @@ -170,12 +170,12 @@ db_namespace = namespace :db do end desc "Retrieves the current schema version number" - task :version => [:environment, :load_config] do + task version: [:environment, :load_config] do puts "Current version: #{ActiveRecord::Migrator.current_version}" end # desc "Raises an error if there are pending migrations" - task :abort_if_pending_migrations => [:environment, :load_config] do + task abort_if_pending_migrations: [:environment, :load_config] do pending_migrations = ActiveRecord::Migrator.open(ActiveRecord::Tasks::DatabaseTasks.migrations_paths).pending_migrations if pending_migrations.any? @@ -188,7 +188,7 @@ db_namespace = namespace :db do end desc "Creates the database, loads the schema, and initializes with the seed data (use db:reset to also drop the database first)" - task :setup => ["db:schema:load_if_ruby", "db:structure:load_if_sql", :seed] + task setup: ["db:schema:load_if_ruby", "db:structure:load_if_sql", :seed] desc "Loads the seed data from db/seeds.rb" task :seed do @@ -198,7 +198,7 @@ db_namespace = namespace :db do namespace :fixtures do desc "Loads fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures." - task :load => [:environment, :load_config] do + task load: [:environment, :load_config] do require "active_record/fixtures" base_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path @@ -220,7 +220,7 @@ db_namespace = namespace :db do end # desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures." - task :identify => [:environment, :load_config] do + task identify: [:environment, :load_config] do require "active_record/fixtures" label, id = ENV["LABEL"], ENV["ID"] @@ -246,7 +246,7 @@ db_namespace = namespace :db do namespace :schema do desc "Creates a db/schema.rb file that is portable against any DB supported by Active Record" - task :dump => [:environment, :load_config] do + task dump: [:environment, :load_config] do require "active_record/schema_dumper" filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema.rb") File.open(filename, "w:utf-8") do |file| @@ -256,17 +256,17 @@ db_namespace = namespace :db do end desc "Loads a schema.rb file into the database" - task :load => [:environment, :load_config, :check_protected_environments] do + task load: [:environment, :load_config, :check_protected_environments] do ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV["SCHEMA"]) end - task :load_if_ruby => ["db:create", :environment] do + task load_if_ruby: ["db:create", :environment] do db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby end namespace :cache do desc "Creates a db/schema_cache.dump file." - task :dump => [:environment, :load_config] do + task dump: [:environment, :load_config] do con = ActiveRecord::Base.connection filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump") @@ -276,7 +276,7 @@ db_namespace = namespace :db do end desc "Clears a db/schema_cache.dump file." - task :clear => [:environment, :load_config] do + task clear: [:environment, :load_config] do filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump") rm_f filename, verbose: false end @@ -286,7 +286,7 @@ db_namespace = namespace :db do namespace :structure do desc "Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql" - task :dump => [:environment, :load_config] do + task dump: [:environment, :load_config] do filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql") current_config = ActiveRecord::Tasks::DatabaseTasks.current_config ActiveRecord::Tasks::DatabaseTasks.structure_dump(current_config, filename) @@ -302,11 +302,11 @@ db_namespace = namespace :db do end desc "Recreates the databases from the structure.sql file" - task :load => [:environment, :load_config, :check_protected_environments] do + task load: [:environment, :load_config, :check_protected_environments] do ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:sql, ENV["SCHEMA"]) end - task :load_if_sql => ["db:create", :environment] do + task load_if_sql: ["db:create", :environment] do db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql end end @@ -321,7 +321,7 @@ db_namespace = namespace :db do end # desc "Recreate the test database from the current schema" - task :load => %w(db:test:purge) do + task load: %w(db:test:purge) do case ActiveRecord::Base.schema_format when :ruby db_namespace["test:load_schema"].invoke @@ -331,7 +331,7 @@ db_namespace = namespace :db do end # desc "Recreate the test database from an existent schema.rb file" - task :load_schema => %w(db:test:purge) do + task load_schema: %w(db:test:purge) do begin should_reconnect = ActiveRecord::Base.connection_pool.active_connection? ActiveRecord::Schema.verbose = false @@ -344,12 +344,12 @@ db_namespace = namespace :db do end # desc "Recreate the test database from an existent structure.sql file" - task :load_structure => %w(db:test:purge) do + task load_structure: %w(db:test:purge) do ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations["test"], :sql, ENV["SCHEMA"] end # desc "Recreate the test database from a fresh schema" - task :clone => %w(db:test:deprecated environment) do + task clone: %w(db:test:deprecated environment) do case ActiveRecord::Base.schema_format when :ruby db_namespace["test:clone_schema"].invoke @@ -359,18 +359,18 @@ db_namespace = namespace :db do end # desc "Recreate the test database from a fresh schema.rb file" - task :clone_schema => %w(db:test:deprecated db:schema:dump db:test:load_schema) + task clone_schema: %w(db:test:deprecated db:schema:dump db:test:load_schema) # desc "Recreate the test database from a fresh structure.sql file" - task :clone_structure => %w(db:test:deprecated db:structure:dump db:test:load_structure) + task clone_structure: %w(db:test:deprecated db:structure:dump db:test:load_structure) # desc "Empty the test database" - task :purge => %w(environment load_config check_protected_environments) do + task purge: %w(environment load_config check_protected_environments) do ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations["test"] end # desc 'Load the test schema' - task :prepare => %w(environment load_config) do + task prepare: %w(environment load_config) do unless ActiveRecord::Base.configurations.blank? db_namespace["test:load"].invoke end @@ -381,7 +381,7 @@ end namespace :railties do namespace :install do # desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2" - task :migrations => :'db:load_config' do + task migrations: :'db:load_config' do to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map(&:strip) railties = {} Rails.application.migration_railties.each do |railtie| @@ -401,7 +401,7 @@ namespace :railties do end ActiveRecord::Migration.copy(ActiveRecord::Tasks::DatabaseTasks.migrations_paths.first, railties, - :on_skip => on_skip, :on_copy => on_copy) + on_skip: on_skip, on_copy: on_copy) end end end diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index bd352d664d..1a092a8c18 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -700,7 +700,7 @@ def collection? class ThroughReflection < AbstractReflection #:nodoc: attr_reader :delegate_reflection delegate :foreign_key, :foreign_type, :association_foreign_key, - :active_record_primary_key, :type, :to => :source_reflection + :active_record_primary_key, :type, to: :source_reflection def initialize(delegate_reflection) @delegate_reflection = delegate_reflection diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb index 2cb1df05df..6b28d85a49 100644 --- a/activerecord/lib/active_record/relation/delegation.rb +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -41,7 +41,7 @@ def inherited(child_class) :shuffle, :split, to: :records delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, - :connection, :columns_hash, :to => :klass + :connection, :columns_hash, to: :klass module ClassSpecificRelation # :nodoc: extend ActiveSupport::Concern @@ -88,7 +88,7 @@ def method_missing(method, *args, &block) self.class.delegate_to_scoped_klass(method) scoping { @klass.public_send(method, *args, &block) } elsif arel.respond_to?(method) - self.class.delegate method, :to => :arel + self.class.delegate method, to: :arel arel.public_send(method, *args, &block) else super diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index 52b4fcb742..269a1488f5 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -96,7 +96,7 @@ def seed_loader end def current_config(options = {}) - options.reverse_merge! :env => env + options.reverse_merge! env: env if options.has_key?(:config) @current_config = options[:config] else diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb index 253961071e..66ef62a76c 100644 --- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb +++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb @@ -4,7 +4,7 @@ module ActiveRecord module Generators # :nodoc: class MigrationGenerator < Base # :nodoc: - argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" + argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" class_option :primary_key_type, type: :string, desc: "The type for primary key" diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb index 0d89b96ffd..f1ddc61688 100644 --- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -3,7 +3,7 @@ module ActiveRecord module Generators # :nodoc: class ModelGenerator < Base # :nodoc: - argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" + argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" check_class_collision diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index a923358f63..b164c12c89 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -73,7 +73,7 @@ def test_indexes indexes = @connection.indexes("accounts") assert indexes.empty? - @connection.add_index :accounts, :firm_id, :name => idx_name + @connection.add_index :accounts, :firm_id, name: idx_name indexes = @connection.indexes("accounts") assert_equal "accounts", indexes.first.table assert_equal idx_name, indexes.first.name @@ -84,18 +84,18 @@ def test_indexes end ensure - @connection.remove_index(:accounts, :name => idx_name) rescue nil + @connection.remove_index(:accounts, name: idx_name) rescue nil end def test_remove_index_when_name_and_wrong_column_name_specified index_name = "accounts_idx" - @connection.add_index :accounts, :firm_id, :name => index_name + @connection.add_index :accounts, :firm_id, name: index_name assert_raises ArgumentError do - @connection.remove_index :accounts, :name => index_name, :column => :wrong_column_name + @connection.remove_index :accounts, name: index_name, column: :wrong_column_name end ensure - @connection.remove_index(:accounts, :name => index_name) + @connection.remove_index(:accounts, name: index_name) end def test_current_database @@ -163,13 +163,13 @@ class << @connection def test_reset_empty_table_with_custom_pk Movie.delete_all Movie.connection.reset_pk_sequence! "movies" - assert_equal 1, Movie.create(:name => "fight club").id + assert_equal 1, Movie.create(name: "fight club").id end def test_reset_table_with_non_integer_pk Subscriber.delete_all Subscriber.connection.reset_pk_sequence! "subscribers" - sub = Subscriber.new(:name => "robert drake") + sub = Subscriber.new(name: "robert drake") sub.id = "bob drake" assert_nothing_raised { sub.save! } end diff --git a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb index 429919a395..716b7b1164 100644 --- a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb @@ -21,42 +21,42 @@ def (ActiveRecord::Base.connection).data_source_exists?(*); true; end def (ActiveRecord::Base.connection).index_name_exists?(*); false; end expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`) " - assert_equal expected, add_index(:people, :last_name, :length => nil) + assert_equal expected, add_index(:people, :last_name, length: nil) expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`(10)) " - assert_equal expected, add_index(:people, :last_name, :length => 10) + assert_equal expected, add_index(:people, :last_name, length: 10) expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(15)) " - assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15) + assert_equal expected, add_index(:people, [:last_name, :first_name], length: 15) expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`) " - assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15}) + assert_equal expected, add_index(:people, [:last_name, :first_name], length: {last_name: 15}) expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(10)) " - assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15, :first_name => 10}) + assert_equal expected, add_index(:people, [:last_name, :first_name], length: {last_name: 15, first_name: 10}) %w(SPATIAL FULLTEXT UNIQUE).each do |type| expected = "CREATE #{type} INDEX `index_people_on_last_name` ON `people` (`last_name`) " - assert_equal expected, add_index(:people, :last_name, :type => type) + assert_equal expected, add_index(:people, :last_name, type: type) end %w(btree hash).each do |using| expected = "CREATE INDEX `index_people_on_last_name` USING #{using} ON `people` (`last_name`) " - assert_equal expected, add_index(:people, :last_name, :using => using) + assert_equal expected, add_index(:people, :last_name, using: using) end expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) " - assert_equal expected, add_index(:people, :last_name, :length => 10, :using => :btree) + assert_equal expected, add_index(:people, :last_name, length: 10, using: :btree) expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) ALGORITHM = COPY" - assert_equal expected, add_index(:people, :last_name, :length => 10, using: :btree, algorithm: :copy) + assert_equal expected, add_index(:people, :last_name, length: 10, using: :btree, algorithm: :copy) assert_raise ArgumentError do add_index(:people, :last_name, algorithm: :coyp) end expected = "CREATE INDEX `index_people_on_last_name_and_first_name` USING btree ON `people` (`last_name`(15), `first_name`(15)) " - assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15, :using => :btree) + assert_equal expected, add_index(:people, [:last_name, :first_name], length: 15, using: :btree) end def test_index_in_create @@ -102,13 +102,13 @@ def test_drop_table def test_create_mysql_database_with_encoding assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt) - assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => "latin1"}) - assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {:charset => :big5, :collation => :big5_chinese_ci}) + assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {charset: "latin1"}) + assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {charset: :big5, collation: :big5_chinese_ci}) end def test_recreate_mysql_database_with_encoding - create_database(:luca, {:charset => "latin1"}) - assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {:charset => "latin1"}) + create_database(:luca, {charset: "latin1"}) + assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {charset: "latin1"}) end def test_add_column @@ -116,7 +116,7 @@ def test_add_column end def test_add_column_with_limit - assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, :limit => 32) + assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, limit: 32) end def test_drop_table_with_specific_database diff --git a/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb b/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb index f75cea70a7..8f7c803a21 100644 --- a/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb +++ b/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb @@ -20,7 +20,7 @@ def test_update_question_marks def test_create_question_marks str = "foo?bar" - x = Topic.create!(:title => str, :content => str) + x = Topic.create!(title: str, content: str) x.reload assert_equal str, x.title assert_equal str, x.content @@ -39,7 +39,7 @@ def test_update_null_bytes def test_create_null_bytes str = "foo\0bar" - x = Topic.create!(:title => str, :content => str) + x = Topic.create!(title: str, content: str) x.reload assert_equal str, x.title assert_equal str, x.content diff --git a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb index 5f677626b0..4d81877a9a 100644 --- a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb +++ b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb @@ -17,36 +17,36 @@ def test_case_sensitive end def test_case_insensitive_comparison_for_ci_column - CollationTest.validates_uniqueness_of(:string_ci_column, :case_sensitive => false) - CollationTest.create!(:string_ci_column => "A") - invalid = CollationTest.new(:string_ci_column => "a") + CollationTest.validates_uniqueness_of(:string_ci_column, case_sensitive: false) + CollationTest.create!(string_ci_column: "A") + invalid = CollationTest.new(string_ci_column: "a") queries = assert_sql { invalid.save } ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) } assert_no_match(/lower/i, ci_uniqueness_query) end def test_case_insensitive_comparison_for_cs_column - CollationTest.validates_uniqueness_of(:string_cs_column, :case_sensitive => false) - CollationTest.create!(:string_cs_column => "A") - invalid = CollationTest.new(:string_cs_column => "a") + CollationTest.validates_uniqueness_of(:string_cs_column, case_sensitive: false) + CollationTest.create!(string_cs_column: "A") + invalid = CollationTest.new(string_cs_column: "a") queries = assert_sql { invalid.save } cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/)} assert_match(/lower/i, cs_uniqueness_query) end def test_case_sensitive_comparison_for_ci_column - CollationTest.validates_uniqueness_of(:string_ci_column, :case_sensitive => true) - CollationTest.create!(:string_ci_column => "A") - invalid = CollationTest.new(:string_ci_column => "A") + CollationTest.validates_uniqueness_of(:string_ci_column, case_sensitive: true) + CollationTest.create!(string_ci_column: "A") + invalid = CollationTest.new(string_ci_column: "A") queries = assert_sql { invalid.save } ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) } assert_match(/binary/i, ci_uniqueness_query) end def test_case_sensitive_comparison_for_cs_column - CollationTest.validates_uniqueness_of(:string_cs_column, :case_sensitive => true) - CollationTest.create!(:string_cs_column => "A") - invalid = CollationTest.new(:string_cs_column => "A") + CollationTest.validates_uniqueness_of(:string_cs_column, case_sensitive: true) + CollationTest.create!(string_cs_column: "A") + invalid = CollationTest.new(string_cs_column: "A") queries = assert_sql { invalid.save } cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) } assert_no_match(/binary/i, cs_uniqueness_query) diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 3fb2b15783..b6ed20abaa 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -114,7 +114,7 @@ def test_passing_flags_by_array_to_adapter def test_mysql_set_session_variable run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => 3}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {default_week_format: 3}})) session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" assert_equal 3, session_mode.rows.first.first.to_i end @@ -122,7 +122,7 @@ def test_mysql_set_session_variable def test_mysql_set_session_variable_to_default run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => :default}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {default_week_format: :default}})) global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT" session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" assert_equal global_mode.rows, session_mode.rows diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb index 28df7fab98..8092cd1d4c 100644 --- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb @@ -21,7 +21,7 @@ class Values < ActiveRecord::Base class Distinct < ActiveRecord::Base Distinct.table_name = "distinct" has_and_belongs_to_many :selects - has_many :values, :through => :groups + has_many :values, through: :groups end def setup @@ -59,7 +59,7 @@ def test_rename_tables def test_change_columns assert_nothing_raised { @connection.change_column_default(:group, :order, "whatever") } #the quoting here will reveal any double quoting issues in change_column's interaction with the column method in the adapter - assert_nothing_raised { @connection.change_column("group", "order", :Int, :default => 0) } + assert_nothing_raised { @connection.change_column("group", "order", :Int, default: 0) } assert_nothing_raised { @connection.rename_column(:group, :order, :values) } end @@ -124,7 +124,7 @@ def test_calculations_work_with_reserved_words end def test_associations_work_with_reserved_words - assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a } + assert_nothing_raised { Select.all.merge!(includes: [:groups]).to_a } end #the following functions were added to DRY test cases diff --git a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb index 3d805bdbdc..a4a06a2da4 100644 --- a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb @@ -15,12 +15,12 @@ def execute(sql, name = nil) sql end def test_create_database_with_encoding assert_equal %(CREATE DATABASE "matt" ENCODING = 'utf8'), create_database(:matt) - assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1) + assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, encoding: :latin1) assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, "encoding" => :latin1) end def test_create_database_with_collation_and_ctype - assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF8' LC_CTYPE = 'ja_JP.UTF8'), create_database(:aimonetti, :encoding => :"UTF8", :collation => :"ja_JP.UTF8", :ctype => :"ja_JP.UTF8") + assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF8' LC_CTYPE = 'ja_JP.UTF8'), create_database(:aimonetti, encoding: :"UTF8", collation: :"ja_JP.UTF8", ctype: :"ja_JP.UTF8") end def test_add_index diff --git a/activerecord/test/cases/adapters/postgresql/bit_string_test.rb b/activerecord/test/cases/adapters/postgresql/bit_string_test.rb index 7f36a6b457..f646e59848 100644 --- a/activerecord/test/cases/adapters/postgresql/bit_string_test.rb +++ b/activerecord/test/cases/adapters/postgresql/bit_string_test.rb @@ -10,7 +10,7 @@ class PostgresqlBitString < ActiveRecord::Base; end def setup @connection = ActiveRecord::Base.connection - @connection.create_table("postgresql_bit_strings", :force => true) do |t| + @connection.create_table("postgresql_bit_strings", force: true) do |t| t.bit :a_bit, default: "00000011", limit: 8 t.bit_varying :a_bit_varying, default: "0011", limit: 4 t.bit :another_bit diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index 436ab3ffa1..adb5422a67 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -184,7 +184,7 @@ def test_reconnection_after_actual_disconnection_with_verify def test_set_session_variable_true run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => true}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: true}})) set_true = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" assert_equal set_true.rows, [["on"]] end @@ -192,7 +192,7 @@ def test_set_session_variable_true def test_set_session_variable_false run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => false}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: false}})) set_false = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" assert_equal set_false.rows, [["off"]] end @@ -201,14 +201,14 @@ def test_set_session_variable_false def test_set_session_variable_nil run_without_connection do |orig_connection| # This should be a no-op that does not raise an error - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => nil}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: nil}})) end end def test_set_session_variable_default run_without_connection do |orig_connection| # This should execute a query that does not raise an error - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => :default}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: :default}})) end end diff --git a/activerecord/test/cases/adapters/postgresql/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb index 1b7d0cf4f0..e35c5eb269 100644 --- a/activerecord/test/cases/adapters/postgresql/geometric_test.rb +++ b/activerecord/test/cases/adapters/postgresql/geometric_test.rb @@ -195,11 +195,11 @@ class PostgresqlGeometric < ActiveRecord::Base; end def test_geometric_types g = PostgresqlGeometric.new( - :a_line_segment => "(2.0, 3), (5.5, 7.0)", - :a_box => "2.0, 3, 5.5, 7.0", - :a_path => "[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]", - :a_polygon => "((2.0, 3), (5.5, 7.0), (8.5, 11.0))", - :a_circle => "<(5.3, 10.4), 2>" + a_line_segment: "(2.0, 3), (5.5, 7.0)", + a_box: "2.0, 3, 5.5, 7.0", + a_path: "[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]", + a_polygon: "((2.0, 3), (5.5, 7.0), (8.5, 11.0))", + a_circle: "<(5.3, 10.4), 2>" ) g.save! @@ -215,11 +215,11 @@ def test_geometric_types def test_alternative_format g = PostgresqlGeometric.new( - :a_line_segment => "((2.0, 3), (5.5, 7.0))", - :a_box => "(2.0, 3), (5.5, 7.0)", - :a_path => "((2.0, 3), (5.5, 7.0), (8.5, 11.0))", - :a_polygon => "2.0, 3, 5.5, 7.0, 8.5, 11.0", - :a_circle => "((5.3, 10.4), 2)" + a_line_segment: "((2.0, 3), (5.5, 7.0))", + a_box: "(2.0, 3), (5.5, 7.0)", + a_path: "((2.0, 3), (5.5, 7.0), (8.5, 11.0))", + a_polygon: "2.0, 3, 5.5, 7.0, 8.5, 11.0", + a_circle: "((5.3, 10.4), 2)" ) g.save! diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index b31aba39d9..04631cb5e5 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -22,7 +22,7 @@ def setup @connection.transaction do @connection.create_table("hstores") do |t| - t.hstore "tags", :default => "" + t.hstore "tags", default: "" t.hstore "payload", array: true t.hstore "settings" end @@ -338,12 +338,12 @@ def assert_array_cycle(array) def assert_cycle(hash) # test creation - x = Hstore.create!(:tags => hash) + x = Hstore.create!(tags: hash) x.reload assert_equal(hash, x.tags) # test updating - x = Hstore.create!(:tags => {}) + x = Hstore.create!(tags: {}) x.tags = hash x.save! x.reload diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index cd2b2d5bc9..79d99c8a58 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -253,7 +253,7 @@ def test_exec_typecasts_bind_vals def test_partial_index with_example_table do - @connection.add_index "ex", %w{ id number }, :name => "partial", :where => "number > 100" + @connection.add_index "ex", %w{ id number }, name: "partial", where: "number > 100" index = @connection.indexes("ex").find { |idx| idx.name == "partial" } assert_equal "(number > 100)", index.where end @@ -395,7 +395,7 @@ def with_example_table(definition = "id serial primary key, number integer, data end def connection_without_insert_returning - ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(:insert_returning => false)) + ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(insert_returning: false)) end end end diff --git a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb index 7b565b348e..72ae11966a 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb @@ -90,9 +90,9 @@ def test_sequence_schema_caching assert_nothing_raised do USERS.each do |u| set_session_auth u - st = SchemaThing.new :name => "TEST1" + st = SchemaThing.new name: "TEST1" st.save! - st = SchemaThing.new :id => 5, :name => "TEST2" + st = SchemaThing.new id: 5, name: "TEST2" st.save! set_session_auth end diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 029314874e..c2a6377cc6 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -260,25 +260,25 @@ def test_classes_with_qualified_schema_name assert_equal 0, Thing3.count assert_equal 0, Thing4.count - Thing1.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now) + Thing1.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now) assert_equal 1, Thing1.count assert_equal 0, Thing2.count assert_equal 0, Thing3.count assert_equal 0, Thing4.count - Thing2.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now) + Thing2.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now) assert_equal 1, Thing1.count assert_equal 1, Thing2.count assert_equal 0, Thing3.count assert_equal 0, Thing4.count - Thing3.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now) + Thing3.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now) assert_equal 1, Thing1.count assert_equal 1, Thing2.count assert_equal 1, Thing3.count assert_equal 0, Thing4.count - Thing4.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now) + Thing4.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now) assert_equal 1, Thing1.count assert_equal 1, Thing2.count assert_equal 1, Thing3.count @@ -401,7 +401,7 @@ def test_current_schema def test_prepared_statements_with_multiple_schemas [SCHEMA_NAME, SCHEMA2_NAME].each do |schema_name| with_schema_search_path schema_name do - Thing5.create(:id => 1, :name => "thing inside #{SCHEMA_NAME}", :email => "thing1@localhost", :moment => Time.now) + Thing5.create(id: 1, name: "thing inside #{SCHEMA_NAME}", email: "thing1@localhost", moment: Time.now) end end diff --git a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb index ad290626ee..e7c1d97d16 100644 --- a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb +++ b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb @@ -63,28 +63,28 @@ def test_load_infinity_and_beyond end def test_save_infinity_and_beyond - d = Developer.create!(:name => "aaron", :updated_at => 1.0 / 0.0) + d = Developer.create!(name: "aaron", updated_at: 1.0 / 0.0) assert_equal(1.0 / 0.0, d.updated_at) - d = Developer.create!(:name => "aaron", :updated_at => -1.0 / 0.0) + d = Developer.create!(name: "aaron", updated_at: -1.0 / 0.0) assert_equal(-1.0 / 0.0, d.updated_at) end def test_bc_timestamp date = Date.new(0) - 1.week - Developer.create!(:name => "aaron", :updated_at => date) + Developer.create!(name: "aaron", updated_at: date) assert_equal date, Developer.find_by_name("aaron").updated_at end def test_bc_timestamp_leap_year date = Time.utc(-4, 2, 29) - Developer.create!(:name => "taihou", :updated_at => date) + Developer.create!(name: "taihou", updated_at: date) assert_equal date, Developer.find_by_name("taihou").updated_at end def test_bc_timestamp_year_zero date = Time.utc(0, 4, 7) - Developer.create!(:name => "yahagi", :updated_at => date) + Developer.create!(name: "yahagi", updated_at: date) assert_equal date, Developer.find_by_name("yahagi").updated_at end end diff --git a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb index 81058064e2..70e2f0fec1 100644 --- a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb @@ -25,7 +25,7 @@ def test_copy_table(from = "customers", to = "customers2", options = {}) def test_copy_table_renaming_column test_copy_table("customers", "customers2", - :rename => {"name" => "person_name"}) do |from, to, options| + rename: {"name" => "person_name"}) do |from, to, options| expected = column_values(from, "name") assert_equal expected, column_values(to, "person_name") assert expected.any?, "No values in table: #{expected.inspect}" @@ -77,7 +77,7 @@ def test_copy_table_with_binary_column protected def copy_table(from, to, options = {}) - @connection.copy_table(from, to, {:temporary => true}.merge(options)) + @connection.copy_table(from, to, {temporary: true}.merge(options)) end def column_names(table) diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb index 6b1b266372..b1b4463bf1 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb @@ -8,9 +8,9 @@ def test_sqlite_creates_directory Dir.mktmpdir do |dir| begin dir = Pathname.new(dir) - @conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"), - :adapter => "sqlite3", - :timeout => 100 + @conn = Base.sqlite3_connection database: dir.join("db/foo.sqlite3"), + adapter: "sqlite3", + timeout: 100 assert Dir.exist? dir.join("db") assert File.exist? dir.join("db/foo.sqlite3") diff --git a/activerecord/test/cases/aggregations_test.rb b/activerecord/test/cases/aggregations_test.rb index 1daa0896ca..f8136fde72 100644 --- a/activerecord/test/cases/aggregations_test.rb +++ b/activerecord/test/cases/aggregations_test.rb @@ -154,11 +154,11 @@ class OverridingAggregationsTest < ActiveRecord::TestCase class DifferentName; end class Person < ActiveRecord::Base - composed_of :composed_of, :mapping => %w(person_first_name first_name) + composed_of :composed_of, mapping: %w(person_first_name first_name) end class DifferentPerson < Person - composed_of :composed_of, :class_name => "DifferentName", :mapping => %w(different_person_first_name first_name) + composed_of :composed_of, class_name: "DifferentName", mapping: %w(different_person_first_name first_name) end def test_composed_of_aggregation_redefinition_reflections_should_differ_and_not_inherited diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb index 37f7a01978..a4919c913d 100644 --- a/activerecord/test/cases/ar_schema_test.rb +++ b/activerecord/test/cases/ar_schema_test.rb @@ -36,7 +36,7 @@ def test_has_primary_key end def test_schema_define - ActiveRecord::Schema.define(:version => 7) do + ActiveRecord::Schema.define(version: 7) do create_table :fruits do |t| t.column :color, :string t.column :fruit_size, :string # NOTE: "size" is reserved in Oracle @@ -55,7 +55,7 @@ def test_schema_define_w_table_name_prefix old_table_name_prefix = ActiveRecord::Base.table_name_prefix ActiveRecord::Base.table_name_prefix = "nep_" ActiveRecord::SchemaMigration.table_name = "nep_#{table_name}" - ActiveRecord::Schema.define(:version => 7) do + ActiveRecord::Schema.define(version: 7) do create_table :fruits do |t| t.column :color, :string t.column :fruit_size, :string # NOTE: "size" is reserved in Oracle @@ -71,7 +71,7 @@ def test_schema_define_w_table_name_prefix def test_schema_raises_an_error_for_invalid_column_type assert_raise NoMethodError do - ActiveRecord::Schema.define(:version => 8) do + ActiveRecord::Schema.define(version: 8) do create_table :vegetables do |t| t.unknown :color end @@ -80,7 +80,7 @@ def test_schema_raises_an_error_for_invalid_column_type end def test_schema_subclass - Class.new(ActiveRecord::Schema).define(:version => 9) do + Class.new(ActiveRecord::Schema).define(version: 9) do create_table :fruits end assert_nothing_raised { @connection.select_all "SELECT * FROM fruits" } diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 20c3b72b41..2413bf0c3a 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -47,7 +47,7 @@ def test_belongs_to_does_not_use_order_by end def test_belongs_to_with_primary_key - client = Client.create(:name => "Primary key client", :firm_name => companies(:first_firm).name) + client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name) assert_equal companies(:first_firm).name, client.firm_with_primary_key.name end @@ -129,12 +129,12 @@ def test_default_scope_on_relations_is_not_cached default_scope -> { counter += 1 - where("id = :inc", :inc => counter) + where("id = :inc", inc: counter) } - has_many :comments, :anonymous_class => comments + has_many :comments, anonymous_class: comments } - belongs_to :post, :anonymous_class => posts, :inverse_of => false + belongs_to :post, anonymous_class: posts, inverse_of: false } assert_equal 0, counter @@ -203,14 +203,14 @@ def test_natural_assignment_with_primary_key def test_eager_loading_with_primary_key Firm.create("name" => "Apple") Client.create("name" => "Citibank", :firm_name => "Apple") - citibank_result = Client.all.merge!(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key).first + citibank_result = Client.all.merge!(where: {name: "Citibank"}, includes: :firm_with_primary_key).first assert citibank_result.association(:firm_with_primary_key).loaded? end def test_eager_loading_with_primary_key_as_symbol Firm.create("name" => "Apple") Client.create("name" => "Citibank", :firm_name => "Apple") - citibank_result = Client.all.merge!(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key_symbols).first + citibank_result = Client.all.merge!(where: {name: "Citibank"}, includes: :firm_with_primary_key_symbols).first assert citibank_result.association(:firm_with_primary_key_symbols).loaded? end @@ -224,7 +224,7 @@ def test_creating_the_belonging_object end def test_creating_the_belonging_object_with_primary_key - client = Client.create(:name => "Primary key client") + client = Client.create(name: "Primary key client") apple = client.create_firm_with_primary_key("name" => "Apple") assert_equal apple, client.firm_with_primary_key client.save @@ -247,36 +247,36 @@ def test_building_the_belonging_object_with_implicit_sti_base_class def test_building_the_belonging_object_with_explicit_sti_base_class account = Account.new - company = account.build_firm(:type => "Company") + company = account.build_firm(type: "Company") assert_kind_of Company, company, "Expected #{company.class} to be a Company" end def test_building_the_belonging_object_with_sti_subclass account = Account.new - company = account.build_firm(:type => "Firm") + company = account.build_firm(type: "Firm") assert_kind_of Firm, company, "Expected #{company.class} to be a Firm" end def test_building_the_belonging_object_with_an_invalid_type account = Account.new - assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(:type => "InvalidType") } + assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "InvalidType") } end def test_building_the_belonging_object_with_an_unrelated_type account = Account.new - assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(:type => "Account") } + assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "Account") } end def test_building_the_belonging_object_with_primary_key - client = Client.create(:name => "Primary key client") + client = Client.create(name: "Primary key client") apple = client.build_firm_with_primary_key("name" => "Apple") client.save assert_equal apple.name, client.firm_name end def test_create! - client = Client.create!(:name => "Jimmy") - account = client.create_account!(:credit_limit => 10) + client = Client.create!(name: "Jimmy") + account = client.create_account!(credit_limit: 10) assert_equal account, client.account assert account.persisted? client.save @@ -285,7 +285,7 @@ def test_create! end def test_failing_create! - client = Client.create!(:name => "Jimmy") + client = Client.create!(name: "Jimmy") assert_raise(ActiveRecord::RecordInvalid) { client.create_account! } assert_not_nil client.account assert client.account.new_record? @@ -301,7 +301,7 @@ def test_natural_assignment_to_nil end def test_natural_assignment_to_nil_with_primary_key - client = Client.create(:name => "Primary key client", :firm_name => companies(:first_firm).name) + client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name) client.firm_with_primary_key = nil client.save client.association(:firm_with_primary_key).reload @@ -330,14 +330,14 @@ def test_polymorphic_association_class sponsor.association(:sponsorable).reload assert_nil sponsor.sponsorable - sponsor.sponsorable = Member.new :name => "Bert" + sponsor.sponsorable = Member.new name: "Bert" assert_equal Member, sponsor.association(:sponsorable).send(:klass) assert_equal "members", sponsor.association(:sponsorable).aliased_table_name end def test_with_polymorphic_and_condition sponsor = Sponsor.create - member = Member.create :name => "Bert" + member = Member.create name: "Bert" sponsor.sponsorable = member assert_equal member, sponsor.sponsorable @@ -346,7 +346,7 @@ def test_with_polymorphic_and_condition def test_with_select assert_equal 1, Company.find(2).firm_with_select.attributes.size - assert_equal 1, Company.all.merge!(:includes => :firm_with_select ).find(2).firm_with_select.attributes.size + assert_equal 1, Company.all.merge!(includes: :firm_with_select ).find(2).firm_with_select.attributes.size end def test_belongs_to_without_counter_cache_option @@ -461,8 +461,8 @@ def test_belongs_to_reassign_with_namespaced_models_and_counters end def test_belongs_to_counter_after_save - topic = Topic.create!(:title => "monday night") - topic.replies.create!(:title => "re: monday night", :content => "football") + topic = Topic.create!(title: "monday night") + topic.replies.create!(title: "re: monday night", content: "football") assert_equal 1, Topic.find(topic.id)[:replies_count] topic.save! @@ -564,8 +564,8 @@ def test_belongs_to_counter_after_update end def test_belongs_to_counter_when_update_columns - topic = Topic.create!(:title => "37s") - topic.replies.create!(:title => "re: 37s", :content => "rails") + topic = Topic.create!(title: "37s") + topic.replies.create!(title: "re: 37s", content: "rails") assert_equal 1, Topic.find(topic.id)[:replies_count] topic.update_columns(content: "rails is wonderful") @@ -601,7 +601,7 @@ def test_assignment_before_child_saved_with_primary_key def test_new_record_with_foreign_key_but_no_object client = Client.new("firm_id" => 1) # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first - assert_equal Firm.all.merge!(:order => "id").first, client.firm_with_basic_id + assert_equal Firm.all.merge!(order: "id").first, client.firm_with_basic_id end def test_setting_foreign_key_after_nil_target_loaded @@ -632,10 +632,10 @@ def test_field_name_same_as_foreign_key end def test_counter_cache - topic = Topic.create :title => "Zoom-zoom-zoom" + topic = Topic.create title: "Zoom-zoom-zoom" assert_equal 0, topic[:replies_count] - reply = Reply.create(:title => "re: zoom", :content => "speedy quick!") + reply = Reply.create(title: "re: zoom", content: "speedy quick!") reply.topic = topic assert_equal 1, topic.reload[:replies_count] @@ -646,10 +646,10 @@ def test_counter_cache end def test_counter_cache_double_destroy - topic = Topic.create :title => "Zoom-zoom-zoom" + topic = Topic.create title: "Zoom-zoom-zoom" 5.times do - topic.replies.create(:title => "re: zoom", :content => "speedy quick!") + topic.replies.create(title: "re: zoom", content: "speedy quick!") end assert_equal 5, topic.reload[:replies_count] @@ -666,10 +666,10 @@ def test_counter_cache_double_destroy end def test_concurrent_counter_cache_double_destroy - topic = Topic.create :title => "Zoom-zoom-zoom" + topic = Topic.create title: "Zoom-zoom-zoom" 5.times do - topic.replies.create(:title => "re: zoom", :content => "speedy quick!") + topic.replies.create(title: "re: zoom", content: "speedy quick!") end assert_equal 5, topic.reload[:replies_count] @@ -687,10 +687,10 @@ def test_concurrent_counter_cache_double_destroy end def test_custom_counter_cache - reply = Reply.create(:title => "re: zoom", :content => "speedy quick!") + reply = Reply.create(title: "re: zoom", content: "speedy quick!") assert_equal 0, reply[:replies_count] - silly = SillyReply.create(:title => "gaga", :content => "boo-boo") + silly = SillyReply.create(title: "gaga", content: "boo-boo") silly.reply = reply assert_equal 1, reply.reload[:replies_count] @@ -714,7 +714,7 @@ def test_replace_counter_cache def test_association_assignment_sticks post = Post.first - author1, author2 = Author.all.merge!(:limit => 2).to_a + author1, author2 = Author.all.merge!(limit: 2).to_a assert_not_nil author1 assert_not_nil author2 @@ -767,7 +767,7 @@ def test_polymorphic_assignment_foreign_type_field_updating def test_polymorphic_assignment_with_primary_key_foreign_type_field_updating # should update when assigning a saved record essay = Essay.new - writer = Author.create(:name => "David") + writer = Author.create(name: "David") essay.writer = writer assert_equal "Author", essay.writer_type @@ -792,7 +792,7 @@ def test_polymorphic_assignment_updates_foreign_id_field_for_new_and_saved_recor def test_assignment_updates_foreign_id_field_for_new_and_saved_records client = Client.new - saved_firm = Firm.create :name => "Saved" + saved_firm = Firm.create name: "Saved" new_firm = Firm.new client.firm = saved_firm @@ -804,7 +804,7 @@ def test_assignment_updates_foreign_id_field_for_new_and_saved_records def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records essay = Essay.new - saved_writer = Author.create(:name => "David") + saved_writer = Author.create(name: "David") new_writer = Author.new essay.writer = saved_writer @@ -842,14 +842,14 @@ def test_save_of_record_with_loaded_belongs_to assert_nothing_raised do Account.find(@account.id).save! - Account.all.merge!(:includes => :firm).find(@account.id).save! + Account.all.merge!(includes: :firm).find(@account.id).save! end @account.firm.delete assert_nothing_raised do Account.find(@account.id).save! - Account.all.merge!(:includes => :firm).find(@account.id).save! + Account.all.merge!(includes: :firm).find(@account.id).save! end end @@ -870,18 +870,18 @@ def test_dependent_delete_and_destroy_with_belongs_to def test_belongs_to_invalid_dependent_option_raises_exception error = assert_raise ArgumentError do - Class.new(Author).belongs_to :special_author_address, :dependent => :nullify + Class.new(Author).belongs_to :special_author_address, dependent: :nullify end assert_equal error.message, "The :dependent option must be one of [:destroy, :delete], but is :nullify" end def test_attributes_are_being_set_when_initialized_from_belongs_to_association_with_where_clause - new_firm = accounts(:signals37).build_firm(:name => "Apple") + new_firm = accounts(:signals37).build_firm(name: "Apple") assert_equal new_firm.name, "Apple" end def test_attributes_are_set_without_error_when_initialized_from_belongs_to_association_with_array_in_where_clause - new_account = Account.where(:credit_limit => [ 50, 60 ]).new + new_account = Account.where(credit_limit: [ 50, 60 ]).new assert_nil new_account.credit_limit end @@ -1002,42 +1002,42 @@ def test_create_bang_with_conditions end def test_build_with_block - client = Client.create(:name => "Client Company") + client = Client.create(name: "Client Company") firm = client.build_firm{ |f| f.name = "Agency Company" } assert_equal "Agency Company", firm.name end def test_create_with_block - client = Client.create(:name => "Client Company") + client = Client.create(name: "Client Company") firm = client.create_firm{ |f| f.name = "Agency Company" } assert_equal "Agency Company", firm.name end def test_create_bang_with_block - client = Client.create(:name => "Client Company") + client = Client.create(name: "Client Company") firm = client.create_firm!{ |f| f.name = "Agency Company" } assert_equal "Agency Company", firm.name end def test_should_set_foreign_key_on_create_association - client = Client.create! :name => "fuu" + client = Client.create! name: "fuu" - firm = client.create_firm :name => "baa" + firm = client.create_firm name: "baa" assert_equal firm.id, client.client_of end def test_should_set_foreign_key_on_create_association! - client = Client.create! :name => "fuu" + client = Client.create! name: "fuu" - firm = client.create_firm! :name => "baa" + firm = client.create_firm! name: "baa" assert_equal firm.id, client.client_of end def test_self_referential_belongs_to_with_counter_cache_assigning_nil - comment = Comment.create! :post => posts(:thinking), :body => "fuu" + comment = Comment.create! post: posts(:thinking), body: "fuu" comment.parent = nil comment.save! @@ -1058,7 +1058,7 @@ def test_belongs_to_with_id_assigning def test_polymorphic_with_custom_primary_key toy = Toy.create! - sponsor = Sponsor.create!(:sponsorable => toy) + sponsor = Sponsor.create!(sponsorable: toy) assert_equal toy, sponsor.reload.sponsorable end @@ -1077,7 +1077,7 @@ def test_polymorphic_with_custom_primary_key def test_reflect_the_most_recent_change author1, author2 = Author.limit(2) - post = Post.new(:title => "foo", :body=> "bar") + post = Post.new(title: "foo", body: "bar") post.author = author1 post.author_id = author2.id diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb index fd35f68d50..15ef2d55c3 100644 --- a/activerecord/test/cases/associations/callbacks_test.rb +++ b/activerecord/test/cases/associations/callbacks_test.rb @@ -61,20 +61,20 @@ def test_multiple_callbacks end def test_has_many_callbacks_with_create - morten = Author.create :name => "Morten" - post = morten.posts_with_proc_callbacks.create! :title => "Hello", :body => "How are you doing?" + morten = Author.create name: "Morten" + post = morten.posts_with_proc_callbacks.create! title: "Hello", body: "How are you doing?" assert_equal ["before_adding", "after_adding#{post.id}"], morten.post_log end def test_has_many_callbacks_with_create! - morten = Author.create! :name => "Morten" - post = morten.posts_with_proc_callbacks.create :title => "Hello", :body => "How are you doing?" + morten = Author.create! name: "Morten" + post = morten.posts_with_proc_callbacks.create title: "Hello", body: "How are you doing?" assert_equal ["before_adding", "after_adding#{post.id}"], morten.post_log end def test_has_many_callbacks_for_save_on_parent - jack = Author.new :name => "Jack" - jack.posts_with_callbacks.build :title => "Call me back!", :body => "Before you wake up and after you sleep" + jack = Author.new name: "Jack" + jack.posts_with_callbacks.build title: "Call me back!", body: "Before you wake up and after you sleep" callback_log = ["before_adding", "after_adding#{jack.posts_with_callbacks.first.id}"] assert_equal callback_log, jack.post_log @@ -84,8 +84,8 @@ def test_has_many_callbacks_for_save_on_parent end def test_has_many_callbacks_for_destroy_on_parent - firm = Firm.create! :name => "Firm" - client = firm.clients.create! :name => "Client" + firm = Firm.create! name: "Firm" + client = firm.clients.create! name: "Client" firm.destroy assert_equal ["before_remove#{client.id}", "after_remove#{client.id}"], firm.log @@ -108,14 +108,14 @@ def test_has_and_belongs_to_many_before_add_called_before_save klass = Class.new(Project) do def self.name; Project.name; end has_and_belongs_to_many :developers_with_callbacks, - :class_name => "Developer", - :before_add => lambda { |o,r| + class_name: "Developer", + before_add: lambda { |o,r| dev = r new_dev = r.new_record? } end rec = klass.create! - alice = Developer.new(:name => "alice") + alice = Developer.new(name: "alice") rec.developers_with_callbacks << alice assert_equal alice, dev assert_not_nil new_dev @@ -126,14 +126,14 @@ def self.name; Project.name; end def test_has_and_belongs_to_many_after_add_called_after_save ar = projects(:active_record) assert ar.developers_log.empty? - alice = Developer.new(:name => "alice") + alice = Developer.new(name: "alice") ar.developers_with_callbacks << alice assert_equal"after_adding#{alice.id}", ar.developers_log.last - bob = ar.developers_with_callbacks.create(:name => "bob") + bob = ar.developers_with_callbacks.create(name: "bob") assert_equal "after_adding#{bob.id}", ar.developers_log.last - ar.developers_with_callbacks.build(:name => "charlie") + ar.developers_with_callbacks.build(name: "charlie") assert_equal "after_adding", ar.developers_log.last end @@ -166,8 +166,8 @@ def test_has_and_belongs_to_many_does_not_fire_callbacks_on_clear end def test_has_many_and_belongs_to_many_callbacks_for_save_on_parent - project = Project.new :name => "Callbacks" - project.developers_with_callbacks.build :name => "Jack", :salary => 95000 + project = Project.new name: "Callbacks" + project.developers_with_callbacks.build name: "Jack", salary: 95000 callback_log = ["before_adding", "after_adding"] assert_equal callback_log, project.developers_log diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb index 0a60de011e..d79246a6c7 100644 --- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb +++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb @@ -16,7 +16,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase :categorizations, :people, :categories, :edges, :vertices def test_eager_association_loading_with_cascaded_two_levels - authors = Author.all.merge!(:includes=>{:posts=>:comments}, :order=>"authors.id").to_a + authors = Author.all.merge!(includes: {posts: :comments}, order: "authors.id").to_a assert_equal 3, authors.size assert_equal 5, authors[0].posts.size assert_equal 3, authors[1].posts.size @@ -24,7 +24,7 @@ def test_eager_association_loading_with_cascaded_two_levels end def test_eager_association_loading_with_cascaded_two_levels_and_one_level - authors = Author.all.merge!(:includes=>[{:posts=>:comments}, :categorizations], :order=>"authors.id").to_a + authors = Author.all.merge!(includes: [{posts: :comments}, :categorizations], order: "authors.id").to_a assert_equal 3, authors.size assert_equal 5, authors[0].posts.size assert_equal 3, authors[1].posts.size @@ -35,22 +35,22 @@ def test_eager_association_loading_with_cascaded_two_levels_and_one_level def test_eager_association_loading_with_hmt_does_not_table_name_collide_when_joining_associations assert_nothing_raised do - Author.joins(:posts).eager_load(:comments).where(:posts => {:tags_count => 1}).to_a + Author.joins(:posts).eager_load(:comments).where(posts: {tags_count: 1}).to_a end - authors = Author.joins(:posts).eager_load(:comments).where(:posts => {:tags_count => 1}).to_a + authors = Author.joins(:posts).eager_load(:comments).where(posts: {tags_count: 1}).to_a assert_equal 1, assert_no_queries { authors.size } assert_equal 10, assert_no_queries { authors[0].comments.size } end def test_eager_association_loading_grafts_stashed_associations_to_correct_parent assert_nothing_raised do - Person.eager_load(:primary_contact => :primary_contact).where("primary_contacts_people_2.first_name = ?", "Susan").order("people.id").to_a + Person.eager_load(primary_contact: :primary_contact).where("primary_contacts_people_2.first_name = ?", "Susan").order("people.id").to_a end - assert_equal people(:michael), Person.eager_load(:primary_contact => :primary_contact).where("primary_contacts_people_2.first_name = ?", "Susan").order("people.id").first + assert_equal people(:michael), Person.eager_load(primary_contact: :primary_contact).where("primary_contacts_people_2.first_name = ?", "Susan").order("people.id").first end def test_cascaded_eager_association_loading_with_join_for_count - categories = Category.joins(:categorizations).includes([{:posts=>:comments}, :authors]) + categories = Category.joins(:categorizations).includes([{posts: :comments}, :authors]) assert_equal 4, categories.count assert_equal 4, categories.to_a.count @@ -59,7 +59,7 @@ def test_cascaded_eager_association_loading_with_join_for_count end def test_cascaded_eager_association_loading_with_duplicated_includes - categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null").references(:categorizations) + categories = Category.includes(:categorizations).includes(categorizations: :author).where("categorizations.id is not null").references(:categorizations) assert_nothing_raised do assert_equal 3, categories.count assert_equal 3, categories.to_a.size @@ -67,7 +67,7 @@ def test_cascaded_eager_association_loading_with_duplicated_includes end def test_cascaded_eager_association_loading_with_twice_includes_edge_cases - categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null").references(:posts) + categories = Category.includes(categorizations: :author).includes(categorizations: :post).where("posts.id is not null").references(:posts) assert_nothing_raised do assert_equal 3, categories.count assert_equal 3, categories.to_a.size @@ -82,7 +82,7 @@ def test_eager_association_loading_with_join_for_count end def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_associations - authors = Author.all.merge!(:includes=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id").to_a + authors = Author.all.merge!(includes: {posts: [:comments, :categorizations]}, order: "authors.id").to_a assert_equal 3, authors.size assert_equal 5, authors[0].posts.size assert_equal 3, authors[1].posts.size @@ -90,7 +90,7 @@ def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_as end def test_eager_association_loading_with_cascaded_two_levels_and_self_table_reference - authors = Author.all.merge!(:includes=>{:posts=>[:comments, :author]}, :order=>"authors.id").to_a + authors = Author.all.merge!(includes: {posts: [:comments, :author]}, order: "authors.id").to_a assert_equal 3, authors.size assert_equal 5, authors[0].posts.size assert_equal authors(:david).name, authors[0].name @@ -98,13 +98,13 @@ def test_eager_association_loading_with_cascaded_two_levels_and_self_table_refer end def test_eager_association_loading_with_cascaded_two_levels_with_condition - authors = Author.all.merge!(:includes=>{:posts=>:comments}, :where=>"authors.id=1", :order=>"authors.id").to_a + authors = Author.all.merge!(includes: {posts: :comments}, where: "authors.id=1", order: "authors.id").to_a assert_equal 1, authors.size assert_equal 5, authors[0].posts.size end def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong - firms = Firm.all.merge!(:includes=>{:account=>{:firm=>:account}}, :order=>"companies.id").to_a + firms = Firm.all.merge!(includes: {account: {firm: :account}}, order: "companies.id").to_a assert_equal 2, firms.size assert_equal firms.first.account, firms.first.account.firm.account assert_equal companies(:first_firm).account, assert_no_queries { firms.first.account.firm.account } @@ -112,7 +112,7 @@ def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong end def test_eager_association_loading_with_has_many_sti - topics = Topic.all.merge!(:includes => :replies, :order => "topics.id").to_a + topics = Topic.all.merge!(includes: :replies, order: "topics.id").to_a first, second, = topics(:first).replies.size, topics(:second).replies.size assert_no_queries do assert_equal first, topics[0].replies.size @@ -121,11 +121,11 @@ def test_eager_association_loading_with_has_many_sti end def test_eager_association_loading_with_has_many_sti_and_subclasses - silly = SillyReply.new(:title => "gaga", :content => "boo-boo", :parent_id => 1) + silly = SillyReply.new(title: "gaga", content: "boo-boo", parent_id: 1) silly.parent_id = 1 assert silly.save - topics = Topic.all.merge!(:includes => :replies, :order => ["topics.id", "replies_topics.id"]).to_a + topics = Topic.all.merge!(includes: :replies, order: ["topics.id", "replies_topics.id"]).to_a assert_no_queries do assert_equal 2, topics[0].replies.size assert_equal 0, topics[1].replies.size @@ -133,14 +133,14 @@ def test_eager_association_loading_with_has_many_sti_and_subclasses end def test_eager_association_loading_with_belongs_to_sti - replies = Reply.all.merge!(:includes => :topic, :order => "topics.id").to_a + replies = Reply.all.merge!(includes: :topic, order: "topics.id").to_a assert replies.include?(topics(:second)) assert !replies.include?(topics(:first)) assert_equal topics(:first), assert_no_queries { replies.first.topic } end def test_eager_association_loading_with_multiple_stis_and_order - author = Author.all.merge!(:includes => { :posts => [ :special_comments , :very_special_comment ] }, :order => ["authors.name", "comments.body", "very_special_comments_posts.body"], :where => "posts.id = 4").first + author = Author.all.merge!(includes: { posts: [ :special_comments , :very_special_comment ] }, order: ["authors.name", "comments.body", "very_special_comments_posts.body"], where: "posts.id = 4").first assert_equal authors(:david), author assert_no_queries do author.posts.first.special_comments @@ -149,7 +149,7 @@ def test_eager_association_loading_with_multiple_stis_and_order end def test_eager_association_loading_of_stis_with_multiple_references - authors = Author.all.merge!(:includes => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => "comments.body, very_special_comments_posts.body", :where => "posts.id = 4").to_a + authors = Author.all.merge!(includes: { posts: { special_comments: { post: [ :special_comments, :very_special_comment ] } } }, order: "comments.body, very_special_comments_posts.body", where: "posts.id = 4").to_a assert_equal [authors(:david)], authors assert_no_queries do authors.first.posts.first.special_comments.first.post.special_comments @@ -158,7 +158,7 @@ def test_eager_association_loading_of_stis_with_multiple_references end def test_eager_association_loading_where_first_level_returns_nil - authors = Author.all.merge!(:includes => {:post_about_thinking => :comments}, :order => "authors.id DESC").to_a + authors = Author.all.merge!(includes: {post_about_thinking: :comments}, order: "authors.id DESC").to_a assert_equal [authors(:bob), authors(:mary), authors(:david)], authors assert_no_queries do authors[2].post_about_thinking.comments.first @@ -166,12 +166,12 @@ def test_eager_association_loading_where_first_level_returns_nil end def test_eager_association_loading_with_recursive_cascading_four_levels_has_many_through - source = Vertex.all.merge!(:includes=>{:sinks=>{:sinks=>{:sinks=>:sinks}}}, :order => "vertices.id").first + source = Vertex.all.merge!(includes: {sinks: {sinks: {sinks: :sinks}}}, order: "vertices.id").first assert_equal vertices(:vertex_4), assert_no_queries { source.sinks.first.sinks.first.sinks.first } end def test_eager_association_loading_with_recursive_cascading_four_levels_has_and_belongs_to_many - sink = Vertex.all.merge!(:includes=>{:sources=>{:sources=>{:sources=>:sources}}}, :order => "vertices.id DESC").first + sink = Vertex.all.merge!(includes: {sources: {sources: {sources: :sources}}}, order: "vertices.id DESC").first assert_equal vertices(:vertex_1), assert_no_queries { sink.sources.first.sources.first.sources.first.sources.first } end diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb index e852e91f20..38c5fd8f1a 100644 --- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb +++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb @@ -5,7 +5,7 @@ module Namespaced class Post < ActiveRecord::Base self.table_name = "posts" - has_one :tagging, :as => :taggable, :class_name => "Tagging" + has_one :tagging, as: :taggable, class_name: "Tagging" end end @@ -16,8 +16,8 @@ def setup end def generate_test_objects - post = Namespaced::Post.create( :title => "Great stuff", :body => "This is not", :author_id => 1 ) - Tagging.create( :taggable => post ) + post = Namespaced::Post.create( title: "Great stuff", body: "This is not", author_id: 1 ) + Tagging.create( taggable: post ) end def test_class_names diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 4762ef90c5..7a3d0c6068 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -23,30 +23,30 @@ def sample; @@remembered.sample; end end class ShapeExpression < ActiveRecord::Base - belongs_to :shape, :polymorphic => true - belongs_to :paint, :polymorphic => true + belongs_to :shape, polymorphic: true + belongs_to :paint, polymorphic: true end class Circle < ActiveRecord::Base - has_many :shape_expressions, :as => :shape + has_many :shape_expressions, as: :shape include Remembered end class Square < ActiveRecord::Base - has_many :shape_expressions, :as => :shape + has_many :shape_expressions, as: :shape include Remembered end class Triangle < ActiveRecord::Base - has_many :shape_expressions, :as => :shape + has_many :shape_expressions, as: :shape include Remembered end class PaintColor < ActiveRecord::Base - has_many :shape_expressions, :as => :paint - belongs_to :non_poly, :foreign_key => "non_poly_one_id", :class_name => "NonPolyOne" + has_many :shape_expressions, as: :paint + belongs_to :non_poly, foreign_key: "non_poly_one_id", class_name: "NonPolyOne" include Remembered end class PaintTexture < ActiveRecord::Base - has_many :shape_expressions, :as => :paint - belongs_to :non_poly, :foreign_key => "non_poly_two_id", :class_name => "NonPolyTwo" + has_many :shape_expressions, as: :paint + belongs_to :non_poly, foreign_key: "non_poly_two_id", class_name: "NonPolyTwo" include Remembered end class NonPolyOne < ActiveRecord::Base @@ -78,19 +78,19 @@ def generate_test_object_graphs [Circle, Square, Triangle, NonPolyOne, NonPolyTwo].map(&:create!) end 1.upto(NUM_SIMPLE_OBJS) do - PaintColor.create!(:non_poly_one_id => NonPolyOne.sample.id) - PaintTexture.create!(:non_poly_two_id => NonPolyTwo.sample.id) + PaintColor.create!(non_poly_one_id: NonPolyOne.sample.id) + PaintTexture.create!(non_poly_two_id: NonPolyTwo.sample.id) end 1.upto(NUM_SHAPE_EXPRESSIONS) do shape_type = [Circle, Square, Triangle].sample paint_type = [PaintColor, PaintTexture].sample - ShapeExpression.create!(:shape_type => shape_type.to_s, :shape_id => shape_type.sample.id, - :paint_type => paint_type.to_s, :paint_id => paint_type.sample.id) + ShapeExpression.create!(shape_type: shape_type.to_s, shape_id: shape_type.sample.id, + paint_type: paint_type.to_s, paint_id: paint_type.sample.id) end end def test_include_query - res = ShapeExpression.all.merge!(:includes => [ :shape, { :paint => :non_poly } ]).to_a + res = ShapeExpression.all.merge!(includes: [ :shape, { paint: :non_poly } ]).to_a assert_equal NUM_SHAPE_EXPRESSIONS, res.size assert_queries(0) do res.each do |se| @@ -103,10 +103,10 @@ def test_include_query class EagerLoadNestedIncludeWithMissingDataTest < ActiveRecord::TestCase def setup - @davey_mcdave = Author.create(:name => "Davey McDave") - @first_post = @davey_mcdave.posts.create(:title => "Davey Speaks", :body => "Expressive wordage") - @first_comment = @first_post.comments.create(:body => "Inflamatory doublespeak") - @first_categorization = @davey_mcdave.categorizations.create(:category => Category.first, :post => @first_post) + @davey_mcdave = Author.create(name: "Davey McDave") + @first_post = @davey_mcdave.posts.create(title: "Davey Speaks", body: "Expressive wordage") + @first_comment = @first_post.comments.create(body: "Inflamatory doublespeak") + @first_categorization = @davey_mcdave.categorizations.create(category: Category.first, post: @first_post) end teardown do @@ -119,8 +119,8 @@ def setup def test_missing_data_in_a_nested_include_should_not_cause_errors_when_constructing_objects assert_nothing_raised do # @davey_mcdave doesn't have any author_favorites - includes = {:posts => :comments, :categorizations => :category, :author_favorites => :favorite_author } - Author.all.merge!(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => "categories.name").to_a + includes = {posts: :comments, categorizations: :category, author_favorites: :favorite_author } + Author.all.merge!(includes: includes, where: {authors: {name: @davey_mcdave.name}}, order: "categories.name").to_a end end end diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb index a61a070331..df238b4859 100644 --- a/activerecord/test/cases/associations/eager_singularization_test.rb +++ b/activerecord/test/cases/associations/eager_singularization_test.rb @@ -25,10 +25,10 @@ class Mess < ActiveRecord::Base class Crisis < ActiveRecord::Base has_and_belongs_to_many :messes - has_many :analyses, :dependent => :destroy - has_many :successes, :through => :analyses - has_many :dresses, :dependent => :destroy - has_many :compresses, :through => :dresses + has_many :analyses, dependent: :destroy + has_many :successes, through: :analyses + has_many :dresses, dependent: :destroy + has_many :compresses, through: :dresses end class Analysis < ActiveRecord::Base @@ -37,8 +37,8 @@ class Analysis < ActiveRecord::Base end class Success < ActiveRecord::Base - has_many :analyses, :dependent => :destroy - has_many :crises, :through => :analyses + has_many :analyses, dependent: :destroy + has_many :crises, through: :analyses end class Dress < ActiveRecord::Base @@ -65,7 +65,7 @@ def setup connection.create_table :buses do |t| t.column :name, :string end - connection.create_table :crises_messes, :id => false do |t| + connection.create_table :crises_messes, id: false do |t| t.column :crisis_id, :integer t.column :mess_id, :integer end @@ -110,38 +110,38 @@ def connection def test_eager_no_extra_singularization_belongs_to assert_nothing_raised do - Virus.all.merge!(:includes => :octopus).to_a + Virus.all.merge!(includes: :octopus).to_a end end def test_eager_no_extra_singularization_has_one assert_nothing_raised do - Octopus.all.merge!(:includes => :virus).to_a + Octopus.all.merge!(includes: :virus).to_a end end def test_eager_no_extra_singularization_has_many assert_nothing_raised do - Bus.all.merge!(:includes => :passes).to_a + Bus.all.merge!(includes: :passes).to_a end end def test_eager_no_extra_singularization_has_and_belongs_to_many assert_nothing_raised do - Crisis.all.merge!(:includes => :messes).to_a - Mess.all.merge!(:includes => :crises).to_a + Crisis.all.merge!(includes: :messes).to_a + Mess.all.merge!(includes: :crises).to_a end end def test_eager_no_extra_singularization_has_many_through_belongs_to assert_nothing_raised do - Crisis.all.merge!(:includes => :successes).to_a + Crisis.all.merge!(includes: :successes).to_a end end def test_eager_no_extra_singularization_has_many_through_has_many assert_nothing_raised do - Crisis.all.merge!(:includes => :compresses).to_a + Crisis.all.merge!(includes: :compresses).to_a end end end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 4da30ea3b6..c7c945e33f 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -34,42 +34,42 @@ class EagerAssociationTest < ActiveRecord::TestCase :developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors def test_eager_with_has_one_through_join_model_with_conditions_on_the_through - member = Member.all.merge!(:includes => :favourite_club).find(members(:some_other_guy).id) + member = Member.all.merge!(includes: :favourite_club).find(members(:some_other_guy).id) assert_nil member.favourite_club end def test_loading_with_one_association - posts = Post.all.merge!(:includes => :comments).to_a + posts = Post.all.merge!(includes: :comments).to_a post = posts.find { |p| p.id == 1 } assert_equal 2, post.comments.size assert post.comments.include?(comments(:greetings)) - post = Post.all.merge!(:includes => :comments, :where => "posts.title = 'Welcome to the weblog'").first + post = Post.all.merge!(includes: :comments, where: "posts.title = 'Welcome to the weblog'").first assert_equal 2, post.comments.size assert post.comments.include?(comments(:greetings)) - posts = Post.all.merge!(:includes => :last_comment).to_a + posts = Post.all.merge!(includes: :last_comment).to_a post = posts.find { |p| p.id == 1 } assert_equal Post.find(1).last_comment, post.last_comment end def test_loading_with_one_association_with_non_preload - posts = Post.all.merge!(:includes => :last_comment, :order => "comments.id DESC").to_a + posts = Post.all.merge!(includes: :last_comment, order: "comments.id DESC").to_a post = posts.find { |p| p.id == 1 } assert_equal Post.find(1).last_comment, post.last_comment end def test_loading_conditions_with_or posts = authors(:david).posts.references(:comments).merge( - :includes => :comments, - :where => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'" + includes: :comments, + where: "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'" ).to_a assert_nil posts.detect { |p| p.author_id != authors(:david).id }, "expected to find only david's posts" end def test_with_ordering - list = Post.all.merge!(:includes => :comments, :order => "posts.id DESC").to_a + list = Post.all.merge!(includes: :comments, order: "posts.id DESC").to_a [:other_by_mary, :other_by_bob, :misc_by_mary, :misc_by_bob, :eager_other, :sti_habtm, :sti_post_and_comments, :sti_comments, :authorless, :thinking, :welcome ].each_with_index do |post, index| @@ -100,14 +100,14 @@ def test_with_two_tables_in_from_without_getting_double_quoted end def test_loading_with_multiple_associations - posts = Post.all.merge!(:includes => [ :comments, :author, :categories ], :order => "posts.id").to_a + posts = Post.all.merge!(includes: [ :comments, :author, :categories ], order: "posts.id").to_a assert_equal 2, posts.first.comments.size assert_equal 2, posts.first.categories.size assert posts.first.comments.include?(comments(:greetings)) end def test_duplicate_middle_objects - comments = Comment.all.merge!(:where => "post_id = 1", :includes => [:post => :author]).to_a + comments = Comment.all.merge!(where: "post_id = 1", includes: [post: :author]).to_a assert_no_queries do comments.each {|comment| comment.post.author.name} end @@ -115,28 +115,28 @@ def test_duplicate_middle_objects def test_preloading_has_many_in_multiple_queries_with_more_ids_than_database_can_handle assert_called(Comment.connection, :in_clause_length, returns: 5) do - posts = Post.all.merge!(:includes=>:comments).to_a + posts = Post.all.merge!(includes: :comments).to_a assert_equal 11, posts.size end end def test_preloading_has_many_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle assert_called(Comment.connection, :in_clause_length, returns: nil) do - posts = Post.all.merge!(:includes=>:comments).to_a + posts = Post.all.merge!(includes: :comments).to_a assert_equal 11, posts.size end end def test_preloading_habtm_in_multiple_queries_with_more_ids_than_database_can_handle assert_called(Comment.connection, :in_clause_length, times: 2, returns: 5) do - posts = Post.all.merge!(:includes=>:categories).to_a + posts = Post.all.merge!(includes: :categories).to_a assert_equal 11, posts.size end end def test_preloading_habtm_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle assert_called(Comment.connection, :in_clause_length, times: 2, returns: nil) do - posts = Post.all.merge!(:includes=>:categories).to_a + posts = Post.all.merge!(includes: :categories).to_a assert_equal 11, posts.size end end @@ -145,7 +145,7 @@ def test_load_associated_records_in_one_query_when_adapter_has_no_limit assert_called(Comment.connection, :in_clause_length, returns: nil) do post = posts(:welcome) assert_queries(2) do - Post.includes(:comments).where(:id => post.id).to_a + Post.includes(:comments).where(id: post.id).to_a end end end @@ -154,7 +154,7 @@ def test_load_associated_records_in_several_queries_when_many_ids_passed assert_called(Comment.connection, :in_clause_length, returns: 1) do post1, post2 = posts(:welcome), posts(:thinking) assert_queries(3) do - Post.includes(:comments).where(:id => [post1.id, post2.id]).to_a + Post.includes(:comments).where(id: [post1.id, post2.id]).to_a end end end @@ -163,50 +163,50 @@ def test_load_associated_records_in_one_query_when_a_few_ids_passed assert_called(Comment.connection, :in_clause_length, returns: 3) do post = posts(:welcome) assert_queries(2) do - Post.includes(:comments).where(:id => post.id).to_a + Post.includes(:comments).where(id: post.id).to_a end end end def test_including_duplicate_objects_from_belongs_to - popular_post = Post.create!(:title => "foo", :body => "I like cars!") - comment = popular_post.comments.create!(:body => "lol") - popular_post.readers.create!(:person => people(:michael)) - popular_post.readers.create!(:person => people(:david)) + popular_post = Post.create!(title: "foo", body: "I like cars!") + comment = popular_post.comments.create!(body: "lol") + popular_post.readers.create!(person: people(:michael)) + popular_post.readers.create!(person: people(:david)) - readers = Reader.all.merge!(:where => ["post_id = ?", popular_post.id], - :includes => {:post => :comments}).to_a + readers = Reader.all.merge!(where: ["post_id = ?", popular_post.id], + includes: {post: :comments}).to_a readers.each do |reader| assert_equal [comment], reader.post.comments end end def test_including_duplicate_objects_from_has_many - car_post = Post.create!(:title => "foo", :body => "I like cars!") + car_post = Post.create!(title: "foo", body: "I like cars!") car_post.categories << categories(:general) car_post.categories << categories(:technology) - comment = car_post.comments.create!(:body => "hmm") - categories = Category.all.merge!(:where => { "posts.id" => car_post.id }, - :includes => {:posts => :comments}).to_a + comment = car_post.comments.create!(body: "hmm") + categories = Category.all.merge!(where: { "posts.id" => car_post.id }, + includes: {posts: :comments}).to_a categories.each do |category| assert_equal [comment], category.posts[0].comments end end def test_associations_loaded_for_all_records - post = Post.create!(:title => "foo", :body => "I like cars!") - SpecialComment.create!(:body => "Come on!", :post => post) - first_category = Category.create! :name => "First!", :posts => [post] - second_category = Category.create! :name => "Second!", :posts => [post] + post = Post.create!(title: "foo", body: "I like cars!") + SpecialComment.create!(body: "Come on!", post: post) + first_category = Category.create! name: "First!", posts: [post] + second_category = Category.create! name: "Second!", posts: [post] - categories = Category.where(:id => [first_category.id, second_category.id]).includes(:posts => :special_comments) + categories = Category.where(id: [first_category.id, second_category.id]).includes(posts: :special_comments) assert_equal categories.map { |category| category.posts.first.special_comments.loaded? }, [true, true] end def test_finding_with_includes_on_has_many_association_with_same_include_includes_only_once author_id = authors(:david).id - author = assert_queries(3) { Author.all.merge!(:includes => {:posts_with_comments => :comments}).find(author_id) } # find the author, then find the posts, then find the comments + author = assert_queries(3) { Author.all.merge!(includes: {posts_with_comments: :comments}).find(author_id) } # find the author, then find the posts, then find the comments author.posts_with_comments.each do |post_with_comments| assert_equal post_with_comments.comments.length, post_with_comments.comments.count assert_nil post_with_comments.comments.to_a.uniq! @@ -217,7 +217,7 @@ def test_finding_with_includes_on_has_one_association_with_same_include_includes author = authors(:david) post = author.post_about_thinking_with_last_comment last_comment = post.last_comment - author = assert_queries(3) { Author.all.merge!(:includes => {:post_about_thinking_with_last_comment => :last_comment}).find(author.id)} # find the author, then find the posts, then find the comments + author = assert_queries(3) { Author.all.merge!(includes: {post_about_thinking_with_last_comment: :last_comment}).find(author.id)} # find the author, then find the posts, then find the comments assert_no_queries do assert_equal post, author.post_about_thinking_with_last_comment assert_equal last_comment, author.post_about_thinking_with_last_comment.last_comment @@ -228,7 +228,7 @@ def test_finding_with_includes_on_belongs_to_association_with_same_include_inclu post = posts(:welcome) author = post.author author_address = author.author_address - post = assert_queries(3) { Post.all.merge!(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author, then find the address + post = assert_queries(3) { Post.all.merge!(includes: {author_with_address: :author_address}).find(post.id) } # find the post, then find the author, then find the address assert_no_queries do assert_equal author, post.author_with_address assert_equal author_address, post.author_with_address.author_address @@ -248,7 +248,7 @@ def test_finding_with_includes_on_null_belongs_to_association_with_same_include_ def test_finding_with_includes_on_null_belongs_to_polymorphic_association sponsor = sponsors(:moustache_club_sponsor_for_groucho) sponsor.update!(sponsorable: nil) - sponsor = assert_queries(1) { Sponsor.all.merge!(:includes => :sponsorable).find(sponsor.id) } + sponsor = assert_queries(1) { Sponsor.all.merge!(includes: :sponsorable).find(sponsor.id) } assert_no_queries do assert_equal nil, sponsor.sponsorable end @@ -258,7 +258,7 @@ def test_finding_with_includes_on_empty_polymorphic_type_column sponsor = sponsors(:moustache_club_sponsor_for_groucho) sponsor.update!(sponsorable_type: "", sponsorable_id: nil) # sponsorable_type column might be declared NOT NULL sponsor = assert_queries(1) do - assert_nothing_raised { Sponsor.all.merge!(:includes => :sponsorable).find(sponsor.id) } + assert_nothing_raised { Sponsor.all.merge!(includes: :sponsorable).find(sponsor.id) } end assert_no_queries do assert_equal nil, sponsor.sponsorable @@ -266,25 +266,25 @@ def test_finding_with_includes_on_empty_polymorphic_type_column end def test_loading_from_an_association - posts = authors(:david).posts.merge(:includes => :comments, :order => "posts.id").to_a + posts = authors(:david).posts.merge(includes: :comments, order: "posts.id").to_a assert_equal 2, posts.first.comments.size end def test_loading_from_an_association_that_has_a_hash_of_conditions assert_nothing_raised do - Author.all.merge!(:includes => :hello_posts_with_hash_conditions).to_a + Author.all.merge!(includes: :hello_posts_with_hash_conditions).to_a end - assert !Author.all.merge!(:includes => :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts.empty? + assert !Author.all.merge!(includes: :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts.empty? end def test_loading_with_no_associations - assert_nil Post.all.merge!(:includes => :author).find(posts(:authorless).id).author + assert_nil Post.all.merge!(includes: :author).find(posts(:authorless).id).author end # Regression test for 21c75e5 def test_nested_loading_does_not_raise_exception_when_association_does_not_exist assert_nothing_raised do - Post.all.merge!(:includes => {:author => :author_addresss}).find(posts(:authorless).id) + Post.all.merge!(includes: {author: :author_addresss}).find(posts(:authorless).id) end end @@ -292,61 +292,61 @@ def test_three_level_nested_preloading_does_not_raise_exception_when_association post_id = Comment.where(author_id: nil).where.not(post_id: nil).first.post_id assert_nothing_raised do - Post.preload(:comments => [{:author => :essays}]).find(post_id) + Post.preload(comments: [{author: :essays}]).find(post_id) end end def test_nested_loading_through_has_one_association - aa = AuthorAddress.all.merge!(:includes => {:author => :posts}).find(author_addresses(:david_address).id) + aa = AuthorAddress.all.merge!(includes: {author: :posts}).find(author_addresses(:david_address).id) assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_order - aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => "author_addresses.id").find(author_addresses(:david_address).id) + aa = AuthorAddress.all.merge!(includes: {author: :posts}, order: "author_addresses.id").find(author_addresses(:david_address).id) assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_order_on_association - aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => "authors.id").find(author_addresses(:david_address).id) + aa = AuthorAddress.all.merge!(includes: {author: :posts}, order: "authors.id").find(author_addresses(:david_address).id) assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_order_on_nested_association - aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => "posts.id").find(author_addresses(:david_address).id) + aa = AuthorAddress.all.merge!(includes: {author: :posts}, order: "posts.id").find(author_addresses(:david_address).id) assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_conditions aa = AuthorAddress.references(:author_addresses).merge( - :includes => {:author => :posts}, - :where => "author_addresses.id > 0" + includes: {author: :posts}, + where: "author_addresses.id > 0" ).find author_addresses(:david_address).id assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_conditions_on_association aa = AuthorAddress.references(:authors).merge( - :includes => {:author => :posts}, - :where => "authors.id > 0" + includes: {author: :posts}, + where: "authors.id > 0" ).find author_addresses(:david_address).id assert_equal aa.author.posts.count, aa.author.posts.length end def test_nested_loading_through_has_one_association_with_conditions_on_nested_association aa = AuthorAddress.references(:posts).merge( - :includes => {:author => :posts}, - :where => "posts.id > 0" + includes: {author: :posts}, + where: "posts.id > 0" ).find author_addresses(:david_address).id assert_equal aa.author.posts.count, aa.author.posts.length end def test_eager_association_loading_with_belongs_to_and_foreign_keys - pets = Pet.all.merge!(:includes => :owner).to_a + pets = Pet.all.merge!(includes: :owner).to_a assert_equal 4, pets.length end def test_eager_association_loading_with_belongs_to - comments = Comment.all.merge!(:includes => :post).to_a + comments = Comment.all.merge!(includes: :post).to_a assert_equal 11, comments.length titles = comments.map { |c| c.post.title } assert titles.include?(posts(:welcome).title) @@ -354,31 +354,31 @@ def test_eager_association_loading_with_belongs_to end def test_eager_association_loading_with_belongs_to_and_limit - comments = Comment.all.merge!(:includes => :post, :limit => 5, :order => "comments.id").to_a + comments = Comment.all.merge!(includes: :post, limit: 5, order: "comments.id").to_a assert_equal 5, comments.length assert_equal [1,2,3,5,6], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_conditions - comments = Comment.all.merge!(:includes => :post, :where => "post_id = 4", :limit => 3, :order => "comments.id").to_a + comments = Comment.all.merge!(includes: :post, where: "post_id = 4", limit: 3, order: "comments.id").to_a assert_equal 3, comments.length assert_equal [5,6,7], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_offset - comments = Comment.all.merge!(:includes => :post, :limit => 3, :offset => 2, :order => "comments.id").to_a + comments = Comment.all.merge!(includes: :post, limit: 3, offset: 2, order: "comments.id").to_a assert_equal 3, comments.length assert_equal [3,5,6], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions - comments = Comment.all.merge!(:includes => :post, :where => "post_id = 4", :limit => 3, :offset => 1, :order => "comments.id").to_a + comments = Comment.all.merge!(includes: :post, where: "post_id = 4", limit: 3, offset: 1, order: "comments.id").to_a assert_equal 3, comments.length assert_equal [6,7,8], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array - comments = Comment.all.merge!(:includes => :post, :where => ["post_id = ?",4], :limit => 3, :offset => 1, :order => "comments.id").to_a + comments = Comment.all.merge!(includes: :post, where: ["post_id = ?",4], limit: 3, offset: 1, order: "comments.id").to_a assert_equal 3, comments.length assert_equal [6,7,8], comments.collect(&:id) end @@ -392,7 +392,7 @@ def test_eager_association_loading_with_belongs_to_and_conditions_string_with_un def test_eager_association_loading_with_belongs_to_and_conditions_hash comments = [] assert_nothing_raised do - comments = Comment.all.merge!(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => "comments.id").to_a + comments = Comment.all.merge!(includes: :post, where: {posts: {id: 4}}, limit: 3, order: "comments.id").to_a end assert_equal 3, comments.length assert_equal [5,6,7], comments.collect(&:id) @@ -410,7 +410,7 @@ def test_eager_association_loading_with_belongs_to_and_conditions_string_with_qu def test_eager_association_loading_with_belongs_to_and_order_string_with_unquoted_table_name assert_nothing_raised do - Comment.all.merge!(:includes => :post, :order => "posts.id").to_a + Comment.all.merge!(includes: :post, order: "posts.id").to_a end end @@ -422,19 +422,19 @@ def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_ end def test_eager_association_loading_with_belongs_to_and_limit_and_multiple_associations - posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :order => "posts.id").to_a + posts = Post.all.merge!(includes: [:author, :very_special_comment], limit: 1, order: "posts.id").to_a assert_equal 1, posts.length assert_equal [1], posts.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_multiple_associations - posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => "posts.id").to_a + posts = Post.all.merge!(includes: [:author, :very_special_comment], limit: 1, offset: 1, order: "posts.id").to_a assert_equal 1, posts.length assert_equal [2], posts.collect(&:id) end def test_eager_association_loading_with_belongs_to_inferred_foreign_key_from_association_name - author_favorite = AuthorFavorite.all.merge!(:includes => :favorite_author).first + author_favorite = AuthorFavorite.all.merge!(includes: :favorite_author).first assert_equal authors(:mary), assert_no_queries { author_favorite.favorite_author } end @@ -445,26 +445,26 @@ def test_eager_load_belongs_to_quotes_table_and_column_names end def test_eager_load_has_one_quotes_table_and_column_names - michael = Person.all.merge!(:includes => :favourite_reference).find(people(:michael).id) + michael = Person.all.merge!(includes: :favourite_reference).find(people(:michael).id) references(:michael_unicyclist) assert_no_queries{ assert_equal references(:michael_unicyclist), michael.favourite_reference} end def test_eager_load_has_many_quotes_table_and_column_names - michael = Person.all.merge!(:includes => :references).find(people(:michael).id) + michael = Person.all.merge!(includes: :references).find(people(:michael).id) references(:michael_magician,:michael_unicyclist) assert_no_queries{ assert_equal references(:michael_magician,:michael_unicyclist), michael.references.sort_by(&:id) } end def test_eager_load_has_many_through_quotes_table_and_column_names - michael = Person.all.merge!(:includes => :jobs).find(people(:michael).id) + michael = Person.all.merge!(includes: :jobs).find(people(:michael).id) jobs(:magician, :unicyclist) assert_no_queries{ assert_equal jobs(:unicyclist, :magician), michael.jobs.sort_by(&:id) } end def test_eager_load_has_many_with_string_keys subscriptions = subscriptions(:webster_awdr, :webster_rfr) - subscriber =Subscriber.all.merge!(:includes => :subscriptions).find(subscribers(:second).id) + subscriber =Subscriber.all.merge!(includes: :subscriptions).find(subscribers(:second).id) assert_equal subscriptions, subscriber.subscriptions.sort_by(&:id) end @@ -475,32 +475,32 @@ def test_string_id_column_joins b = Book.create! - Subscription.create!(:subscriber_id => "PL", :book_id => b.id) + Subscription.create!(subscriber_id: "PL", book_id: b.id) s.reload s.book_ids = s.book_ids end def test_eager_load_has_many_through_with_string_keys books = books(:awdr, :rfr) - subscriber = Subscriber.all.merge!(:includes => :books).find(subscribers(:second).id) + subscriber = Subscriber.all.merge!(includes: :books).find(subscribers(:second).id) assert_equal books, subscriber.books.sort_by(&:id) end def test_eager_load_belongs_to_with_string_keys subscriber = subscribers(:second) - subscription = Subscription.all.merge!(:includes => :subscriber).find(subscriptions(:webster_awdr).id) + subscription = Subscription.all.merge!(includes: :subscriber).find(subscriptions(:webster_awdr).id) assert_equal subscriber, subscription.subscriber end def test_eager_association_loading_with_explicit_join - posts = Post.all.merge!(:includes => :comments, :joins => "INNER JOIN authors ON posts.author_id = authors.id AND authors.name = 'Mary'", :limit => 1, :order => "author_id").to_a + posts = Post.all.merge!(includes: :comments, joins: "INNER JOIN authors ON posts.author_id = authors.id AND authors.name = 'Mary'", limit: 1, order: "author_id").to_a assert_equal 1, posts.length end def test_eager_with_has_many_through - posts_with_comments = people(:michael).posts.merge(:includes => :comments, :order => "posts.id").to_a - posts_with_author = people(:michael).posts.merge(:includes => :author, :order => "posts.id").to_a - posts_with_comments_and_author = people(:michael).posts.merge(:includes => [ :comments, :author ], :order => "posts.id").to_a + posts_with_comments = people(:michael).posts.merge(includes: :comments, order: "posts.id").to_a + posts_with_author = people(:michael).posts.merge(includes: :author, order: "posts.id").to_a + posts_with_comments_and_author = people(:michael).posts.merge(includes: [ :comments, :author ], order: "posts.id").to_a assert_equal 2, posts_with_comments.inject(0) { |sum, post| sum + post.comments.size } assert_equal authors(:david), assert_no_queries { posts_with_author.first.author } assert_equal authors(:david), assert_no_queries { posts_with_comments_and_author.first.author } @@ -508,35 +508,35 @@ def test_eager_with_has_many_through def test_eager_with_has_many_through_a_belongs_to_association author = authors(:mary) - Post.create!(:author => author, :title => "TITLE", :body => "BODY") - author.author_favorites.create(:favorite_author_id => 1) - author.author_favorites.create(:favorite_author_id => 2) - posts_with_author_favorites = author.posts.merge(:includes => :author_favorites).to_a + Post.create!(author: author, title: "TITLE", body: "BODY") + author.author_favorites.create(favorite_author_id: 1) + author.author_favorites.create(favorite_author_id: 2) + posts_with_author_favorites = author.posts.merge(includes: :author_favorites).to_a assert_no_queries { posts_with_author_favorites.first.author_favorites.first.author_id } end def test_eager_with_has_many_through_an_sti_join_model - author = Author.all.merge!(:includes => :special_post_comments, :order => "authors.id").first + author = Author.all.merge!(includes: :special_post_comments, order: "authors.id").first assert_equal [comments(:does_it_hurt)], assert_no_queries { author.special_post_comments } end def test_eager_with_has_many_through_an_sti_join_model_with_conditions_on_both - author = Author.all.merge!(:includes => :special_nonexistent_post_comments, :order => "authors.id").first + author = Author.all.merge!(includes: :special_nonexistent_post_comments, order: "authors.id").first assert_equal [], author.special_nonexistent_post_comments end def test_eager_with_has_many_through_join_model_with_conditions - assert_equal Author.all.merge!(:includes => :hello_post_comments, - :order => "authors.id").first.hello_post_comments.sort_by(&:id), - Author.all.merge!(:order => "authors.id").first.hello_post_comments.sort_by(&:id) + assert_equal Author.all.merge!(includes: :hello_post_comments, + order: "authors.id").first.hello_post_comments.sort_by(&:id), + Author.all.merge!(order: "authors.id").first.hello_post_comments.sort_by(&:id) end def test_eager_with_has_many_through_join_model_with_conditions_on_top_level - assert_equal comments(:more_greetings), Author.all.merge!(:includes => :comments_with_order_and_conditions).find(authors(:david).id).comments_with_order_and_conditions.first + assert_equal comments(:more_greetings), Author.all.merge!(includes: :comments_with_order_and_conditions).find(authors(:david).id).comments_with_order_and_conditions.first end def test_eager_with_has_many_through_join_model_with_include - author_comments = Author.all.merge!(:includes => :comments_with_include).find(authors(:david).id).comments_with_include.to_a + author_comments = Author.all.merge!(includes: :comments_with_include).find(authors(:david).id).comments_with_include.to_a assert_no_queries do author_comments.first.post.title end @@ -544,7 +544,7 @@ def test_eager_with_has_many_through_join_model_with_include def test_eager_with_has_many_through_with_conditions_join_model_with_include post_tags = Post.find(posts(:welcome).id).misc_tags - eager_post_tags = Post.all.merge!(:includes => :misc_tags).find(1).misc_tags + eager_post_tags = Post.all.merge!(includes: :misc_tags).find(1).misc_tags assert_equal post_tags, eager_post_tags end @@ -555,19 +555,19 @@ def test_eager_with_has_many_through_join_model_ignores_default_includes end def test_eager_with_has_many_and_limit - posts = Post.all.merge!(:order => "posts.id asc", :includes => [ :author, :comments ], :limit => 2).to_a + posts = Post.all.merge!(order: "posts.id asc", includes: [ :author, :comments ], limit: 2).to_a assert_equal 2, posts.size assert_equal 3, posts.inject(0) { |sum, post| sum + post.comments.size } end def test_eager_with_has_many_and_limit_and_conditions - posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").to_a + posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, where: "posts.body = 'hello'", order: "posts.id").to_a assert_equal 2, posts.size assert_equal [4,5], posts.collect(&:id) end def test_eager_with_has_many_and_limit_and_conditions_array - posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", "hello" ], :order => "posts.id").to_a + posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, where: [ "posts.body = ?", "hello" ], order: "posts.id").to_a assert_equal 2, posts.size assert_equal [4,5], posts.collect(&:id) end @@ -581,34 +581,34 @@ def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers end def test_eager_with_has_many_and_limit_and_high_offset - posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { "authors.name" => "David" }).to_a + posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, offset: 10, where: { "authors.name" => "David" }).to_a assert_equal 0, posts.size end def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_conditions assert_queries(1) do posts = Post.references(:authors, :comments). - merge(:includes => [ :author, :comments ], :limit => 2, :offset => 10, - :where => [ "authors.name = ? and comments.body = ?", "David", "go crazy" ]).to_a + merge(includes: [ :author, :comments ], limit: 2, offset: 10, + where: [ "authors.name = ? and comments.body = ?", "David", "go crazy" ]).to_a assert_equal 0, posts.size end end def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_hash_conditions assert_queries(1) do - posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, - :where => { "authors.name" => "David", "comments.body" => "go crazy" }).to_a + posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, offset: 10, + where: { "authors.name" => "David", "comments.body" => "go crazy" }).to_a assert_equal 0, posts.size end end def test_count_eager_with_has_many_and_limit_and_high_offset - posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { "authors.name" => "David" }).count(:all) + posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, offset: 10, where: { "authors.name" => "David" }).count(:all) assert_equal 0, posts end def test_eager_with_has_many_and_limit_with_no_results - posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.title = 'magic forest'").to_a + posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, where: "posts.title = 'magic forest'").to_a assert_equal 0, posts.size end @@ -625,7 +625,7 @@ def test_eager_count_performed_on_a_has_many_through_association_with_multi_tabl end def test_eager_with_has_and_belongs_to_many_and_limit - posts = Post.all.merge!(:includes => :categories, :order => "posts.id", :limit => 3).to_a + posts = Post.all.merge!(includes: :categories, order: "posts.id", limit: 3).to_a assert_equal 3, posts.size assert_equal 2, posts[0].categories.size assert_equal 1, posts[1].categories.size @@ -691,7 +691,7 @@ def test_eager_with_has_many_and_limit_and_scoped_conditions_on_the_eagers end def test_eager_association_loading_with_habtm - posts = Post.all.merge!(:includes => :categories, :order => "posts.id").to_a + posts = Post.all.merge!(includes: :categories, order: "posts.id").to_a assert_equal 2, posts[0].categories.size assert_equal 1, posts[1].categories.size assert_equal 0, posts[2].categories.size @@ -700,23 +700,23 @@ def test_eager_association_loading_with_habtm end def test_eager_with_inheritance - SpecialPost.all.merge!(:includes => [ :comments ]).to_a + SpecialPost.all.merge!(includes: [ :comments ]).to_a end def test_eager_has_one_with_association_inheritance - post = Post.all.merge!(:includes => [ :very_special_comment ]).find(4) + post = Post.all.merge!(includes: [ :very_special_comment ]).find(4) assert_equal "VerySpecialComment", post.very_special_comment.class.to_s end def test_eager_has_many_with_association_inheritance - post = Post.all.merge!(:includes => [ :special_comments ]).find(4) + post = Post.all.merge!(includes: [ :special_comments ]).find(4) post.special_comments.each do |special_comment| assert special_comment.is_a?(SpecialComment) end end def test_eager_habtm_with_association_inheritance - post = Post.all.merge!(:includes => [ :special_categories ]).find(6) + post = Post.all.merge!(includes: [ :special_categories ]).find(6) assert_equal 1, post.special_categories.size post.special_categories.each do |special_category| assert_equal "SpecialCategory", special_category.class.to_s @@ -725,8 +725,8 @@ def test_eager_habtm_with_association_inheritance def test_eager_with_has_one_dependent_does_not_destroy_dependent assert_not_nil companies(:first_firm).account - f = Firm.all.merge!(:includes => :account, - :where => ["companies.name = ?", "37signals"]).first + f = Firm.all.merge!(includes: :account, + where: ["companies.name = ?", "37signals"]).first assert_not_nil f.account assert_equal companies(:first_firm, :reload).account, f.account end @@ -740,16 +740,16 @@ def test_eager_with_multi_table_conditional_properly_counts_the_records_when_usi def test_eager_with_invalid_association_reference assert_raise(ActiveRecord::AssociationNotFoundError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") { - Post.all.merge!(:includes=> :monkeys ).find(6) + Post.all.merge!(includes: :monkeys ).find(6) } assert_raise(ActiveRecord::AssociationNotFoundError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") { - Post.all.merge!(:includes=>[ :monkeys ]).find(6) + Post.all.merge!(includes: [ :monkeys ]).find(6) } assert_raise(ActiveRecord::AssociationNotFoundError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") { - Post.all.merge!(:includes=>[ "monkeys" ]).find(6) + Post.all.merge!(includes: [ "monkeys" ]).find(6) } assert_raise(ActiveRecord::AssociationNotFoundError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") { - Post.all.merge!(:includes=>[ :monkeys, :elephants ]).find(6) + Post.all.merge!(includes: [ :monkeys, :elephants ]).find(6) } end @@ -786,7 +786,7 @@ def test_eager_has_many_through_multiple_with_order end def test_eager_with_default_scope - developer = EagerDeveloperWithDefaultScope.where(:name => "David").first + developer = EagerDeveloperWithDefaultScope.where(name: "David").first projects = Project.order(:id).to_a assert_no_queries do assert_equal(projects, developer.projects) @@ -794,7 +794,7 @@ def test_eager_with_default_scope end def test_eager_with_default_scope_as_class_method - developer = EagerDeveloperWithClassMethodDefaultScope.where(:name => "David").first + developer = EagerDeveloperWithClassMethodDefaultScope.where(name: "David").first projects = Project.order(:id).to_a assert_no_queries do assert_equal(projects, developer.projects) @@ -819,7 +819,7 @@ def test_eager_with_default_scope_as_class_method_using_find_by_method end def test_eager_with_default_scope_as_lambda - developer = EagerDeveloperWithLambdaDefaultScope.where(:name => "David").first + developer = EagerDeveloperWithLambdaDefaultScope.where(name: "David").first projects = Project.order(:id).to_a assert_no_queries do assert_equal(projects, developer.projects) @@ -828,8 +828,8 @@ def test_eager_with_default_scope_as_lambda def test_eager_with_default_scope_as_block # warm up the habtm cache - EagerDeveloperWithBlockDefaultScope.where(:name => "David").first.projects - developer = EagerDeveloperWithBlockDefaultScope.where(:name => "David").first + EagerDeveloperWithBlockDefaultScope.where(name: "David").first.projects + developer = EagerDeveloperWithBlockDefaultScope.where(name: "David").first projects = Project.order(:id).to_a assert_no_queries do assert_equal(projects, developer.projects) @@ -837,7 +837,7 @@ def test_eager_with_default_scope_as_block end def test_eager_with_default_scope_as_callable - developer = EagerDeveloperWithCallableDefaultScope.where(:name => "David").first + developer = EagerDeveloperWithCallableDefaultScope.where(name: "David").first projects = Project.order(:id).to_a assert_no_queries do assert_equal(projects, developer.projects) @@ -845,22 +845,22 @@ def test_eager_with_default_scope_as_callable end def find_all_ordered(className, include=nil) - className.all.merge!(:order=>"#{className.table_name}.#{className.primary_key}", :includes=>include).to_a + className.all.merge!(order: "#{className.table_name}.#{className.primary_key}", includes: include).to_a end def test_limited_eager_with_order assert_equal( posts(:thinking, :sti_comments), Post.all.merge!( - :includes => [:author, :comments], :where => { "authors.name" => "David" }, - :order => "UPPER(posts.title)", :limit => 2, :offset => 1 + includes: [:author, :comments], where: { "authors.name" => "David" }, + order: "UPPER(posts.title)", limit: 2, offset: 1 ).to_a ) assert_equal( posts(:sti_post_and_comments, :sti_comments), Post.all.merge!( - :includes => [:author, :comments], :where => { "authors.name" => "David" }, - :order => "UPPER(posts.title) DESC", :limit => 2, :offset => 1 + includes: [:author, :comments], where: { "authors.name" => "David" }, + order: "UPPER(posts.title) DESC", limit: 2, offset: 1 ).to_a ) end @@ -869,15 +869,15 @@ def test_limited_eager_with_multiple_order_columns assert_equal( posts(:thinking, :sti_comments), Post.all.merge!( - :includes => [:author, :comments], :where => { "authors.name" => "David" }, - :order => ["UPPER(posts.title)", "posts.id"], :limit => 2, :offset => 1 + includes: [:author, :comments], where: { "authors.name" => "David" }, + order: ["UPPER(posts.title)", "posts.id"], limit: 2, offset: 1 ).to_a ) assert_equal( posts(:sti_post_and_comments, :sti_comments), Post.all.merge!( - :includes => [:author, :comments], :where => { "authors.name" => "David" }, - :order => ["UPPER(posts.title) DESC", "posts.id"], :limit => 2, :offset => 1 + includes: [:author, :comments], where: { "authors.name" => "David" }, + order: ["UPPER(posts.title) DESC", "posts.id"], limit: 2, offset: 1 ).to_a ) end @@ -886,17 +886,17 @@ def test_limited_eager_with_numeric_in_association assert_equal( people(:david, :susan), Person.references(:number1_fans_people).merge( - :includes => [:readers, :primary_contact, :number1_fan], - :where => "number1_fans_people.first_name like 'M%'", - :order => "people.id", :limit => 2, :offset => 0 + includes: [:readers, :primary_contact, :number1_fan], + where: "number1_fans_people.first_name like 'M%'", + order: "people.id", limit: 2, offset: 0 ).to_a ) end def test_polymorphic_type_condition - post = Post.all.merge!(:includes => :taggings).find(posts(:thinking).id) + post = Post.all.merge!(includes: :taggings).find(posts(:thinking).id) assert post.taggings.include?(taggings(:thinking_general)) - post = SpecialPost.all.merge!(:includes => :taggings).find(posts(:thinking).id) + post = SpecialPost.all.merge!(includes: :taggings).find(posts(:thinking).id) assert post.taggings.include?(taggings(:thinking_general)) end @@ -947,13 +947,13 @@ def test_eager_with_multiple_associations_with_same_table_belongs_to end end def test_eager_with_valid_association_as_string_not_symbol - assert_nothing_raised { Post.all.merge!(:includes => "comments").to_a } + assert_nothing_raised { Post.all.merge!(includes: "comments").to_a } end def test_eager_with_floating_point_numbers assert_queries(2) do # Before changes, the floating point numbers will be interpreted as table names and will cause this to run in one query - Comment.all.merge!(:where => "123.456 = 123.456", :includes => :post).to_a + Comment.all.merge!(where: "123.456 = 123.456", includes: :post).to_a end end @@ -1007,12 +1007,12 @@ def test_count_with_include def test_association_loading_notification notifications = messages_for("instantiation.active_record") do - Developer.all.merge!(:includes => "projects", :where => { "developers_projects.access_level" => 1 }, :limit => 5).to_a.size + Developer.all.merge!(includes: "projects", where: { "developers_projects.access_level" => 1 }, limit: 5).to_a.size end message = notifications.first payload = message.last - count = Developer.all.merge!(:includes => "projects", :where => { "developers_projects.access_level" => 1 }, :limit => 5).to_a.size + count = Developer.all.merge!(includes: "projects", where: { "developers_projects.access_level" => 1 }, limit: 5).to_a.size # eagerloaded row count should be greater than just developer count assert_operator payload[:record_count], :>, count @@ -1048,22 +1048,22 @@ def test_load_with_sti_sharing_association end def test_conditions_on_join_table_with_include_and_limit - assert_equal 3, Developer.all.merge!(:includes => "projects", :where => { "developers_projects.access_level" => 1 }, :limit => 5).to_a.size + assert_equal 3, Developer.all.merge!(includes: "projects", where: { "developers_projects.access_level" => 1 }, limit: 5).to_a.size end def test_dont_create_temporary_active_record_instances Developer.instance_count = 0 - developers = Developer.all.merge!(:includes => "projects", :where => { "developers_projects.access_level" => 1 }, :limit => 5).to_a + developers = Developer.all.merge!(includes: "projects", where: { "developers_projects.access_level" => 1 }, limit: 5).to_a assert_equal developers.count, Developer.instance_count end def test_order_on_join_table_with_include_and_limit - assert_equal 5, Developer.all.merge!(:includes => "projects", :order => "developers_projects.joined_on DESC", :limit => 5).to_a.size + assert_equal 5, Developer.all.merge!(includes: "projects", order: "developers_projects.joined_on DESC", limit: 5).to_a.size end def test_eager_loading_with_order_on_joined_table_preloads posts = assert_queries(2) do - Post.all.merge!(:joins => :comments, :includes => :author, :order => "comments.id DESC").to_a + Post.all.merge!(joins: :comments, includes: :author, order: "comments.id DESC").to_a end assert_equal posts(:eager_other), posts[1] assert_equal authors(:mary), assert_no_queries { posts[1].author} @@ -1071,32 +1071,32 @@ def test_eager_loading_with_order_on_joined_table_preloads def test_eager_loading_with_conditions_on_joined_table_preloads posts = assert_queries(2) do - Post.all.merge!(:select => "distinct posts.*", :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => "posts.id").to_a + Post.all.merge!(select: "distinct posts.*", includes: :author, joins: [:comments], where: "comments.body like 'Thank you%'", order: "posts.id").to_a end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} posts = assert_queries(2) do - Post.all.merge!(:select => "distinct posts.*", :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => "posts.id").to_a + Post.all.merge!(select: "distinct posts.*", includes: :author, joins: [:comments], where: "comments.body like 'Thank you%'", order: "posts.id").to_a end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} posts = assert_queries(2) do - Post.all.merge!(:includes => :author, :joins => {:taggings => :tag}, :where => "tags.name = 'General'", :order => "posts.id").to_a + Post.all.merge!(includes: :author, joins: {taggings: :tag}, where: "tags.name = 'General'", order: "posts.id").to_a end assert_equal posts(:welcome, :thinking), posts posts = assert_queries(2) do - Post.all.merge!(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => "posts.id").to_a + Post.all.merge!(includes: :author, joins: {taggings: {tag: :taggings}}, where: "taggings_tags.super_tag_id=2", order: "posts.id").to_a end assert_equal posts(:welcome, :thinking), posts end def test_preload_has_many_with_association_condition_and_default_scope - post = Post.create!(:title => "Beaches", :body => "I like beaches!") - Reader.create! :person => people(:david), :post => post - LazyReader.create! :person => people(:susan), :post => post + post = Post.create!(title: "Beaches", body: "I like beaches!") + Reader.create! person: people(:david), post: post + LazyReader.create! person: people(:susan), post: post assert_equal 1, post.lazy_readers.to_a.size assert_equal 2, post.lazy_readers_skimmers_or_not.to_a.size @@ -1107,13 +1107,13 @@ def test_preload_has_many_with_association_condition_and_default_scope def test_eager_loading_with_conditions_on_string_joined_table_preloads posts = assert_queries(2) do - Post.all.merge!(:select => "distinct posts.*", :includes => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :where => "comments.body like 'Thank you%'", :order => "posts.id").to_a + Post.all.merge!(select: "distinct posts.*", includes: :author, joins: "INNER JOIN comments on comments.post_id = posts.id", where: "comments.body like 'Thank you%'", order: "posts.id").to_a end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} posts = assert_queries(2) do - Post.all.merge!(:select => "distinct posts.*", :includes => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :where => "comments.body like 'Thank you%'", :order => "posts.id").to_a + Post.all.merge!(select: "distinct posts.*", includes: :author, joins: ["INNER JOIN comments on comments.post_id = posts.id"], where: "comments.body like 'Thank you%'", order: "posts.id").to_a end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} @@ -1121,7 +1121,7 @@ def test_eager_loading_with_conditions_on_string_joined_table_preloads def test_eager_loading_with_select_on_joined_table_preloads posts = assert_queries(2) do - Post.all.merge!(:select => "posts.*, authors.name as author_name", :includes => :comments, :joins => :author, :order => "posts.id").to_a + Post.all.merge!(select: "posts.*, authors.name as author_name", includes: :comments, joins: :author, order: "posts.id").to_a end assert_equal "David", posts[0].author_name assert_equal posts(:welcome).comments, assert_no_queries { posts[0].comments} @@ -1129,14 +1129,14 @@ def test_eager_loading_with_select_on_joined_table_preloads def test_eager_loading_with_conditions_on_join_model_preloads authors = assert_queries(2) do - Author.all.merge!(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").to_a + Author.all.merge!(includes: :author_address, joins: :comments, where: "posts.title like 'Welcome%'").to_a end assert_equal authors(:david), authors[0] assert_equal author_addresses(:david_address), authors[0].author_address end def test_preload_belongs_to_uses_exclusive_scope - people = Person.males.merge(:includes => :primary_contact).to_a + people = Person.males.merge(includes: :primary_contact).to_a assert_not_equal people.length, 0 people.each do |person| assert_no_queries {assert_not_nil person.primary_contact} @@ -1163,9 +1163,9 @@ def test_include_has_many_using_primary_key expected = Firm.find(1).clients_using_primary_key.sort_by(&:name) # Oracle adapter truncates alias to 30 characters if current_adapter?(:OracleAdapter) - firm = Firm.all.merge!(:includes => :clients_using_primary_key, :order => "clients_using_primary_keys_companies"[0,30]+".name").find(1) + firm = Firm.all.merge!(includes: :clients_using_primary_key, order: "clients_using_primary_keys_companies"[0,30]+".name").find(1) else - firm = Firm.all.merge!(:includes => :clients_using_primary_key, :order => "clients_using_primary_keys_companies.name").find(1) + firm = Firm.all.merge!(includes: :clients_using_primary_key, order: "clients_using_primary_keys_companies.name").find(1) end assert_no_queries do assert_equal expected, firm.clients_using_primary_key @@ -1174,7 +1174,7 @@ def test_include_has_many_using_primary_key def test_preload_has_one_using_primary_key expected = accounts(:signals37) - firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => "companies.id").first + firm = Firm.all.merge!(includes: :account_using_primary_key, order: "companies.id").first assert_no_queries do assert_equal expected, firm.account_using_primary_key end @@ -1182,35 +1182,35 @@ def test_preload_has_one_using_primary_key def test_include_has_one_using_primary_key expected = accounts(:signals37) - firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => "accounts.id").to_a.detect {|f| f.id == 1} + firm = Firm.all.merge!(includes: :account_using_primary_key, order: "accounts.id").to_a.detect {|f| f.id == 1} assert_no_queries do assert_equal expected, firm.account_using_primary_key end end def test_preloading_empty_belongs_to - c = Client.create!(:name => "Foo", :client_of => Company.maximum(:id) + 1) + c = Client.create!(name: "Foo", client_of: Company.maximum(:id) + 1) client = assert_queries(2) { Client.preload(:firm).find(c.id) } assert_no_queries { assert_nil client.firm } end def test_preloading_empty_belongs_to_polymorphic - t = Tagging.create!(:taggable_type => "Post", :taggable_id => Post.maximum(:id) + 1, :tag => tags(:general)) + t = Tagging.create!(taggable_type: "Post", taggable_id: Post.maximum(:id) + 1, tag: tags(:general)) tagging = assert_queries(2) { Tagging.preload(:taggable).find(t.id) } assert_no_queries { assert_nil tagging.taggable } end def test_preloading_through_empty_belongs_to - c = Client.create!(:name => "Foo", :client_of => Company.maximum(:id) + 1) + c = Client.create!(name: "Foo", client_of: Company.maximum(:id) + 1) client = assert_queries(2) { Client.preload(:accounts).find(c.id) } assert_no_queries { assert client.accounts.empty? } end def test_preloading_has_many_through_with_distinct - mary = Author.includes(:unique_categorized_posts).where(:id => authors(:mary).id).first + mary = Author.includes(:unique_categorized_posts).where(id: authors(:mary).id).first assert_equal 1, mary.unique_categorized_posts.length assert_equal 1, mary.unique_categorized_post_ids.length end @@ -1238,7 +1238,7 @@ def test_preloading_polymorphic_with_custom_foreign_type groucho = members(:groucho) sponsor = assert_queries(2) { - Sponsor.includes(:thing).where(:id => sponsor.id).first + Sponsor.includes(:thing).where(id: sponsor.id).first } assert_no_queries { assert_equal groucho, sponsor.thing } end @@ -1253,16 +1253,16 @@ def test_joins_with_includes_should_preload_via_joins def test_join_eager_with_empty_order_should_generate_valid_sql assert_nothing_raised do - Post.includes(:comments).order("").where(:comments => {:body => "Thank you for the welcome"}).first + Post.includes(:comments).order("").where(comments: {body: "Thank you for the welcome"}).first end end def test_deep_including_through_habtm # warm up habtm cache - posts = Post.all.merge!(:includes => {:categories => :categorizations}, :order => "posts.id").to_a + posts = Post.all.merge!(includes: {categories: :categorizations}, order: "posts.id").to_a posts[0].categories[0].categorizations.length - posts = Post.all.merge!(:includes => {:categories => :categorizations}, :order => "posts.id").to_a + posts = Post.all.merge!(includes: {categories: :categorizations}, order: "posts.id").to_a assert_no_queries { assert_equal 2, posts[0].categories[0].categorizations.length } assert_no_queries { assert_equal 1, posts[0].categories[1].categorizations.length } assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length } @@ -1279,12 +1279,12 @@ def test_eager_load_multiple_associations_with_references end test "scoping with a circular preload" do - assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) } + assert_equal Comment.find(1), Comment.preload(post: :comments).scoping { Comment.find(1) } end test "circular preload does not modify unscoped" do expected = FirstPost.unscoped.find(2) - FirstPost.preload(:comments => :first_post).find(1) + FirstPost.preload(comments: :first_post).find(1) assert_equal expected, FirstPost.unscoped.find(2) end diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index e274a0dc96..67931ed228 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -34,10 +34,10 @@ class ProjectWithAfterCreateHook < ActiveRecord::Base self.table_name = "projects" has_and_belongs_to_many :developers, - :class_name => "DeveloperForProjectWithAfterCreateHook", - :join_table => "developers_projects", - :foreign_key => "project_id", - :association_foreign_key => "developer_id" + class_name: "DeveloperForProjectWithAfterCreateHook", + join_table: "developers_projects", + foreign_key: "project_id", + association_foreign_key: "developer_id" after_create :add_david @@ -50,36 +50,36 @@ def add_david class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base self.table_name = "developers" has_and_belongs_to_many :projects, - :class_name => "ProjectWithAfterCreateHook", - :join_table => "developers_projects", - :association_foreign_key => "project_id", - :foreign_key => "developer_id" + class_name: "ProjectWithAfterCreateHook", + join_table: "developers_projects", + association_foreign_key: "project_id", + foreign_key: "developer_id" end class ProjectWithSymbolsForKeys < ActiveRecord::Base self.table_name = "projects" has_and_belongs_to_many :developers, - :class_name => "DeveloperWithSymbolsForKeys", - :join_table => :developers_projects, - :foreign_key => :project_id, - :association_foreign_key => "developer_id" + class_name: "DeveloperWithSymbolsForKeys", + join_table: :developers_projects, + foreign_key: :project_id, + association_foreign_key: "developer_id" end class DeveloperWithSymbolsForKeys < ActiveRecord::Base self.table_name = "developers" has_and_belongs_to_many :projects, - :class_name => "ProjectWithSymbolsForKeys", - :join_table => :developers_projects, - :association_foreign_key => :project_id, - :foreign_key => "developer_id" + class_name: "ProjectWithSymbolsForKeys", + join_table: :developers_projects, + association_foreign_key: :project_id, + foreign_key: "developer_id" end class SubDeveloper < Developer self.table_name = "developers" has_and_belongs_to_many :special_projects, - :join_table => "developers_projects", - :foreign_key => "project_id", - :association_foreign_key => "developer_id" + join_table: "developers_projects", + foreign_key: "project_id", + association_foreign_key: "developer_id" end class DeveloperWithSymbolClassName < Developer @@ -112,11 +112,11 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase def setup_data_for_habtm_case ActiveRecord::Base.connection.execute("delete from countries_treaties") - country = Country.new(:name => "India") + country = Country.new(name: "India") country.country_id = "c1" country.save! - treaty = Treaty.new(:name => "peace") + treaty = Treaty.new(name: "peace") treaty.treaty_id = "t1" country.treaties << treaty end @@ -148,11 +148,11 @@ def test_proper_usage_of_primary_keys_and_join_table end def test_join_table_composite_primary_key_should_not_warn - country = Country.new(:name => "India") + country = Country.new(name: "India") country.country_id = "c1" country.save! - treaty = Treaty.new(:name => "peace") + treaty = Treaty.new(name: "peace") treaty.treaty_id = "t1" warning = capture(:stderr) do country.treaties << treaty @@ -258,7 +258,7 @@ def test_habtm_adding_before_save def test_habtm_saving_multiple_relationships new_project = Project.new("name" => "Grimetime") amount_of_developers = 4 - developers = (0...amount_of_developers).collect {|i| Developer.create(:name => "JME #{i}") }.reverse + developers = (0...amount_of_developers).collect {|i| Developer.create(name: "JME #{i}") }.reverse new_project.developer_ids = [developers[0].id, developers[1].id] new_project.developers_with_callback_ids = [developers[2].id, developers[3].id] @@ -323,9 +323,9 @@ def test_new_aliased_to_build end def test_build_by_new_record - devel = Developer.new(:name => "Marcel", :salary => 75000) - devel.projects.build(:name => "Make bed") - proj2 = devel.projects.build(:name => "Lie in it") + devel = Developer.new(name: "Marcel", salary: 75000) + devel.projects.build(name: "Make bed") + proj2 = devel.projects.build(name: "Lie in it") assert_equal devel.projects.last, proj2 assert !proj2.persisted? devel.save @@ -348,9 +348,9 @@ def test_create end def test_create_by_new_record - devel = Developer.new(:name => "Marcel", :salary => 75000) - devel.projects.build(:name => "Make bed") - proj2 = devel.projects.build(:name => "Lie in it") + devel = Developer.new(name: "Marcel", salary: 75000) + devel.projects.build(name: "Make bed") + proj2 = devel.projects.build(name: "Lie in it") assert_equal devel.projects.last, proj2 assert !proj2.persisted? devel.save @@ -362,13 +362,13 @@ def test_create_by_new_record def test_creation_respects_hash_condition # in Oracle '' is saved as null therefore need to save ' ' in not null column - post = categories(:general).post_with_conditions.build(:body => " ") + post = categories(:general).post_with_conditions.build(body: " ") assert post.save assert_equal "Yet Another Testing Title", post.title # in Oracle '' is saved as null therefore need to save ' ' in not null column - another_post = categories(:general).post_with_conditions.create(:body => " ") + another_post = categories(:general).post_with_conditions.create(body: " ") assert another_post.persisted? assert_equal "Yet Another Testing Title", another_post.title @@ -563,7 +563,7 @@ def test_include_checks_if_record_exists_if_target_not_loaded def test_include_returns_false_for_non_matching_record_to_verify_scoping project = projects(:active_record) - developer = Developer.create :name => "Bryan", :salary => 50_000 + developer = Developer.create name: "Bryan", salary: 50_000 assert ! project.developers.loaded? assert ! project.developers.include?(developer) @@ -577,9 +577,9 @@ def test_find_with_merged_options def test_dynamic_find_should_respect_association_order # Developers are ordered 'name DESC, id DESC' - high_id_jamis = projects(:active_record).developers.create(:name => "Jamis") + high_id_jamis = projects(:active_record).developers.create(name: "Jamis") - assert_equal high_id_jamis, projects(:active_record).developers.merge(:where => "name = 'Jamis'").first + assert_equal high_id_jamis, projects(:active_record).developers.merge(where: "name = 'Jamis'").first assert_equal high_id_jamis, projects(:active_record).developers.find_by_name("Jamis") end @@ -596,7 +596,7 @@ def test_dynamic_find_all_should_respect_readonly_access def test_new_with_values_in_collection jamis = DeveloperForProjectWithAfterCreateHook.find_by_name("Jamis") david = DeveloperForProjectWithAfterCreateHook.find_by_name("David") - project = ProjectWithAfterCreateHook.new(:name => "Cooking with Bertie") + project = ProjectWithAfterCreateHook.new(name: "Cooking with Bertie") project.developers << jamis project.save! project.reload @@ -701,8 +701,8 @@ def test_join_table_alias assert_equal( 3, Developer.references(:developers_projects_join).merge( - :includes => {:projects => :developers}, - :where => "projects_developers_projects_join.joined_on IS NOT NULL" + includes: {projects: :developers}, + where: "projects_developers_projects_join.joined_on IS NOT NULL" ).to_a.size ) end @@ -721,15 +721,15 @@ def test_join_with_group assert_equal( 3, Developer.references(:developers_projects_join).merge( - :includes => {:projects => :developers}, :where => "projects_developers_projects_join.joined_on IS NOT NULL", - :group => group.join(",") + includes: {projects: :developers}, where: "projects_developers_projects_join.joined_on IS NOT NULL", + group: group.join(",") ).to_a.size ) end def test_find_grouped - all_posts_from_category1 = Post.all.merge!(:where => "category_id = 1", :joins => :categories).to_a - grouped_posts_of_category1 = Post.all.merge!(:where => "category_id = 1", :group => "author_id", :select => "count(posts.id) as posts_count", :joins => :categories).to_a + all_posts_from_category1 = Post.all.merge!(where: "category_id = 1", joins: :categories).to_a + grouped_posts_of_category1 = Post.all.merge!(where: "category_id = 1", group: "author_id", select: "count(posts.id) as posts_count", joins: :categories).to_a assert_equal 5, all_posts_from_category1.size assert_equal 2, grouped_posts_of_category1.size end @@ -796,8 +796,8 @@ def test_has_many_through_polymorphic_has_manys_works end def test_symbols_as_keys - developer = DeveloperWithSymbolsForKeys.new(:name => "David") - project = ProjectWithSymbolsForKeys.new(:name => "Rails Testing") + developer = DeveloperWithSymbolsForKeys.new(name: "David") + project = ProjectWithSymbolsForKeys.new(name: "Rails Testing") project.developers << developer project.save! @@ -842,12 +842,12 @@ def test_caching_of_columns end def test_attributes_are_being_set_when_initialized_from_habtm_association_with_where_clause - new_developer = projects(:action_controller).developers.where(:name => "Marcelo").build + new_developer = projects(:action_controller).developers.where(name: "Marcelo").build assert_equal new_developer.name, "Marcelo" end def test_attributes_are_being_set_when_initialized_from_habtm_association_with_multiple_where_clauses - new_developer = projects(:action_controller).developers.where(:name => "Marcelo").where(:salary => 90_000).build + new_developer = projects(:action_controller).developers.where(name: "Marcelo").where(salary: 90_000).build assert_equal new_developer.name, "Marcelo" assert_equal new_developer.salary, 90_000 end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index c8901a29d3..b513c40f48 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -65,7 +65,7 @@ def test_custom_primary_key_on_new_record_should_fetch_with_query end def test_association_primary_key_on_new_record_should_fetch_with_query - author = Author.new(:name => "David") + author = Author.new(name: "David") assert !author.essays.loaded? assert_queries 1 do @@ -121,9 +121,9 @@ def test_anonymous_has_many developer_project = Class.new(ActiveRecord::Base) { self.table_name = "developers_projects" - belongs_to :developer, :anonymous_class => dev + belongs_to :developer, anonymous_class: dev } - has_many :developer_projects, :anonymous_class => developer_project, :foreign_key => "developer_id" + has_many :developer_projects, anonymous_class: developer_project, foreign_key: "developer_id" } dev = developer.first named = Developer.find(dev.id) @@ -142,13 +142,13 @@ def test_default_scope_on_relations_is_not_cached comments = Class.new(ActiveRecord::Base) { self.table_name = "comments" self.inheritance_column = "not_there" - belongs_to :post, :anonymous_class => post + belongs_to :post, anonymous_class: post default_scope -> { counter += 1 - where("id = :inc", :inc => counter) + where("id = :inc", inc: counter) } } - has_many :comments, :anonymous_class => comments, :foreign_key => "post_id" + has_many :comments, anonymous_class: comments, foreign_key: "post_id" } assert_equal 0, counter post = posts.first @@ -192,7 +192,7 @@ def test_clear_collection_should_not_change_updated_at end def test_create_from_association_should_respect_default_scope - car = Car.create(:name => "honda") + car = Car.create(name: "honda") assert_equal "honda", car.name bulb = Bulb.create @@ -229,7 +229,7 @@ def test_build_from_association_should_respect_scope end def test_create_from_association_with_nil_values_should_work - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb = car.bulbs.new(nil) assert_equal "defaulty", bulb.name @@ -242,7 +242,7 @@ def test_create_from_association_with_nil_values_should_work end def test_do_not_call_callbacks_for_delete_all - car = Car.create(:name => "honda") + car = Car.create(name: "honda") car.funky_bulbs.create! assert_equal 1, car.funky_bulbs.count assert_nothing_raised { car.reload.funky_bulbs.delete_all } @@ -251,11 +251,11 @@ def test_do_not_call_callbacks_for_delete_all def test_delete_all_on_association_is_the_same_as_not_loaded author = authors :david - author.thinking_posts.create!(:body => "test") + author.thinking_posts.create!(body: "test") author.reload expected_sql = capture_sql { author.thinking_posts.delete_all } - author.thinking_posts.create!(:body => "test") + author.thinking_posts.create!(body: "test") author.reload author.thinking_posts.inspect loaded_sql = capture_sql { author.thinking_posts.delete_all } @@ -264,11 +264,11 @@ def test_delete_all_on_association_is_the_same_as_not_loaded def test_delete_all_on_association_with_nil_dependency_is_the_same_as_not_loaded author = authors :david - author.posts.create!(:title => "test", :body => "body") + author.posts.create!(title: "test", body: "body") author.reload expected_sql = capture_sql { author.posts.delete_all } - author.posts.create!(:title => "test", :body => "body") + author.posts.create!(title: "test", body: "body") author.reload author.posts.to_a loaded_sql = capture_sql { author.posts.delete_all } @@ -283,24 +283,24 @@ def test_building_the_associated_object_with_implicit_sti_base_class def test_building_the_associated_object_with_explicit_sti_base_class firm = DependentFirm.new - company = firm.companies.build(:type => "Company") + company = firm.companies.build(type: "Company") assert_kind_of Company, company, "Expected #{company.class} to be a Company" end def test_building_the_associated_object_with_sti_subclass firm = DependentFirm.new - company = firm.companies.build(:type => "Client") + company = firm.companies.build(type: "Client") assert_kind_of Client, company, "Expected #{company.class} to be a Client" end def test_building_the_associated_object_with_an_invalid_type firm = DependentFirm.new - assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(:type => "Invalid") } + assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Invalid") } end def test_building_the_associated_object_with_an_unrelated_type firm = DependentFirm.new - assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(:type => "Account") } + assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Account") } end test "building the association with an array" do @@ -314,24 +314,24 @@ def test_building_the_associated_object_with_an_unrelated_type end def test_association_keys_bypass_attribute_protection - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb = car.bulbs.new assert_equal car.id, bulb.car_id - bulb = car.bulbs.new :car_id => car.id + 1 + bulb = car.bulbs.new car_id: car.id + 1 assert_equal car.id, bulb.car_id bulb = car.bulbs.build assert_equal car.id, bulb.car_id - bulb = car.bulbs.build :car_id => car.id + 1 + bulb = car.bulbs.build car_id: car.id + 1 assert_equal car.id, bulb.car_id bulb = car.bulbs.create assert_equal car.id, bulb.car_id - bulb = car.bulbs.create :car_id => car.id + 1 + bulb = car.bulbs.create car_id: car.id + 1 assert_equal car.id, bulb.car_id end @@ -341,19 +341,19 @@ def test_association_protect_foreign_key line_item = invoice.line_items.new assert_equal invoice.id, line_item.invoice_id - line_item = invoice.line_items.new :invoice_id => invoice.id + 1 + line_item = invoice.line_items.new invoice_id: invoice.id + 1 assert_equal invoice.id, line_item.invoice_id line_item = invoice.line_items.build assert_equal invoice.id, line_item.invoice_id - line_item = invoice.line_items.build :invoice_id => invoice.id + 1 + line_item = invoice.line_items.build invoice_id: invoice.id + 1 assert_equal invoice.id, line_item.invoice_id line_item = invoice.line_items.create assert_equal invoice.id, line_item.invoice_id - line_item = invoice.line_items.create :invoice_id => invoice.id + 1 + line_item = invoice.line_items.create invoice_id: invoice.id + 1 assert_equal invoice.id, line_item.invoice_id end @@ -374,7 +374,7 @@ def test_build_and_create_should_not_happen_within_scope end def test_no_sql_should_be_fired_if_association_already_loaded - Car.create(:name => "honda") + Car.create(name: "honda") bulbs = Car.first.bulbs bulbs.to_a # to load all instances of bulbs @@ -425,13 +425,13 @@ def test_no_sql_should_be_fired_if_association_already_loaded end def test_create_resets_cached_counters - person = Person.create!(:first_name => "tenderlove") + person = Person.create!(first_name: "tenderlove") post = Post.first assert_equal [], person.readers assert_nil person.readers.find_by_post_id(post.id) - person.readers.create(:post_id => post.id) + person.readers.create(post_id: post.id) assert_equal 1, person.readers.count assert_equal 1, person.readers.length @@ -461,19 +461,19 @@ def test_exists_respects_association_scope # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first def test_counting_with_counter_sql - assert_equal 3, Firm.all.merge!(:order => "id").first.clients.count + assert_equal 3, Firm.all.merge!(order: "id").first.clients.count end def test_counting - assert_equal 3, Firm.all.merge!(:order => "id").first.plain_clients.count + assert_equal 3, Firm.all.merge!(order: "id").first.plain_clients.count end def test_counting_with_single_hash - assert_equal 1, Firm.all.merge!(:order => "id").first.plain_clients.where(:name => "Microsoft").count + assert_equal 1, Firm.all.merge!(order: "id").first.plain_clients.where(name: "Microsoft").count end def test_counting_with_column_name_and_hash - assert_equal 3, Firm.all.merge!(:order => "id").first.plain_clients.count(:name) + assert_equal 3, Firm.all.merge!(order: "id").first.plain_clients.count(:name) end def test_counting_with_association_limit @@ -483,7 +483,7 @@ def test_counting_with_association_limit end def test_finding - assert_equal 3, Firm.all.merge!(:order => "id").first.clients.length + assert_equal 3, Firm.all.merge!(order: "id").first.clients.length end def test_finding_array_compatibility @@ -551,27 +551,27 @@ def test_cant_save_has_many_readonly_association end def test_finding_default_orders - assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients.first.name + assert_equal "Summit", Firm.all.merge!(order: "id").first.clients.first.name end def test_finding_with_different_class_name_and_order - assert_equal "Apex", Firm.all.merge!(:order => "id").first.clients_sorted_desc.first.name + assert_equal "Apex", Firm.all.merge!(order: "id").first.clients_sorted_desc.first.name end def test_finding_with_foreign_key - assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_of_firm.first.name + assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_of_firm.first.name end def test_finding_with_condition - assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms.first.name + assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_like_ms.first.name end def test_finding_with_condition_hash - assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms_with_hash_conditions.first.name + assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_like_ms_with_hash_conditions.first.name end def test_finding_using_primary_key - assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients_using_primary_key.first.name + assert_equal "Summit", Firm.all.merge!(order: "id").first.clients_using_primary_key.first.name end def test_update_all_on_association_accessed_before_save @@ -599,7 +599,7 @@ def test_belongs_to_sanity end def test_find_ids - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find } @@ -633,7 +633,7 @@ def test_find_ids_and_inverse_of end def test_find_all - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first assert_equal 3, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length end @@ -644,7 +644,7 @@ def test_find_each assert ! firm.clients.loaded? assert_queries(4) do - firm.clients.find_each(:batch_size => 1) {|c| assert_equal firm.id, c.firm_id } + firm.clients.find_each(batch_size: 1) {|c| assert_equal firm.id, c.firm_id } end assert ! firm.clients.loaded? @@ -669,7 +669,7 @@ def test_find_in_batches assert ! firm.clients.loaded? assert_queries(2) do - firm.clients.find_in_batches(:batch_size => 2) do |clients| + firm.clients.find_in_batches(batch_size: 2) do |clients| clients.each {|c| assert_equal firm.id, c.firm_id } end end @@ -679,29 +679,29 @@ def test_find_in_batches def test_find_all_sanitized # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first summit = firm.clients.where("name = 'Summit'").to_a assert_equal summit, firm.clients.where("name = ?", "Summit").to_a - assert_equal summit, firm.clients.where("name = :name", { :name => "Summit" }).to_a + assert_equal summit, firm.clients.where("name = :name", { name: "Summit" }).to_a end def test_find_first - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first client2 = Client.find(2) assert_equal firm.clients.first, firm.clients.order("id").first assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first end def test_find_first_sanitized - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first client2 = Client.find(2) - assert_equal client2, firm.clients.merge!(:where => ["#{QUOTED_TYPE} = ?", "Client"], :order => "id").first - assert_equal client2, firm.clients.merge!(:where => ["#{QUOTED_TYPE} = :type", { :type => "Client" }], :order => "id").first + assert_equal client2, firm.clients.merge!(where: ["#{QUOTED_TYPE} = ?", "Client"], order: "id").first + assert_equal client2, firm.clients.merge!(where: ["#{QUOTED_TYPE} = :type", { type: "Client" }], order: "id").first end def test_find_all_with_include_and_conditions assert_nothing_raised do - Developer.all.merge!(:joins => :audit_logs, :where => {"audit_logs.message" => nil, :name => "Smith"}).to_a + Developer.all.merge!(joins: :audit_logs, where: {"audit_logs.message" => nil, :name => "Smith"}).to_a end end @@ -711,8 +711,8 @@ def test_find_in_collection end def test_find_grouped - all_clients_of_firm1 = Client.all.merge!(:where => "firm_id = 1").to_a - grouped_clients_of_firm1 = Client.all.merge!(:where => "firm_id = 1", :group => "firm_id", :select => "firm_id, count(id) as clients_count").to_a + all_clients_of_firm1 = Client.all.merge!(where: "firm_id = 1").to_a + grouped_clients_of_firm1 = Client.all.merge!(where: "firm_id = 1", group: "firm_id", select: "firm_id, count(id) as clients_count").to_a assert_equal 3, all_clients_of_firm1.size assert_equal 1, grouped_clients_of_firm1.size end @@ -760,7 +760,7 @@ def test_adding def test_adding_using_create first_firm = companies(:first_firm) assert_equal 3, first_firm.plain_clients.size - first_firm.plain_clients.create(:name => "Natural Company") + first_firm.plain_clients.create(name: "Natural Company") assert_equal 4, first_firm.plain_clients.length assert_equal 4, first_firm.plain_clients.size end @@ -768,7 +768,7 @@ def test_adding_using_create def test_create_with_bang_on_has_many_when_parent_is_new_raises error = assert_raise(ActiveRecord::RecordNotSaved) do firm = Firm.new - firm.plain_clients.create! :name=>"Whoever" + firm.plain_clients.create! name: "Whoever" end assert_equal "You cannot call create unless the parent is saved", error.message @@ -777,7 +777,7 @@ def test_create_with_bang_on_has_many_when_parent_is_new_raises def test_regular_create_on_has_many_when_parent_is_new_raises error = assert_raise(ActiveRecord::RecordNotSaved) do firm = Firm.new - firm.plain_clients.create :name=>"Whoever" + firm.plain_clients.create name: "Whoever" end assert_equal "You cannot call create unless the parent is saved", error.message @@ -785,7 +785,7 @@ def test_regular_create_on_has_many_when_parent_is_new_raises def test_create_with_bang_on_has_many_raises_when_record_not_saved assert_raise(ActiveRecord::RecordInvalid) do - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first firm.plain_clients.create! end end @@ -815,8 +815,8 @@ def test_adding_a_collection end def test_transactions_when_adding_to_persisted - good = Client.new(:name => "Good") - bad = Client.new(:name => "Bad", :raise_on_save => true) + good = Client.new(name: "Good") + bad = Client.new(name: "Bad", raise_on_save: true) begin companies(:first_firm).clients_of_firm.concat(good, bad) @@ -905,7 +905,7 @@ def test_build_without_loading_association assert_equal 1, first_topic.replies.length assert_no_queries do - first_topic.replies.build(:title => "Not saved", :content => "Superstars") + first_topic.replies.build(title: "Not saved", content: "Superstars") assert_equal 2, first_topic.replies.size end @@ -944,7 +944,7 @@ def test_create_without_loading_association first_firm.clients_of_firm.reset assert_queries(1) do - first_firm.clients_of_firm.create(:name => "Superstars") + first_firm.clients_of_firm.create(name: "Superstars") end assert_equal 3, first_firm.clients_of_firm.size @@ -1104,10 +1104,10 @@ def test_calling_update_attributes_on_id_changes_the_counter_cache assert_equal original_count, topic.replies_count first_reply = topic.replies.first - first_reply.update_attributes(:parent_id => nil) + first_reply.update_attributes(parent_id: nil) assert_equal original_count - 1, topic.reload.replies_count - first_reply.update_attributes(:parent_id => topic.id) + first_reply.update_attributes(parent_id: topic.id) assert_equal original_count, topic.reload.replies_count end @@ -1120,11 +1120,11 @@ def test_calling_update_attributes_changing_ids_doesnt_change_counter_cache reply1 = topic1.replies.first reply2 = topic2.replies.first - reply1.update_attributes(:parent_id => topic2.id) + reply1.update_attributes(parent_id: topic2.id) assert_equal original_count1 - 1, topic1.reload.replies_count assert_equal original_count2 + 1, topic2.reload.replies_count - reply2.update_attributes(:parent_id => topic1.id) + reply2.update_attributes(parent_id: topic1.id) assert_equal original_count1, topic1.reload.replies_count assert_equal original_count2, topic2.reload.replies_count end @@ -1169,8 +1169,8 @@ def test_delete_all_with_not_yet_loaded_association_collection end def test_transaction_when_deleting_persisted - good = Client.new(:name => "Good") - bad = Client.new(:name => "Bad", :raise_on_destroy => true) + good = Client.new(name: "Good") + bad = Client.new(name: "Bad", raise_on_destroy: true) companies(:first_firm).clients_of_firm = [good, bad] @@ -1278,8 +1278,8 @@ def test_clearing_an_exclusively_dependent_association_collection def test_dependent_association_respects_optional_conditions_on_delete firm = companies(:odegy) - Client.create(:client_of => firm.id, :name => "BigShot Inc.") - Client.create(:client_of => firm.id, :name => "SmallTime Inc.") + Client.create(client_of: firm.id, name: "BigShot Inc.") + Client.create(client_of: firm.id, name: "SmallTime Inc.") # only one of two clients is included in the association due to the :conditions key assert_equal 2, Client.where(client_of: firm.id).size assert_equal 1, firm.dependent_conditional_clients_of_firm.size @@ -1290,8 +1290,8 @@ def test_dependent_association_respects_optional_conditions_on_delete def test_dependent_association_respects_optional_sanitized_conditions_on_delete firm = companies(:odegy) - Client.create(:client_of => firm.id, :name => "BigShot Inc.") - Client.create(:client_of => firm.id, :name => "SmallTime Inc.") + Client.create(client_of: firm.id, name: "BigShot Inc.") + Client.create(client_of: firm.id, name: "SmallTime Inc.") # only one of two clients is included in the association due to the :conditions key assert_equal 2, Client.where(client_of: firm.id).size assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size @@ -1302,8 +1302,8 @@ def test_dependent_association_respects_optional_sanitized_conditions_on_delete def test_dependent_association_respects_optional_hash_conditions_on_delete firm = companies(:odegy) - Client.create(:client_of => firm.id, :name => "BigShot Inc.") - Client.create(:client_of => firm.id, :name => "SmallTime Inc.") + Client.create(client_of: firm.id, name: "BigShot Inc.") + Client.create(client_of: firm.id, name: "SmallTime Inc.") # only one of two clients is included in the association due to the :conditions key assert_equal 2, Client.where(client_of: firm.id).size assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size @@ -1457,7 +1457,7 @@ def test_dependence firm = companies(:first_firm) assert_equal 3, firm.clients.size firm.destroy - assert Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.empty? + assert Client.all.merge!(where: "firm_id=#{firm.id}").to_a.empty? end def test_dependence_for_associations_with_hash_condition @@ -1467,7 +1467,7 @@ def test_dependence_for_associations_with_hash_condition def test_destroy_dependent_when_deleted_from_association # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first assert_equal 3, firm.clients.size client = firm.clients.first @@ -1494,7 +1494,7 @@ def test_dependence_with_transaction_support_on_failure firm.destroy rescue "do nothing" - assert_equal 3, Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.size + assert_equal 3, Client.all.merge!(where: "firm_id=#{firm.id}").to_a.size end def test_dependence_on_account @@ -1518,13 +1518,13 @@ def test_depends_and_nullify end def test_restrict_with_exception - firm = RestrictedWithExceptionFirm.create!(:name => "restrict") - firm.companies.create(:name => "child") + firm = RestrictedWithExceptionFirm.create!(name: "restrict") + firm.companies.create(name: "child") assert !firm.companies.empty? assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy } - assert RestrictedWithExceptionFirm.exists?(:name => "restrict") - assert firm.companies.exists?(:name => "child") + assert RestrictedWithExceptionFirm.exists?(name: "restrict") + assert firm.companies.exists?(name: "child") end def test_restrict_with_error_is_deprecated_using_key_many @@ -1548,8 +1548,8 @@ def test_restrict_with_error_is_deprecated_using_key_many end def test_restrict_with_error - firm = RestrictedWithErrorFirm.create!(:name => "restrict") - firm.companies.create(:name => "child") + firm = RestrictedWithErrorFirm.create!(name: "restrict") + firm.companies.create(name: "child") assert !firm.companies.empty? @@ -1558,8 +1558,8 @@ def test_restrict_with_error assert !firm.errors.empty? assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first - assert RestrictedWithErrorFirm.exists?(:name => "restrict") - assert firm.companies.exists?(:name => "child") + assert RestrictedWithErrorFirm.exists?(name: "restrict") + assert firm.companies.exists?(name: "child") end def test_restrict_with_error_with_locale @@ -1586,7 +1586,7 @@ def test_included_in_collection end def test_included_in_collection_for_new_records - client = Client.create(:name => "Persisted") + client = Client.create(name: "Persisted") assert_nil client.client_of assert_equal false, Firm.new.clients_of_firm.include?(client), "includes a client that does not belong to any firm" @@ -1597,7 +1597,7 @@ def test_adding_array_and_collection end def test_replace_with_less - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first firm.clients = [companies(:first_client)] assert firm.save, "Could not save firm" firm.reload @@ -1611,7 +1611,7 @@ def test_replace_with_less_and_dependent_nullify end def test_replace_with_new - firm = Firm.all.merge!(:order => "id").first + firm = Firm.all.merge!(order: "id").first firm.clients = [companies(:second_client), Client.new("name" => "New Client")] firm.save firm.reload @@ -1648,8 +1648,8 @@ def test_replace_with_same_content end def test_transactions_when_replacing_on_persisted - good = Client.new(:name => "Good") - bad = Client.new(:name => "Bad", :raise_on_save => true) + good = Client.new(name: "Good") + bad = Client.new(name: "Bad", raise_on_save: true) companies(:first_firm).clients_of_firm = [good] @@ -1712,7 +1712,7 @@ def test_set_ids_for_association_on_new_record_applies_association_correctly contract_a = Contract.create! contract_b = Contract.create! Contract.create! # another contract - company = Company.new(:name => "Some Company") + company = Company.new(name: "Some Company") company.contract_ids = [contract_a.id, contract_b.id] assert_equal [contract_a.id, contract_b.id], company.contract_ids @@ -1724,7 +1724,7 @@ def test_set_ids_for_association_on_new_record_applies_association_correctly end def test_assign_ids_ignoring_blanks - firm = Firm.create!(:name => "Apple") + firm = Firm.create!(name: "Apple") firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, ""] firm.save! @@ -1740,7 +1740,7 @@ def test_modifying_a_through_a_has_many_should_raise [ lambda { authors(:mary).comment_ids = [comments(:greetings).id, comments(:more_greetings).id] }, lambda { authors(:mary).comments = [comments(:greetings), comments(:more_greetings)] }, - lambda { authors(:mary).comments << Comment.create!(:body => "Yay", :post_id => 424242) }, + lambda { authors(:mary).comments << Comment.create!(body: "Yay", post_id: 424242) }, lambda { authors(:mary).comments.delete(authors(:mary).comments.first) }, ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) } end @@ -1781,7 +1781,7 @@ def test_include_checks_if_record_exists_if_target_not_loaded def test_include_returns_false_for_non_matching_record_to_verify_scoping firm = companies(:first_firm) - client = Client.create!(:name => "Not Associated") + client = Client.create!(name: "Not Associated") assert ! firm.clients.loaded? assert_equal false, firm.clients.include?(client) @@ -1810,7 +1810,7 @@ def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query def test_calling_first_or_last_on_existing_record_with_build_should_load_association firm = companies(:first_firm) - firm.clients.build(:name => "Foo") + firm.clients.build(name: "Foo") assert !firm.clients.loaded? assert_queries 1 do @@ -1824,7 +1824,7 @@ def test_calling_first_or_last_on_existing_record_with_build_should_load_associa def test_calling_first_nth_or_last_on_existing_record_with_create_should_not_load_association firm = companies(:first_firm) - firm.clients.create(:name => "Foo") + firm.clients.create(name: "Foo") assert !firm.clients.loaded? assert_queries 3 do @@ -1848,7 +1848,7 @@ def test_calling_first_nth_or_last_on_new_record_should_not_run_queries def test_calling_first_or_last_with_integer_on_association_should_not_load_association firm = companies(:first_firm) - firm.clients.create(:name => "Foo") + firm.clients.create(name: "Foo") assert !firm.clients.loaded? assert_queries 2 do @@ -1978,13 +1978,13 @@ def test_joins_with_namespaced_model_should_use_correct_type old = ActiveRecord::Base.store_full_sti_class ActiveRecord::Base.store_full_sti_class = true - firm = Namespaced::Firm.create({ :name => "Some Company" }) - firm.clients.create({ :name => "Some Client" }) + firm = Namespaced::Firm.create({ name: "Some Company" }) + firm.clients.create({ name: "Some Client" }) stats = Namespaced::Firm.all.merge!( - :select => "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients", - :joins => :clients, - :group => "#{Namespaced::Firm.table_name}.id" + select: "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients", + joins: :clients, + group: "#{Namespaced::Firm.table_name}.id" ).find firm.id assert_equal 1, stats.num_clients.to_i ensure @@ -2010,8 +2010,8 @@ def test_respond_to_private_class_methods end def test_creating_using_primary_key - firm = Firm.all.merge!(:order => "id").first - client = firm.clients_using_primary_key.create!(:name => "test") + firm = Firm.all.merge!(order: "id").first + client = firm.clients_using_primary_key.create!(name: "test") assert_equal firm.name, client.firm_name end @@ -2034,12 +2034,12 @@ class NullifyModel < ActiveRecord::Base end def test_attributes_are_being_set_when_initialized_from_has_many_association_with_where_clause - new_comment = posts(:welcome).comments.where(:body => "Some content").build + new_comment = posts(:welcome).comments.where(body: "Some content").build assert_equal new_comment.body, "Some content" end def test_attributes_are_being_set_when_initialized_from_has_many_association_with_multiple_where_clauses - new_comment = posts(:welcome).comments.where(:body => "Some content").where(:type => "SpecialComment").build + new_comment = posts(:welcome).comments.where(body: "Some content").where(type: "SpecialComment").build assert_equal new_comment.body, "Some content" assert_equal new_comment.type, "SpecialComment" assert_equal new_comment.post_id, posts(:welcome).id @@ -2053,7 +2053,7 @@ def test_include_method_in_has_many_association_should_return_true_for_instance_ def test_load_target_respects_protected_attributes topic = Topic.create! - reply = topic.replies.create(:title => "reply 1") + reply = topic.replies.create(title: "reply 1") reply.approved = false reply.save! @@ -2080,7 +2080,7 @@ def test_to_a_should_dup_target end def test_merging_with_custom_attribute_writer - bulb = Bulb.new(:color => "red") + bulb = Bulb.new(color: "red") assert_equal "RED!", bulb.color car = Car.create! @@ -2090,13 +2090,13 @@ def test_merging_with_custom_attribute_writer end def test_abstract_class_with_polymorphic_has_many - post = SubStiPost.create! :title => "fooo", :body => "baa" - tagging = Tagging.create! :taggable => post + post = SubStiPost.create! title: "fooo", body: "baa" + tagging = Tagging.create! taggable: post assert_equal [tagging], post.taggings end def test_with_polymorphic_has_many_with_custom_columns_name - post = Post.create! :title => "foo", :body => "bar" + post = Post.create! title: "foo", body: "bar" image = Image.create! post.images << image @@ -2106,7 +2106,7 @@ def test_with_polymorphic_has_many_with_custom_columns_name def test_build_with_polymorphic_has_many_does_not_allow_to_override_type_and_id welcome = posts(:welcome) - tagging = welcome.taggings.build(:taggable_id => 99, :taggable_type => "ShouldNotChange") + tagging = welcome.taggings.build(taggable_id: 99, taggable_type: "ShouldNotChange") assert_equal welcome.id, tagging.taggable_id assert_equal "Post", tagging.taggable_type @@ -2121,7 +2121,7 @@ def test_dont_call_save_callbacks_twice_on_has_many end def test_association_attributes_are_available_to_after_initialize - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb = car.bulbs.build assert_equal car.id, bulb.attributes_after_initialize["car_id"] @@ -2144,7 +2144,7 @@ def test_attributes_are_set_when_initialized_from_polymorphic_has_many_null_rela end def test_replace - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb1 = car.bulbs.create bulb2 = Bulb.create @@ -2155,7 +2155,7 @@ def test_replace end def test_replace_returns_target - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb1 = car.bulbs.create bulb2 = car.bulbs.create bulb3 = Bulb.create diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index f6c723aebd..90004eb70f 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -37,8 +37,8 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase # Dummies to force column loads so query counts are clean. def setup - Person.create :first_name => "gummy" - Reader.create :person_id => 0, :post_id => 0 + Person.create first_name: "gummy" + Reader.create person_id: 0, post_id: 0 end def test_preload_sti_rhs_class @@ -70,7 +70,7 @@ def test_ordered_has_many_through def self.name; "Person"; end has_many :readers - has_many :posts, -> { order("posts.id DESC") }, :through => :readers + has_many :posts, -> { order("posts.id DESC") }, through: :readers end posts = person_prime.includes(:posts).first.posts @@ -106,8 +106,8 @@ def test_singleton_has_many_through def test_no_pk_join_table_append lesson, _, student = make_no_pk_hm_t - sicp = lesson.new(:name => "SICP") - ben = student.new(:name => "Ben Bitdiddle") + sicp = lesson.new(name: "SICP") + ben = student.new(name: "Ben Bitdiddle") sicp.students << ben assert sicp.save! end @@ -115,9 +115,9 @@ def test_no_pk_join_table_append def test_no_pk_join_table_delete lesson, lesson_student, student = make_no_pk_hm_t - sicp = lesson.new(:name => "SICP") - ben = student.new(:name => "Ben Bitdiddle") - louis = student.new(:name => "Louis Reasoner") + sicp = lesson.new(name: "SICP") + ben = student.new(name: "Ben Bitdiddle") + louis = student.new(name: "Louis Reasoner") sicp.students << ben sicp.students << louis assert sicp.save! @@ -139,8 +139,8 @@ def test_no_pk_join_model_callbacks after_destroy_called = true end - sicp = lesson.new(:name => "SICP") - ben = student.new(:name => "Ben Bitdiddle") + sicp = lesson.new(name: "SICP") + ben = student.new(name: "Ben Bitdiddle") sicp.students << ben assert sicp.save! @@ -156,10 +156,10 @@ def make_no_pk_hm_t lesson_student = make_model "LessonStudent" lesson_student.table_name = "lessons_students" - lesson_student.belongs_to :lesson, :anonymous_class => lesson - lesson_student.belongs_to :student, :anonymous_class => student - lesson.has_many :lesson_students, :anonymous_class => lesson_student - lesson.has_many :students, :through => :lesson_students, :anonymous_class => student + lesson_student.belongs_to :lesson, anonymous_class: lesson + lesson_student.belongs_to :student, anonymous_class: student + lesson.has_many :lesson_students, anonymous_class: lesson_student + lesson.has_many :students, through: :lesson_students, anonymous_class: student [lesson, lesson_student, student] end @@ -274,7 +274,7 @@ def test_associating_new new_person = nil # so block binding catches it assert_queries(0) do - new_person = Person.new :first_name => "bob" + new_person = Person.new first_name: "bob" end # Associating new records always saves them @@ -294,8 +294,8 @@ def test_associate_new_by_building assert_queries(1) { posts(:thinking) } assert_queries(0) do - posts(:thinking).people.build(:first_name => "Bob") - posts(:thinking).people.new(:first_name => "Ted") + posts(:thinking).people.build(first_name: "Bob") + posts(:thinking).people.new(first_name: "Ted") end # Should only need to load the association once @@ -318,7 +318,7 @@ def test_associate_new_by_building def test_build_then_save_with_has_many_inverse post = posts(:thinking) - person = post.people.build(:first_name => "Bob") + person = post.people.build(first_name: "Bob") person.save post.reload @@ -327,7 +327,7 @@ def test_build_then_save_with_has_many_inverse def test_build_then_save_with_has_one_inverse post = posts(:thinking) - person = post.single_people.build(:first_name => "Bob") + person = post.single_people.build(first_name: "Bob") person.save post.reload @@ -394,7 +394,7 @@ def test_delete_through_belongs_to_with_dependent_nullify person = people(:michael) job = jobs(:magician) - reference = Reference.where(:job_id => job.id, :person_id => person.id).first + reference = Reference.where(job_id: job.id, person_id: person.id).first assert_no_difference ["Job.count", "Reference.count"] do assert_difference "person.jobs.count", -1 do @@ -491,7 +491,7 @@ def test_belongs_to_with_dependent_nullify def test_update_counter_caches_on_delete post = posts(:welcome) - tag = post.tags.create!(:name => "doomed") + tag = post.tags.create!(name: "doomed") assert_difference ["post.reload.tags_count"], -1 do posts(:welcome).tags.delete(tag) @@ -500,7 +500,7 @@ def test_update_counter_caches_on_delete def test_update_counter_caches_on_delete_with_dependent_destroy post = posts(:welcome) - tag = post.tags.create!(:name => "doomed") + tag = post.tags.create!(name: "doomed") post.update_columns(tags_with_destroy_count: post.tags.count) assert_difference ["post.reload.tags_with_destroy_count"], -1 do @@ -510,7 +510,7 @@ def test_update_counter_caches_on_delete_with_dependent_destroy def test_update_counter_caches_on_delete_with_dependent_nullify post = posts(:welcome) - tag = post.tags.create!(:name => "doomed") + tag = post.tags.create!(name: "doomed") post.update_columns(tags_with_nullify_count: post.tags.count) assert_no_difference "post.reload.tags_count" do @@ -522,7 +522,7 @@ def test_update_counter_caches_on_delete_with_dependent_nullify def test_update_counter_caches_on_replace_association post = posts(:welcome) - tag = post.tags.create!(:name => "doomed") + tag = post.tags.create!(name: "doomed") tag.tagged_posts << posts(:thinking) tag.tagged_posts = [] @@ -586,7 +586,7 @@ def test_associate_with_create # 1 query for the new record, 1 for the join table record # No need to update the actual collection yet! assert_queries(2) do - posts(:thinking).people.create(:first_name=>"Jeb") + posts(:thinking).people.create(first_name: "Jeb") end # *Now* we actually need the collection so it's loaded @@ -605,55 +605,55 @@ def test_through_record_is_built_when_created_with_where def test_associate_with_create_and_no_options peeps = posts(:thinking).people.count - posts(:thinking).people.create(:first_name => "foo") + posts(:thinking).people.create(first_name: "foo") assert_equal peeps + 1, posts(:thinking).people.count end def test_associate_with_create_with_through_having_conditions impatient_people = posts(:thinking).impatient_people.count - posts(:thinking).impatient_people.create!(:first_name => "foo") + posts(:thinking).impatient_people.create!(first_name: "foo") assert_equal impatient_people + 1, posts(:thinking).impatient_people.count end def test_associate_with_create_exclamation_and_no_options peeps = posts(:thinking).people.count - posts(:thinking).people.create!(:first_name => "foo") + posts(:thinking).people.create!(first_name: "foo") assert_equal peeps + 1, posts(:thinking).people.count end def test_create_on_new_record p = Post.new - error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(:first_name => "mew") } + error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(first_name: "mew") } assert_equal "You cannot call create unless the parent is saved", error.message - error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(:first_name => "snow") } + error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(first_name: "snow") } assert_equal "You cannot call create unless the parent is saved", error.message end def test_associate_with_create_and_invalid_options firm = companies(:first_firm) - assert_no_difference("firm.developers.count") { assert_nothing_raised { firm.developers.create(:name => "0") } } + assert_no_difference("firm.developers.count") { assert_nothing_raised { firm.developers.create(name: "0") } } end def test_associate_with_create_and_valid_options firm = companies(:first_firm) - assert_difference("firm.developers.count", 1) { firm.developers.create(:name => "developer") } + assert_difference("firm.developers.count", 1) { firm.developers.create(name: "developer") } end def test_associate_with_create_bang_and_invalid_options firm = companies(:first_firm) - assert_no_difference("firm.developers.count") { assert_raises(ActiveRecord::RecordInvalid) { firm.developers.create!(:name => "0") } } + assert_no_difference("firm.developers.count") { assert_raises(ActiveRecord::RecordInvalid) { firm.developers.create!(name: "0") } } end def test_associate_with_create_bang_and_valid_options firm = companies(:first_firm) - assert_difference("firm.developers.count", 1) { firm.developers.create!(:name => "developer") } + assert_difference("firm.developers.count", 1) { firm.developers.create!(name: "developer") } end def test_push_with_invalid_record firm = companies(:first_firm) - assert_raises(ActiveRecord::RecordInvalid) { firm.developers << Developer.new(:name => "0") } + assert_raises(ActiveRecord::RecordInvalid) { firm.developers << Developer.new(name: "0") } end def test_push_with_invalid_join_record @@ -661,10 +661,10 @@ def test_push_with_invalid_join_record Contract.validate {|r| r.errors[:base] << "Invalid Contract" } firm = companies(:first_firm) - lifo = Developer.new(:name => "lifo") + lifo = Developer.new(name: "lifo") assert_raises(ActiveRecord::RecordInvalid) { firm.developers << lifo } - lifo = Developer.create!(:name => "lifo") + lifo = Developer.create!(name: "lifo") assert_raises(ActiveRecord::RecordInvalid) { firm.developers << lifo } end end @@ -694,7 +694,7 @@ def test_association_callback_ordering [:added, :after, "Michael"] ], log.last(2) - post.people_with_callbacks.push(people(:david), Person.create!(:first_name => "Bob"), Person.new(:first_name => "Lary")) + post.people_with_callbacks.push(people(:david), Person.create!(first_name: "Bob"), Person.new(first_name: "Lary")) assert_equal [ [:added, :before, "David"], [:added, :after, "David"], @@ -704,19 +704,19 @@ def test_association_callback_ordering [:added, :after, "Lary"] ],log.last(6) - post.people_with_callbacks.build(:first_name => "Ted") + post.people_with_callbacks.build(first_name: "Ted") assert_equal [ [:added, :before, "Ted"], [:added, :after, "Ted"] ], log.last(2) - post.people_with_callbacks.create(:first_name => "Sam") + post.people_with_callbacks.create(first_name: "Sam") assert_equal [ [:added, :before, "Sam"], [:added, :after, "Sam"] ], log.last(2) - post.people_with_callbacks = [people(:michael),people(:david), Person.new(:first_name => "Julian"), Person.create!(:first_name => "Roger")] + post.people_with_callbacks = [people(:michael),people(:david), Person.new(first_name: "Julian"), Person.create!(first_name: "Roger")] assert_equal((%w(Ted Bob Sam Lary) * 2).sort, log[-12..-5].collect(&:last).sort) assert_equal [ [:added, :before, "Julian"], @@ -745,7 +745,7 @@ def test_get_ids end def test_get_ids_for_has_many_through_with_conditions_should_not_preload - Tagging.create!(:taggable_type => "Post", :taggable_id => posts(:welcome).id, :tag => tags(:misc)) + Tagging.create!(taggable_type: "Post", taggable_id: posts(:welcome).id, tag: tags(:misc)) assert_not_called(ActiveRecord::Associations::Preloader, :new) do posts(:welcome).misc_tag_ids end @@ -776,16 +776,16 @@ def test_association_proxy_transaction_method_starts_transaction_in_association_ end def test_has_many_association_through_a_belongs_to_association_where_the_association_doesnt_exist - post = Post.create!(:title => "TITLE", :body => "BODY") + post = Post.create!(title: "TITLE", body: "BODY") assert_equal [], post.author_favorites end def test_has_many_association_through_a_belongs_to_association author = authors(:mary) - post = Post.create!(:author => author, :title => "TITLE", :body => "BODY") - author.author_favorites.create(:favorite_author_id => 1) - author.author_favorites.create(:favorite_author_id => 2) - author.author_favorites.create(:favorite_author_id => 3) + post = Post.create!(author: author, title: "TITLE", body: "BODY") + author.author_favorites.create(favorite_author_id: 1) + author.author_favorites.create(favorite_author_id: 2) + author.author_favorites.create(favorite_author_id: 3) assert_equal post.author.author_favorites, post.author_favorites end @@ -809,36 +809,36 @@ def test_has_many_through_has_one_reflection def test_modifying_has_many_through_has_one_reflection_should_raise [ - lambda { authors(:david).very_special_comments = [VerySpecialComment.create!(:body => "Gorp!", :post_id => 1011), VerySpecialComment.create!(:body => "Eep!", :post_id => 1012)] }, - lambda { authors(:david).very_special_comments << VerySpecialComment.create!(:body => "Hoohah!", :post_id => 1013) }, + lambda { authors(:david).very_special_comments = [VerySpecialComment.create!(body: "Gorp!", post_id: 1011), VerySpecialComment.create!(body: "Eep!", post_id: 1012)] }, + lambda { authors(:david).very_special_comments << VerySpecialComment.create!(body: "Hoohah!", post_id: 1013) }, lambda { authors(:david).very_special_comments.delete(authors(:david).very_special_comments.first) }, ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) } end def test_has_many_association_through_a_has_many_association_to_self - sarah = Person.create!(:first_name => "Sarah", :primary_contact_id => people(:susan).id, :gender => "F", :number1_fan_id => 1) - john = Person.create!(:first_name => "John", :primary_contact_id => sarah.id, :gender => "M", :number1_fan_id => 1) + sarah = Person.create!(first_name: "Sarah", primary_contact_id: people(:susan).id, gender: "F", number1_fan_id: 1) + john = Person.create!(first_name: "John", primary_contact_id: sarah.id, gender: "M", number1_fan_id: 1) assert_equal sarah.agents, [john] assert_equal people(:susan).agents.flat_map(&:agents), people(:susan).agents_of_agents end def test_associate_existing_with_nonstandard_primary_key_on_belongs_to - Categorization.create(:author => authors(:mary), :named_category_name => categories(:general).name) + Categorization.create(author: authors(:mary), named_category_name: categories(:general).name) assert_equal categories(:general), authors(:mary).named_categories.first end def test_collection_build_with_nonstandard_primary_key_on_belongs_to author = authors(:mary) - category = author.named_categories.build(:name => "Primary") + category = author.named_categories.build(name: "Primary") author.save - assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name) + assert Categorization.exists?(author_id: author.id, named_category_name: category.name) assert author.named_categories.reload.include?(category) end def test_collection_create_with_nonstandard_primary_key_on_belongs_to author = authors(:mary) - category = author.named_categories.create(:name => "Primary") - assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name) + category = author.named_categories.create(name: "Primary") + assert Categorization.exists?(author_id: author.id, named_category_name: category.name) assert author.named_categories.reload.include?(category) end @@ -851,9 +851,9 @@ def test_collection_exists def test_collection_delete_with_nonstandard_primary_key_on_belongs_to author = authors(:mary) - category = author.named_categories.create(:name => "Primary") + category = author.named_categories.create(name: "Primary") author.named_categories.delete(category) - assert !Categorization.exists?(:author_id => author.id, :named_category_name => category.name) + assert !Categorization.exists?(author_id: author.id, named_category_name: category.name) assert author.named_categories.reload.empty? end @@ -890,16 +890,16 @@ def test_collection_singular_ids_setter_raises_exception_when_invalid_ids_set end def test_build_a_model_from_hm_through_association_with_where_clause - assert_nothing_raised { books(:awdr).subscribers.where(:nick => "marklazz").build } + assert_nothing_raised { books(:awdr).subscribers.where(nick: "marklazz").build } end def test_attributes_are_being_set_when_initialized_from_hm_through_association_with_where_clause - new_subscriber = books(:awdr).subscribers.where(:nick => "marklazz").build + new_subscriber = books(:awdr).subscribers.where(nick: "marklazz").build assert_equal new_subscriber.nick, "marklazz" end def test_attributes_are_being_set_when_initialized_from_hm_through_association_with_multiple_where_clauses - new_subscriber = books(:awdr).subscribers.where(:nick => "marklazz").where(:name => "Marcelo Giorgi").build + new_subscriber = books(:awdr).subscribers.where(nick: "marklazz").where(name: "Marcelo Giorgi").build assert_equal new_subscriber.nick, "marklazz" assert_equal new_subscriber.name, "Marcelo Giorgi" end @@ -960,12 +960,12 @@ def test_has_many_through_with_default_scope_on_join_model end def test_create_has_many_through_with_default_scope_on_join_model - category = authors(:david).special_categories.create(:name => "Foo") - assert_equal 1, category.categorizations.where(:special => true).count + category = authors(:david).special_categories.create(name: "Foo") + assert_equal 1, category.categorizations.where(special: true).count end def test_joining_has_many_through_with_distinct - mary = Author.joins(:unique_categorized_posts).where(:id => authors(:mary).id).first + mary = Author.joins(:unique_categorized_posts).where(id: authors(:mary).id).first assert_equal 1, mary.unique_categorized_posts.length assert_equal 1, mary.unique_categorized_post_ids.length end @@ -1030,7 +1030,7 @@ def test_deleting_from_has_many_through_a_belongs_to_should_not_try_to_update_co def test_primary_key_option_on_source post = posts(:welcome) category = categories(:general) - Categorization.create!(:post_id => post.id, :named_category_name => category.name) + Categorization.create!(post_id: post.id, named_category_name: category.name) assert_equal [category], post.named_categories assert_equal [category.name], post.named_category_ids # checks when target loaded @@ -1040,12 +1040,12 @@ def test_primary_key_option_on_source def test_create_should_not_raise_exception_when_join_record_has_errors repair_validations(Categorization) do Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" } - Category.create(:name => "Fishing", :authors => [Author.first]) + Category.create(name: "Fishing", authors: [Author.first]) end end def test_assign_array_to_new_record_builds_join_records - c = Category.new(:name => "Fishing", :authors => [Author.first]) + c = Category.new(name: "Fishing", authors: [Author.first]) assert_equal 1, c.categorizations.size end @@ -1053,7 +1053,7 @@ def test_create_bang_should_raise_exception_when_join_record_has_errors repair_validations(Categorization) do Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" } assert_raises(ActiveRecord::RecordInvalid) do - Category.create!(:name => "Fishing", :authors => [Author.first]) + Category.create!(name: "Fishing", authors: [Author.first]) end end end @@ -1061,7 +1061,7 @@ def test_create_bang_should_raise_exception_when_join_record_has_errors def test_save_bang_should_raise_exception_when_join_record_has_errors repair_validations(Categorization) do Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" } - c = Category.new(:name => "Fishing", :authors => [Author.first]) + c = Category.new(name: "Fishing", authors: [Author.first]) assert_raises(ActiveRecord::RecordInvalid) do c.save! end @@ -1071,14 +1071,14 @@ def test_save_bang_should_raise_exception_when_join_record_has_errors def test_save_returns_falsy_when_join_record_has_errors repair_validations(Categorization) do Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" } - c = Category.new(:name => "Fishing", :authors => [Author.first]) + c = Category.new(name: "Fishing", authors: [Author.first]) assert_not c.save end end def test_preloading_empty_through_association_via_joins - person = Person.create!(:first_name => "Gaga") - person = Person.where(:id => person.id).where("readers.id = 1 or 1=1").references(:readers).includes(:posts).to_a.first + person = Person.create!(first_name: "Gaga") + person = Person.where(id: person.id).where("readers.id = 1 or 1=1").references(:readers).includes(:posts).to_a.first assert person.posts.loaded?, "person.posts should be loaded" assert_equal [], person.posts @@ -1101,7 +1101,7 @@ def test_explicitly_joining_join_table end def test_has_many_through_with_polymorphic_source - post = tags(:general).tagged_posts.create! :title => "foo", :body => "bar" + post = tags(:general).tagged_posts.create! title: "foo", body: "bar" assert_equal [tags(:general)], post.reload.tags end @@ -1148,9 +1148,9 @@ def test_insert_records_via_has_many_through_association_with_scope end def test_has_many_through_unscope_default_scope - post = Post.create!(:title => "Beaches", :body => "I like beaches!") - Reader.create! :person => people(:david), :post => post - LazyReader.create! :person => people(:susan), :post => post + post = Post.create!(title: "Beaches", body: "I like beaches!") + Reader.create! person: people(:david), post: post + LazyReader.create! person: people(:susan), post: post assert_equal 2, post.people.to_a.size assert_equal 1, post.lazy_people.to_a.size diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 9b049438f1..ad0d47920d 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -36,13 +36,13 @@ def test_has_one_cache_nils assert_queries(1) { assert_nil firm.account } assert_queries(0) { assert_nil firm.account } - firms = Firm.all.merge!(:includes => :account).to_a + firms = Firm.all.merge!(includes: :account).to_a assert_queries(0) { firms.each(&:account) } end def test_with_select assert_equal Firm.find(1).account_with_select.attributes.size, 2 - assert_equal Firm.all.merge!(:includes => :account_with_select).find(1).account_with_select.attributes.size, 2 + assert_equal Firm.all.merge!(includes: :account_with_select).find(1).account_with_select.attributes.size, 2 end def test_finding_using_primary_key @@ -102,7 +102,7 @@ def test_natural_assignment_to_nil def test_nullification_on_association_change firm = companies(:rails_core) old_account_id = firm.account.id - firm.account = Account.new(:credit_limit => 5) + firm.account = Account.new(credit_limit: 5) # account is dependent with nullify, therefore its firm_id should be nil assert_nil Account.find(old_account_id).firm_id end @@ -125,12 +125,12 @@ def test_natural_assignment_to_nil_after_destroy end def test_association_change_calls_delete - companies(:first_firm).deletable_account = Account.new(:credit_limit => 5) + companies(:first_firm).deletable_account = Account.new(credit_limit: 5) assert_equal [], Account.destroyed_account_ids[companies(:first_firm).id] end def test_association_change_calls_destroy - companies(:first_firm).account = Account.new(:credit_limit => 5) + companies(:first_firm).account = Account.new(credit_limit: 5) assert_equal [companies(:first_firm).id], Account.destroyed_account_ids[companies(:first_firm).id] end @@ -170,19 +170,19 @@ def test_exclusive_dependence end def test_dependence_with_nil_associate - firm = DependentFirm.new(:name => "nullify") + firm = DependentFirm.new(name: "nullify") firm.save! assert_nothing_raised { firm.destroy } end def test_restrict_with_exception - firm = RestrictedWithExceptionFirm.create!(:name => "restrict") - firm.create_account(:credit_limit => 10) + firm = RestrictedWithExceptionFirm.create!(name: "restrict") + firm.create_account(credit_limit: 10) assert_not_nil firm.account assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy } - assert RestrictedWithExceptionFirm.exists?(:name => "restrict") + assert RestrictedWithExceptionFirm.exists?(name: "restrict") assert firm.account.present? end @@ -206,8 +206,8 @@ def test_restrict_with_error_is_deprecated_using_key_one end def test_restrict_with_error - firm = RestrictedWithErrorFirm.create!(:name => "restrict") - firm.create_account(:credit_limit => 10) + firm = RestrictedWithErrorFirm.create!(name: "restrict") + firm.create_account(credit_limit: 10) assert_not_nil firm.account @@ -215,7 +215,7 @@ def test_restrict_with_error assert !firm.errors.empty? assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first - assert RestrictedWithErrorFirm.exists?(:name => "restrict") + assert RestrictedWithErrorFirm.exists?(name: "restrict") assert firm.account.present? end @@ -260,24 +260,24 @@ def test_building_the_associated_object_with_implicit_sti_base_class def test_building_the_associated_object_with_explicit_sti_base_class firm = DependentFirm.new - company = firm.build_company(:type => "Company") + company = firm.build_company(type: "Company") assert_kind_of Company, company, "Expected #{company.class} to be a Company" end def test_building_the_associated_object_with_sti_subclass firm = DependentFirm.new - company = firm.build_company(:type => "Client") + company = firm.build_company(type: "Client") assert_kind_of Client, company, "Expected #{company.class} to be a Client" end def test_building_the_associated_object_with_an_invalid_type firm = DependentFirm.new - assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Invalid") } + assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(type: "Invalid") } end def test_building_the_associated_object_with_an_unrelated_type firm = DependentFirm.new - assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Account") } + assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(type: "Account") } end def test_build_and_create_should_not_happen_within_scope @@ -295,19 +295,19 @@ def test_build_and_create_should_not_happen_within_scope end def test_create_association - firm = Firm.create(:name => "GlobalMegaCorp") - account = firm.create_account(:credit_limit => 1000) + firm = Firm.create(name: "GlobalMegaCorp") + account = firm.create_account(credit_limit: 1000) assert_equal account, firm.reload.account end def test_create_association_with_bang - firm = Firm.create(:name => "GlobalMegaCorp") - account = firm.create_account!(:credit_limit => 1000) + firm = Firm.create(name: "GlobalMegaCorp") + account = firm.create_account!(credit_limit: 1000) assert_equal account, firm.reload.account end def test_create_association_with_bang_failing - firm = Firm.create(:name => "GlobalMegaCorp") + firm = Firm.create(name: "GlobalMegaCorp") assert_raise ActiveRecord::RecordInvalid do firm.create_account! end @@ -365,7 +365,7 @@ def test_dependence_with_missing_association_and_nullify def test_finding_with_interpolated_condition firm = Firm.first - superior = firm.clients.create(:name => "SuperiorCo") + superior = firm.clients.create(name: "SuperiorCo") superior.rating = 10 superior.save assert_equal 10, firm.clients_with_interpolated_conditions.first.rating @@ -382,7 +382,7 @@ def test_assignment_before_child_saved end def test_save_still_works_after_accessing_nil_has_one - jp = Company.new :name => "Jaded Pixel" + jp = Company.new name: "Jaded Pixel" jp.dummy_account.nil? assert_nothing_raised do @@ -411,14 +411,14 @@ def test_save_of_record_with_loaded_has_one assert_nothing_raised do Firm.find(@firm.id).save! - Firm.all.merge!(:includes => :account).find(@firm.id).save! + Firm.all.merge!(includes: :account).find(@firm.id).save! end @firm.account.destroy assert_nothing_raised do Firm.find(@firm.id).save! - Firm.all.merge!(:includes => :account).find(@firm.id).save! + Firm.all.merge!(includes: :account).find(@firm.id).save! end end @@ -435,7 +435,7 @@ def test_create_respects_hash_condition end def test_attributes_are_being_set_when_initialized_from_has_one_association_with_where_clause - new_account = companies(:first_firm).build_account(:firm_name => "Account") + new_account = companies(:first_firm).build_account(firm_name: "Account") assert_equal new_account.firm_name, "Account" end @@ -505,60 +505,60 @@ def test_replacement_failure_due_to_new_record_should_raise_error end def test_association_keys_bypass_attribute_protection - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb = car.build_bulb assert_equal car.id, bulb.car_id - bulb = car.build_bulb :car_id => car.id + 1 + bulb = car.build_bulb car_id: car.id + 1 assert_equal car.id, bulb.car_id bulb = car.create_bulb assert_equal car.id, bulb.car_id - bulb = car.create_bulb :car_id => car.id + 1 + bulb = car.create_bulb car_id: car.id + 1 assert_equal car.id, bulb.car_id end def test_association_protect_foreign_key - pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") + pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") ship = pirate.build_ship assert_equal pirate.id, ship.pirate_id - ship = pirate.build_ship :pirate_id => pirate.id + 1 + ship = pirate.build_ship pirate_id: pirate.id + 1 assert_equal pirate.id, ship.pirate_id ship = pirate.create_ship assert_equal pirate.id, ship.pirate_id - ship = pirate.create_ship :pirate_id => pirate.id + 1 + ship = pirate.create_ship pirate_id: pirate.id + 1 assert_equal pirate.id, ship.pirate_id end def test_build_with_block - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb = car.build_bulb{ |b| b.color = "Red" } assert_equal "RED!", bulb.color end def test_create_with_block - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb = car.create_bulb{ |b| b.color = "Red" } assert_equal "RED!", bulb.color end def test_create_bang_with_block - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb = car.create_bulb!{ |b| b.color = "Red" } assert_equal "RED!", bulb.color end def test_association_attributes_are_available_to_after_initialize - car = Car.create(:name => "honda") + car = Car.create(name: "honda") bulb = car.create_bulb assert_equal car.id, bulb.attributes_after_initialize["car_id"] @@ -635,7 +635,7 @@ def test_has_one_relationship_cannot_have_a_counter_cache end def test_with_polymorphic_has_one_with_custom_columns_name - post = Post.create! :title => "foo", :body => "bar" + post = Post.create! title: "foo", body: "bar" image = Image.create! post.main_image = image diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index ef1cc3b27a..3a7f48fbb7 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -34,14 +34,14 @@ def test_has_one_through_with_has_one end def test_creating_association_creates_through_record - new_member = Member.create(:name => "Chris") - new_member.club = Club.create(:name => "LRUG") + new_member = Member.create(name: "Chris") + new_member.club = Club.create(name: "LRUG") assert_not_nil new_member.current_membership assert_not_nil new_member.club end def test_creating_association_builds_through_record_for_new - new_member = Member.new(:name => "Jane") + new_member = Member.new(name: "Jane") new_member.club = clubs(:moustache_club) assert new_member.current_membership assert_equal clubs(:moustache_club), new_member.current_membership.club @@ -65,7 +65,7 @@ def test_creating_association_sets_both_parent_ids_for_new end def test_replace_target_record - new_club = Club.create(:name => "Marx Bros") + new_club = Club.create(name: "Marx Bros") @member.club = new_club @member.reload assert_equal new_club, @member.club @@ -73,7 +73,7 @@ def test_replace_target_record def test_replacing_target_record_deletes_old_association assert_no_difference "Membership.count" do - new_club = Club.create(:name => "Bananarama") + new_club = Club.create(name: "Bananarama") @member.club = new_club @member.reload end @@ -92,7 +92,7 @@ def test_has_one_through_polymorphic def test_has_one_through_eager_loading members = assert_queries(3) do #base table, through table, clubs table - Member.all.merge!(:includes => :club, :where => ["name = ?", "Groucho Marx"]).to_a + Member.all.merge!(includes: :club, where: ["name = ?", "Groucho Marx"]).to_a end assert_equal 1, members.size assert_not_nil assert_no_queries {members[0].club} @@ -100,7 +100,7 @@ def test_has_one_through_eager_loading def test_has_one_through_eager_loading_through_polymorphic members = assert_queries(3) do #base table, through table, clubs table - Member.all.merge!(:includes => :sponsor_club, :where => ["name = ?", "Groucho Marx"]).to_a + Member.all.merge!(includes: :sponsor_club, where: ["name = ?", "Groucho Marx"]).to_a end assert_equal 1, members.size assert_not_nil assert_no_queries {members[0].sponsor_club} @@ -108,14 +108,14 @@ def test_has_one_through_eager_loading_through_polymorphic def test_has_one_through_with_conditions_eager_loading # conditions on the through table - assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :favourite_club).find(@member.id).favourite_club + assert_equal clubs(:moustache_club), Member.all.merge!(includes: :favourite_club).find(@member.id).favourite_club memberships(:membership_of_favourite_club).update_columns(favourite: false) - assert_equal nil, Member.all.merge!(:includes => :favourite_club).find(@member.id).reload.favourite_club + assert_equal nil, Member.all.merge!(includes: :favourite_club).find(@member.id).reload.favourite_club # conditions on the source table - assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :hairy_club).find(@member.id).hairy_club + assert_equal clubs(:moustache_club), Member.all.merge!(includes: :hairy_club).find(@member.id).hairy_club clubs(:moustache_club).update_columns(name: "Association of Clean-Shaven Persons") - assert_equal nil, Member.all.merge!(:includes => :hairy_club).find(@member.id).reload.hairy_club + assert_equal nil, Member.all.merge!(includes: :hairy_club).find(@member.id).reload.hairy_club end def test_has_one_through_polymorphic_with_source_type @@ -123,14 +123,14 @@ def test_has_one_through_polymorphic_with_source_type end def test_eager_has_one_through_polymorphic_with_source_type - clubs = Club.all.merge!(:includes => :sponsored_member, :where => ["name = ?","Moustache and Eyebrow Fancier Club"]).to_a + clubs = Club.all.merge!(includes: :sponsored_member, where: ["name = ?","Moustache and Eyebrow Fancier Club"]).to_a # Only the eyebrow fanciers club has a sponsored_member assert_not_nil assert_no_queries {clubs[0].sponsored_member} end def test_has_one_through_nonpreload_eagerloading members = assert_queries(1) do - Member.all.merge!(:includes => :club, :where => ["members.name = ?", "Groucho Marx"], :order => "clubs.name").to_a #force fallback + Member.all.merge!(includes: :club, where: ["members.name = ?", "Groucho Marx"], order: "clubs.name").to_a #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries {members[0].club} @@ -138,16 +138,16 @@ def test_has_one_through_nonpreload_eagerloading def test_has_one_through_nonpreload_eager_loading_through_polymorphic members = assert_queries(1) do - Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => "clubs.name").to_a #force fallback + Member.all.merge!(includes: :sponsor_club, where: ["members.name = ?", "Groucho Marx"], order: "clubs.name").to_a #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries {members[0].sponsor_club} end def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record - Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save! + Sponsor.new(sponsor_club: clubs(:crazy_club), sponsorable: members(:groucho)).save! members = assert_queries(1) do - Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => "clubs.name DESC").to_a #force fallback + Member.all.merge!(includes: :sponsor_club, where: ["members.name = ?", "Groucho Marx"], order: "clubs.name DESC").to_a #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries { members[0].sponsor_club } @@ -159,8 +159,8 @@ def test_uninitialized_has_one_through_should_return_nil_for_unsaved_record end def test_assigning_association_correctly_assigns_target - new_member = Member.create(:name => "Chris") - new_member.club = new_club = Club.create(:name => "LRUG") + new_member = Member.create(name: "Chris") + new_member.club = new_club = Club.create(name: "LRUG") assert_equal new_club, new_member.association(:club).target end @@ -177,7 +177,7 @@ def test_has_one_through_proxy_should_respond_to_private_methods_via_send def test_assigning_to_has_one_through_preserves_decorated_join_record @organization = organizations(:nsa) assert_difference "MemberDetail.count", 1 do - @member_detail = MemberDetail.new(:extra_data => "Extra") + @member_detail = MemberDetail.new(extra_data: "Extra") @member.member_detail = @member_detail @member.organization = @organization end @@ -191,7 +191,7 @@ def test_reassigning_has_one_through @new_organization = organizations(:discordians) assert_difference "MemberDetail.count", 1 do - @member_detail = MemberDetail.new(:extra_data => "Extra") + @member_detail = MemberDetail.new(extra_data: "Extra") @member.member_detail = @member_detail @member.organization = @organization end @@ -217,7 +217,7 @@ def test_preloading_has_one_through_on_belongs_to @member.member_detail = @member_detail @member.organization = @organization @member_details = assert_queries(3) do - MemberDetail.all.merge!(:includes => :member_type).to_a + MemberDetail.all.merge!(includes: :member_type).to_a end @new_detail = @member_details[0] assert @new_detail.send(:association, :member_type).loaded? @@ -230,19 +230,19 @@ def test_save_of_record_with_loaded_has_one_through assert_nothing_raised do Club.find(@club.id).save! - Club.all.merge!(:includes => :sponsored_member).find(@club.id).save! + Club.all.merge!(includes: :sponsored_member).find(@club.id).save! end @club.sponsor.destroy assert_nothing_raised do Club.find(@club.id).save! - Club.all.merge!(:includes => :sponsored_member).find(@club.id).save! + Club.all.merge!(includes: :sponsored_member).find(@club.id).save! end end def test_through_belongs_to_after_destroy - @member_detail = MemberDetail.new(:extra_data => "Extra") + @member_detail = MemberDetail.new(extra_data: "Extra") @member.member_detail = @member_detail @member.save! diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index 816610ebea..be5c8854be 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -20,7 +20,7 @@ def test_construct_finder_sql_applies_aliases_tables_on_association_conditions def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations assert_nothing_raised do - sql = Person.joins(:agents => {:agents => :agents}).joins(:agents => {:agents => {:primary_contact => :agents}}).to_sql + sql = Person.joins(agents: {agents: :agents}).joins(agents: {agents: {primary_contact: :agents}}).to_sql assert_match(/agents_people_4/i, sql) end end @@ -47,7 +47,7 @@ def test_join_association_conditions_support_string_and_arel_expressions end def test_join_conditions_allow_nil_associations - authors = Author.includes(:essays).where(:essays => {:id => nil}) + authors = Author.includes(:essays).where(essays: {id: nil}) assert_equal 2, authors.count end @@ -92,7 +92,7 @@ def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions end def test_find_with_sti_join - scope = Post.joins(:special_comments).where(:id => posts(:sti_comments).id) + scope = Post.joins(:special_comments).where(id: posts(:sti_comments).id) # The join should match SpecialComment and its subclasses only assert scope.where("comments.type" => "Comment").empty? @@ -102,12 +102,12 @@ def test_find_with_sti_join def test_find_with_conditions_on_reflection assert !posts(:welcome).comments.empty? - assert Post.joins(:nonexistent_comments).where(:id => posts(:welcome).id).empty? # [sic!] + assert Post.joins(:nonexistent_comments).where(id: posts(:welcome).id).empty? # [sic!] end def test_find_with_conditions_on_through_reflection assert !posts(:welcome).tags.empty? - assert Post.joins(:misc_tags).where(:id => posts(:welcome).id).empty? + assert Post.joins(:misc_tags).where(id: posts(:welcome).id).empty? end test "the default scope of the target is applied when joining associations" do diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index 6387afeb27..ae0468ef1e 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -131,15 +131,15 @@ def test_polymorphic_relationships_should_still_not_have_inverses_when_non_polym class InverseAssociationTests < ActiveRecord::TestCase def test_should_allow_for_inverse_of_options_in_associations assert_nothing_raised do - Class.new(ActiveRecord::Base).has_many(:wheels, :inverse_of => :car) + Class.new(ActiveRecord::Base).has_many(:wheels, inverse_of: :car) end assert_nothing_raised do - Class.new(ActiveRecord::Base).has_one(:engine, :inverse_of => :car) + Class.new(ActiveRecord::Base).has_one(:engine, inverse_of: :car) end assert_nothing_raised do - Class.new(ActiveRecord::Base).belongs_to(:car, :inverse_of => :driver) + Class.new(ActiveRecord::Base).belongs_to(:car, inverse_of: :driver) end end @@ -228,7 +228,7 @@ def test_parent_instance_should_be_shared_with_child_on_find def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find - m = Man.all.merge!(:where => {:name => "Gordon"}, :includes => :face).first + m = Man.all.merge!(where: {name: "Gordon"}, includes: :face).first f = m.face assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = "Bongo" @@ -236,7 +236,7 @@ def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find f.man.name = "Mungo" assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance" - m = Man.all.merge!(:where => {:name => "Gordon"}, :includes => :face, :order => "faces.id").first + m = Man.all.merge!(where: {name: "Gordon"}, includes: :face, order: "faces.id").first f = m.face assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = "Bongo" @@ -247,7 +247,7 @@ def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find def test_parent_instance_should_be_shared_with_newly_built_child m = Man.first - f = m.build_face(:description => "haunted") + f = m.build_face(description: "haunted") assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = "Bongo" @@ -258,7 +258,7 @@ def test_parent_instance_should_be_shared_with_newly_built_child def test_parent_instance_should_be_shared_with_newly_created_child m = Man.first - f = m.create_face(:description => "haunted") + f = m.create_face(description: "haunted") assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = "Bongo" @@ -269,7 +269,7 @@ def test_parent_instance_should_be_shared_with_newly_created_child def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method m = Man.first - f = m.create_face!(:description => "haunted") + f = m.create_face!(description: "haunted") assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = "Bongo" @@ -280,7 +280,7 @@ def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_meth def test_parent_instance_should_be_shared_with_replaced_via_accessor_child m = Man.first - f = Face.new(:description => "haunted") + f = Face.new(description: "haunted") m.face = f assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" @@ -311,7 +311,7 @@ def test_parent_instance_should_be_shared_with_every_child_on_find end def test_parent_instance_should_be_shared_with_eager_loaded_children - m = Man.all.merge!(:where => {:name => "Gordon"}, :includes => :interests).first + m = Man.all.merge!(where: {name: "Gordon"}, includes: :interests).first is = m.interests is.each do |i| assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" @@ -321,7 +321,7 @@ def test_parent_instance_should_be_shared_with_eager_loaded_children assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance" end - m = Man.all.merge!(:where => {:name => "Gordon"}, :includes => :interests, :order => "interests.id").first + m = Man.all.merge!(where: {name: "Gordon"}, includes: :interests, order: "interests.id").first is = m.interests is.each do |i| assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" @@ -346,7 +346,7 @@ def test_parent_instance_should_be_shared_with_newly_block_style_built_child def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child m = Man.first - i = m.interests.create!(:topic => "Industrial Revolution Re-enactment") + i = m.interests.create!(topic: "Industrial Revolution Re-enactment") assert_not_nil i.man assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" m.name = "Bongo" @@ -385,7 +385,7 @@ def test_parent_instance_should_be_shared_within_build_block_of_new_child def test_parent_instance_should_be_shared_with_poked_in_child m = men(:gordon) - i = Interest.create(:topic => "Industrial Revolution Re-enactment") + i = Interest.create(topic: "Industrial Revolution Re-enactment") m.interests << i assert_not_nil i.man assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" @@ -397,7 +397,7 @@ def test_parent_instance_should_be_shared_with_poked_in_child def test_parent_instance_should_be_shared_with_replaced_via_accessor_children m = Man.first - i = Interest.new(:topic => "Industrial Revolution Re-enactment") + i = Interest.new(topic: "Industrial Revolution Re-enactment") m.interests = [i] assert_not_nil i.man assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" @@ -485,7 +485,7 @@ def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error def test_child_instance_should_point_to_parent_without_saving man = Man.new - i = Interest.create(:topic => "Industrial Revolution Re-enactment") + i = Interest.create(topic: "Industrial Revolution Re-enactment") man.interests << i assert_not_nil i.man @@ -511,7 +511,7 @@ def test_child_instance_should_be_shared_with_parent_on_find end def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find - f = Face.all.merge!(:includes => :man, :where => {:description => "trusting"}).first + f = Face.all.merge!(includes: :man, where: {description: "trusting"}).first m = f.man assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance" f.description = "gormless" @@ -519,7 +519,7 @@ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find m.face.description = "pleasing" assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance" - f = Face.all.merge!(:includes => :man, :order => "men.id", :where => {:description => "trusting"}).first + f = Face.all.merge!(includes: :man, order: "men.id", where: {description: "trusting"}).first m = f.man assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance" f.description = "gormless" @@ -530,7 +530,7 @@ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find def test_child_instance_should_be_shared_with_newly_built_parent f = faces(:trusting) - m = f.build_man(:name => "Charles") + m = f.build_man(name: "Charles") assert_not_nil m.face assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance" f.description = "gormless" @@ -541,7 +541,7 @@ def test_child_instance_should_be_shared_with_newly_built_parent def test_child_instance_should_be_shared_with_newly_created_parent f = faces(:trusting) - m = f.create_man(:name => "Charles") + m = f.create_man(name: "Charles") assert_not_nil m.face assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance" f.description = "gormless" @@ -565,7 +565,7 @@ def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many def test_child_instance_should_be_shared_with_replaced_via_accessor_parent f = Face.first - m = Man.new(:name => "Charles") + m = Man.new(name: "Charles") f.man = m assert_not_nil m.face assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance" @@ -584,7 +584,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase fixtures :men, :faces, :interests def test_child_instance_should_be_shared_with_parent_on_find - f = Face.all.merge!(:where => {:description => "confused"}).first + f = Face.all.merge!(where: {description: "confused"}).first m = f.polymorphic_man assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance" f.description = "gormless" @@ -594,7 +594,7 @@ def test_child_instance_should_be_shared_with_parent_on_find end def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find - f = Face.all.merge!(:where => {:description => "confused"}, :includes => :man).first + f = Face.all.merge!(where: {description: "confused"}, includes: :man).first m = f.polymorphic_man assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance" f.description = "gormless" @@ -602,7 +602,7 @@ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find m.polymorphic_face.description = "pleasing" assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance" - f = Face.all.merge!(:where => {:description => "confused"}, :includes => :man, :order => "men.id").first + f = Face.all.merge!(where: {description: "confused"}, includes: :man, order: "men.id").first m = f.polymorphic_man assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance" f.description = "gormless" @@ -698,8 +698,8 @@ def test_that_we_can_load_associations_that_have_the_same_reciprocal_name_from_d def test_that_we_can_create_associations_that_have_the_same_reciprocal_name_from_different_models assert_nothing_raised do i = Interest.first - i.build_zine(:title => "Get Some in Winter! 2008") - i.build_man(:name => "Gordon") + i.build_zine(title: "Get Some in Winter! 2008") + i.build_man(name: "Gordon") i.save! end end diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 00777fdcf5..7d67c289ff 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -97,10 +97,10 @@ def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key end def test_polymorphic_has_many_create_model_with_inheritance_and_custom_base_class - post = SubStiPost.create :title => "SubStiPost", :body => "SubStiPost body" + post = SubStiPost.create title: "SubStiPost", body: "SubStiPost body" assert_instance_of SubStiPost, post - tagging = tags(:misc).taggings.create(:taggable => post) + tagging = tags(:misc).taggings.create(taggable: post) assert_equal "SubStiPost", tagging.taggable_type end @@ -116,12 +116,12 @@ def test_polymorphic_has_many_create_model_with_inheritance post = posts(:thinking) assert_instance_of SpecialPost, post - tagging = tags(:misc).taggings.create(:taggable => post) + tagging = tags(:misc).taggings.create(taggable: post) assert_equal "Post", tagging.taggable_type end def test_polymorphic_has_one_create_model_with_inheritance - tagging = tags(:misc).create_tagging(:taggable => posts(:thinking)) + tagging = tags(:misc).create_tagging(taggable: posts(:thinking)) assert_equal "Post", tagging.taggable_type end @@ -142,7 +142,7 @@ def test_set_polymorphic_has_one def test_set_polymorphic_has_one_on_new_record tagging = tags(:misc).taggings.create - post = Post.new :title => "foo", :body => "bar" + post = Post.new title: "foo", body: "bar" post.tagging = tagging post.save! @@ -153,21 +153,21 @@ def test_set_polymorphic_has_one_on_new_record def test_create_polymorphic_has_many_with_scope old_count = posts(:welcome).taggings.count - tagging = posts(:welcome).taggings.create(:tag => tags(:misc)) + tagging = posts(:welcome).taggings.create(tag: tags(:misc)) assert_equal "Post", tagging.taggable_type assert_equal old_count+1, posts(:welcome).taggings.count end def test_create_bang_polymorphic_with_has_many_scope old_count = posts(:welcome).taggings.count - tagging = posts(:welcome).taggings.create!(:tag => tags(:misc)) + tagging = posts(:welcome).taggings.create!(tag: tags(:misc)) assert_equal "Post", tagging.taggable_type assert_equal old_count+1, posts(:welcome).taggings.count end def test_create_polymorphic_has_one_with_scope old_count = Tagging.count - tagging = posts(:welcome).create_tagging(:tag => tags(:misc)) + tagging = posts(:welcome).create_tagging(tag: tags(:misc)) assert_equal "Post", tagging.taggable_type assert_equal old_count+1, Tagging.count end @@ -235,15 +235,15 @@ def test_has_many_with_piggyback def test_create_through_has_many_with_piggyback category = categories(:sti_test) - ernie = category.authors_with_select.create(:name => "Ernie") + ernie = category.authors_with_select.create(name: "Ernie") assert_nothing_raised do assert_equal ernie, category.authors_with_select.detect {|a| a.name == "Ernie"} end end def test_include_has_many_through - posts = Post.all.merge!(:order => "posts.id").to_a - posts_with_authors = Post.all.merge!(:includes => :authors, :order => "posts.id").to_a + posts = Post.all.merge!(order: "posts.id").to_a + posts_with_authors = Post.all.merge!(includes: :authors, order: "posts.id").to_a assert_equal posts.length, posts_with_authors.length posts.length.times do |i| assert_equal posts[i].authors.length, assert_no_queries { posts_with_authors[i].authors.length } @@ -267,8 +267,8 @@ def test_include_polymorphic_has_one_defined_in_abstract_parent end def test_include_polymorphic_has_many_through - posts = Post.all.merge!(:order => "posts.id").to_a - posts_with_tags = Post.all.merge!(:includes => :tags, :order => "posts.id").to_a + posts = Post.all.merge!(order: "posts.id").to_a + posts_with_tags = Post.all.merge!(includes: :tags, order: "posts.id").to_a assert_equal posts.length, posts_with_tags.length posts.length.times do |i| assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length } @@ -276,8 +276,8 @@ def test_include_polymorphic_has_many_through end def test_include_polymorphic_has_many - posts = Post.all.merge!(:order => "posts.id").to_a - posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => "posts.id").to_a + posts = Post.all.merge!(order: "posts.id").to_a + posts_with_taggings = Post.all.merge!(includes: :taggings, order: "posts.id").to_a assert_equal posts.length, posts_with_taggings.length posts.length.times do |i| assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length } @@ -329,7 +329,7 @@ def test_has_many_through_with_custom_primary_key_on_has_many_source def test_belongs_to_polymorphic_with_counter_cache assert_equal 1, posts(:welcome)[:tags_count] - tagging = posts(:welcome).taggings.create(:tag => tags(:general)) + tagging = posts(:welcome).taggings.create(tag: tags(:general)) assert_equal 2, posts(:welcome, :reload)[:tags_count] tagging.destroy assert_equal 1, posts(:welcome, :reload)[:tags_count] @@ -365,13 +365,13 @@ def test_has_many_polymorphic_with_source_type def test_has_many_polymorphic_associations_merges_through_scope Tag.has_many :null_taggings, -> { none }, class_name: :Tagging - Tag.has_many :null_tagged_posts, :through => :null_taggings, :source => "taggable", :source_type => "Post" + Tag.has_many :null_tagged_posts, through: :null_taggings, source: "taggable", source_type: "Post" assert_equal [], tags(:general).null_tagged_posts refute_equal [], tags(:general).tagged_posts end def test_eager_has_many_polymorphic_with_source_type - tag_with_include = Tag.all.merge!(:includes => :tagged_posts).find(tags(:general).id) + tag_with_include = Tag.all.merge!(includes: :tagged_posts).find(tags(:general).id) desired = posts(:welcome, :thinking) assert_no_queries do # added sort by ID as otherwise test using JRuby was failing as array elements were in different order @@ -393,7 +393,7 @@ def test_has_many_through_has_many_find_first end def test_has_many_through_has_many_find_conditions - options = { :where => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => "comments.id" } + options = { where: "comments.#{QUOTED_TYPE}='SpecialComment'", order: "comments.id" } assert_equal comments(:does_it_hurt), authors(:david).comments.merge(options).first end @@ -418,7 +418,7 @@ def test_include_has_many_through_polymorphic_has_many end def test_eager_load_has_many_through_has_many - author = Author.all.merge!(:where => ["name = ?", "David"], :includes => :comments, :order => "comments.id").first + author = Author.all.merge!(where: ["name = ?", "David"], includes: :comments, order: "comments.id").first SpecialComment.new; VerySpecialComment.new assert_no_queries do assert_equal [1,2,3,5,6,7,8,9,10,12], author.comments.collect(&:id) @@ -426,7 +426,7 @@ def test_eager_load_has_many_through_has_many end def test_eager_load_has_many_through_has_many_with_conditions - post = Post.all.merge!(:includes => :invalid_tags).first + post = Post.all.merge!(includes: :invalid_tags).first assert_no_queries do post.invalid_tags end @@ -434,8 +434,8 @@ def test_eager_load_has_many_through_has_many_with_conditions def test_eager_belongs_to_and_has_one_not_singularized assert_nothing_raised do - Author.all.merge!(:includes => :author_address).first - AuthorAddress.all.merge!(:includes => :author).first + Author.all.merge!(includes: :author_address).first + AuthorAddress.all.merge!(includes: :author).first end end @@ -445,8 +445,8 @@ def test_self_referential_has_many_through end def test_add_to_self_referential_has_many_through - new_author = Author.create(:name => "Bob") - authors(:david).author_favorites.create :favorite_author => new_author + new_author = Author.create(name: "Bob") + authors(:david).author_favorites.create favorite_author: new_author assert_equal new_author, authors(:david).reload.favorite_authors.first end @@ -462,7 +462,7 @@ def test_has_many_through_uses_correct_attributes def test_associating_unsaved_records_with_has_many_through saved_post = posts(:thinking) - new_tag = Tag.new(:name => "new") + new_tag = Tag.new(name: "new") saved_post.tags << new_tag assert new_tag.persisted? #consistent with habtm! @@ -473,7 +473,7 @@ def test_associating_unsaved_records_with_has_many_through assert saved_post.reload.tags.reload.include?(new_tag) - new_post = Post.new(:title => "Association replacement works!", :body => "You best believe it.") + new_post = Post.new(title: "Association replacement works!", body: "You best believe it.") saved_tag = tags(:general) new_post.tags << saved_tag @@ -491,7 +491,7 @@ def test_associating_unsaved_records_with_has_many_through def test_create_associate_when_adding_to_has_many_through count = posts(:thinking).tags.count - push = Tag.create!(:name => "pushme") + push = Tag.create!(name: "pushme") post_thinking = posts(:thinking) assert_nothing_raised { post_thinking.tags << push } assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag }, @@ -501,7 +501,7 @@ def test_create_associate_when_adding_to_has_many_through assert_equal(count + 1, post_thinking.reload.tags.size) assert_equal(count + 1, post_thinking.tags.reload.size) - assert_kind_of Tag, post_thinking.tags.create!(:name => "foo") + assert_kind_of Tag, post_thinking.tags.create!(name: "foo") assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag }, message = "Expected a Tag in tags collection, got #{wrong.class}.") assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging }, @@ -509,7 +509,7 @@ def test_create_associate_when_adding_to_has_many_through assert_equal(count + 2, post_thinking.reload.tags.size) assert_equal(count + 2, post_thinking.tags.reload.size) - assert_nothing_raised { post_thinking.tags.concat(Tag.create!(:name => "abc"), Tag.create!(:name => "def")) } + assert_nothing_raised { post_thinking.tags.concat(Tag.create!(name: "abc"), Tag.create!(name: "def")) } assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag }, message = "Expected a Tag in tags collection, got #{wrong.class}.") assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging }, @@ -550,7 +550,7 @@ def test_adding_to_has_many_through_should_return_self def test_delete_associate_when_deleting_from_has_many_through_with_nonstandard_id count = books(:awdr).references.count references_before = books(:awdr).references - book = Book.create!(:name => "Getting Real") + book = Book.create!(name: "Getting Real") book_awdr = books(:awdr) book_awdr.references << book assert_equal(count + 1, book_awdr.references.reload.size) @@ -564,7 +564,7 @@ def test_delete_associate_when_deleting_from_has_many_through_with_nonstandard_i def test_delete_associate_when_deleting_from_has_many_through count = posts(:thinking).tags.count tags_before = posts(:thinking).tags.sort - tag = Tag.create!(:name => "doomed") + tag = Tag.create!(name: "doomed") post_thinking = posts(:thinking) post_thinking.tags << tag assert_equal(count + 1, post_thinking.taggings.reload.size) @@ -581,9 +581,9 @@ def test_delete_associate_when_deleting_from_has_many_through def test_delete_associate_when_deleting_from_has_many_through_with_multiple_tags count = posts(:thinking).tags.count tags_before = posts(:thinking).tags.sort - doomed = Tag.create!(:name => "doomed") - doomed2 = Tag.create!(:name => "doomed2") - quaked = Tag.create!(:name => "quaked") + doomed = Tag.create!(name: "doomed") + doomed2 = Tag.create!(name: "doomed2") + quaked = Tag.create!(name: "quaked") post_thinking = posts(:thinking) post_thinking.tags << doomed << doomed2 assert_equal(count + 2, post_thinking.reload.tags.reload.size) @@ -642,7 +642,7 @@ def test_distinct_has_many_through_should_retain_order def test_polymorphic_has_many expected = taggings(:welcome_general) - p = Post.all.merge!(:includes => :taggings).find(posts(:welcome).id) + p = Post.all.merge!(includes: :taggings).find(posts(:welcome).id) assert_no_queries {assert p.taggings.include?(expected)} assert posts(:welcome).taggings.include?(taggings(:welcome_general)) end @@ -650,18 +650,18 @@ def test_polymorphic_has_many def test_polymorphic_has_one expected = posts(:welcome) - tagging = Tagging.all.merge!(:includes => :taggable).find(taggings(:welcome_general).id) + tagging = Tagging.all.merge!(includes: :taggable).find(taggings(:welcome_general).id) assert_no_queries { assert_equal expected, tagging.taggable} end def test_polymorphic_belongs_to - p = Post.all.merge!(:includes => {:taggings => :taggable}).find(posts(:welcome).id) + p = Post.all.merge!(includes: {taggings: :taggable}).find(posts(:welcome).id) assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable} end def test_preload_polymorphic_has_many_through - posts = Post.all.merge!(:order => "posts.id").to_a - posts_with_tags = Post.all.merge!(:includes => :tags, :order => "posts.id").to_a + posts = Post.all.merge!(order: "posts.id").to_a + posts_with_tags = Post.all.merge!(includes: :tags, order: "posts.id").to_a assert_equal posts.length, posts_with_tags.length posts.length.times do |i| assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length } @@ -669,7 +669,7 @@ def test_preload_polymorphic_has_many_through end def test_preload_polymorph_many_types - taggings = Tagging.all.merge!(:includes => :taggable, :where => ["taggable_type != ?", "FakeModel"]).to_a + taggings = Tagging.all.merge!(includes: :taggable, where: ["taggable_type != ?", "FakeModel"]).to_a assert_no_queries do taggings.first.taggable.id taggings[1].taggable.id @@ -682,13 +682,13 @@ def test_preload_polymorph_many_types def test_preload_nil_polymorphic_belongs_to assert_nothing_raised do - Tagging.all.merge!(:includes => :taggable, :where => ["taggable_type IS NULL"]).to_a + Tagging.all.merge!(includes: :taggable, where: ["taggable_type IS NULL"]).to_a end end def test_preload_polymorphic_has_many - posts = Post.all.merge!(:order => "posts.id").to_a - posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => "posts.id").to_a + posts = Post.all.merge!(order: "posts.id").to_a + posts_with_taggings = Post.all.merge!(includes: :taggings, order: "posts.id").to_a assert_equal posts.length, posts_with_taggings.length posts.length.times do |i| assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length } @@ -696,7 +696,7 @@ def test_preload_polymorphic_has_many end def test_belongs_to_shared_parent - comments = Comment.all.merge!(:includes => :post, :where => "post_id = 1").to_a + comments = Comment.all.merge!(includes: :post, where: "post_id = 1").to_a assert_no_queries do assert_equal comments.first.post, comments[1].post end @@ -728,22 +728,22 @@ def test_has_many_through_include_checks_if_record_exists_if_target_not_loaded def test_has_many_through_include_returns_false_for_non_matching_record_to_verify_scoping david = authors(:david) - category = Category.create!(:name => "Not Associated") + category = Category.create!(name: "Not Associated") assert ! david.categories.loaded? assert ! david.categories.include?(category) end def test_has_many_through_goes_through_all_sti_classes - sub_sti_post = SubStiPost.create!(:title => "test", :body => "test", :author_id => 1) - new_comment = sub_sti_post.comments.create(:body => "test") + sub_sti_post = SubStiPost.create!(title: "test", body: "test", author_id: 1) + new_comment = sub_sti_post.comments.create(body: "test") assert_equal [9, 10, new_comment.id], authors(:david).sti_post_comments.map(&:id).sort end def test_has_many_with_pluralize_table_names_false - aircraft = Aircraft.create!(:name => "Airbus 380") - engine = Engine.create!(:car_id => aircraft.id) + aircraft = Aircraft.create!(name: "Airbus 380") + engine = Engine.create!(car_id: aircraft.id) assert_equal aircraft.engines, [engine] end @@ -771,7 +771,7 @@ def find_post_with_dependency(post_id, association, association_name, dependency Post.find(post_id).update_columns type: class_name klass = Object.const_set(class_name, Class.new(ActiveRecord::Base)) klass.table_name = "posts" - klass.send(association, association_name, :as => :taggable, :dependent => dependency) + klass.send(association, association_name, as: :taggable, dependent: dependency) klass.find(post_id) end end diff --git a/activerecord/test/cases/associations/left_outer_join_association_test.rb b/activerecord/test/cases/associations/left_outer_join_association_test.rb index 6258c356fc..003240bb26 100644 --- a/activerecord/test/cases/associations/left_outer_join_association_test.rb +++ b/activerecord/test/cases/associations/left_outer_join_association_test.rb @@ -18,8 +18,8 @@ def test_construct_finder_sql_applies_aliases_tables_on_association_conditions def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations assert_nothing_raised do queries = capture_sql do - Person.left_outer_joins(:agents => {:agents => :agents}) - .left_outer_joins(:agents => {:agents => {:primary_contact => :agents}}).to_a + Person.left_outer_joins(agents: {agents: :agents}) + .left_outer_joins(agents: {agents: {primary_contact: :agents}}).to_a end assert queries.any? { |sql| /agents_people_4/i.match?(sql) } end @@ -56,7 +56,7 @@ def test_join_conditions_added_to_join_clause end def test_find_with_sti_join - scope = Post.left_outer_joins(:special_comments).where(:id => posts(:sti_comments).id) + scope = Post.left_outer_joins(:special_comments).where(id: posts(:sti_comments).id) # The join should match SpecialComment and its subclasses only assert scope.where("comments.type" => "Comment").empty? diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb index 09264f08db..dc26f6a383 100644 --- a/activerecord/test/cases/associations/nested_through_associations_test.rb +++ b/activerecord/test/cases/associations/nested_through_associations_test.rb @@ -443,7 +443,7 @@ def test_has_many_through_with_sti_on_through_reflection assert_equal [ratings(:special_comment_rating), ratings(:sub_special_comment_rating)], ratings # Ensure STI is respected in the join - scope = Post.joins(:special_comments_ratings).where(:id => posts(:sti_comments).id) + scope = Post.joins(:special_comments_ratings).where(id: posts(:sti_comments).id) assert scope.where("comments.type" => "Comment").empty? assert !scope.where("comments.type" => "SpecialComment").empty? assert !scope.where("comments.type" => "SubSpecialComment").empty? @@ -453,7 +453,7 @@ def test_has_many_through_with_sti_on_nested_through_reflection taggings = posts(:sti_comments).special_comments_ratings_taggings assert_equal [taggings(:special_comment_rating)], taggings - scope = Post.joins(:special_comments_ratings_taggings).where(:id => posts(:sti_comments).id) + scope = Post.joins(:special_comments_ratings_taggings).where(id: posts(:sti_comments).id) assert scope.where("comments.type" => "Comment").empty? assert !scope.where("comments.type" => "SpecialComment").empty? end diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index f0b1f0bbe8..b600bf2835 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -25,32 +25,32 @@ class AssociationsTest < ActiveRecord::TestCase :computers, :people, :readers, :authors, :author_favorites def test_eager_loading_should_not_change_count_of_children - liquid = Liquid.create(:name => "salty") - molecule = liquid.molecules.create(:name => "molecule_1") - molecule.electrons.create(:name => "electron_1") - molecule.electrons.create(:name => "electron_2") + liquid = Liquid.create(name: "salty") + molecule = liquid.molecules.create(name: "molecule_1") + molecule.electrons.create(name: "electron_1") + molecule.electrons.create(name: "electron_2") - liquids = Liquid.includes(:molecules => :electrons).references(:molecules).where("molecules.id is not null") + liquids = Liquid.includes(molecules: :electrons).references(:molecules).where("molecules.id is not null") assert_equal 1, liquids[0].molecules.length end def test_subselect author = authors :david favs = author.author_favorites - fav2 = author.author_favorites.where(:author => Author.where(id: author.id)).to_a + fav2 = author.author_favorites.where(author: Author.where(id: author.id)).to_a assert_equal favs, fav2 end def test_loading_the_association_target_should_keep_child_records_marked_for_destruction - ship = Ship.create!(:name => "The good ship Dollypop") - part = ship.parts.create!(:name => "Mast") + ship = Ship.create!(name: "The good ship Dollypop") + part = ship.parts.create!(name: "Mast") part.mark_for_destruction assert ship.parts[0].marked_for_destruction? end def test_loading_the_association_target_should_load_most_recent_attributes_for_child_records_marked_for_destruction - ship = Ship.create!(:name => "The good ship Dollypop") - part = ship.parts.create!(:name => "Mast") + ship = Ship.create!(name: "The good ship Dollypop") + part = ship.parts.create!(name: "Mast") part.mark_for_destruction ShipPart.find(part.id).update_columns(name: "Deck") assert_equal "Deck", ship.parts[0].name @@ -58,21 +58,21 @@ def test_loading_the_association_target_should_load_most_recent_attributes_for_c def test_include_with_order_works - assert_nothing_raised {Account.all.merge!(:order => "id", :includes => :firm).first} - assert_nothing_raised {Account.all.merge!(:order => :id, :includes => :firm).first} + assert_nothing_raised {Account.all.merge!(order: "id", includes: :firm).first} + assert_nothing_raised {Account.all.merge!(order: :id, includes: :firm).first} end def test_bad_collection_keys assert_raise(ArgumentError, "ActiveRecord should have barked on bad collection keys") do - Class.new(ActiveRecord::Base).has_many(:wheels, :name => "wheels") + Class.new(ActiveRecord::Base).has_many(:wheels, name: "wheels") end end def test_should_construct_new_finder_sql_after_create - person = Person.new :first_name => "clark" + person = Person.new first_name: "clark" assert_equal [], person.readers.to_a person.save! - reader = Reader.create! :person => person, :post => Post.new(:title => "foo", :body => "bar") + reader = Reader.create! person: person, post: Post.new(title: "foo", body: "bar") assert person.readers.find(reader.id) end @@ -131,7 +131,7 @@ class AssociationProxyTest < ActiveRecord::TestCase def test_push_does_not_load_target david = authors(:david) - david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!")) + david.posts << (post = Post.new(title: "New on Edge", body: "More cool stuff!")) assert !david.posts.loaded? assert david.posts.include?(post) end @@ -147,7 +147,7 @@ def test_push_has_many_through_does_not_load_target def test_push_followed_by_save_does_not_load_target david = authors(:david) - david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!")) + david.posts << (post = Post.new(title: "New on Edge", body: "More cool stuff!")) assert !david.posts.loaded? david.save assert !david.posts.loaded? @@ -155,21 +155,21 @@ def test_push_followed_by_save_does_not_load_target end def test_push_does_not_lose_additions_to_new_record - josh = Author.new(:name => "Josh") - josh.posts << Post.new(:title => "New on Edge", :body => "More cool stuff!") + josh = Author.new(name: "Josh") + josh.posts << Post.new(title: "New on Edge", body: "More cool stuff!") assert josh.posts.loaded? assert_equal 1, josh.posts.size end def test_append_behaves_like_push - josh = Author.new(:name => "Josh") - josh.posts.append Post.new(:title => "New on Edge", :body => "More cool stuff!") + josh = Author.new(name: "Josh") + josh.posts.append Post.new(title: "New on Edge", body: "More cool stuff!") assert josh.posts.loaded? assert_equal 1, josh.posts.size end def test_prepend_is_not_defined - josh = Author.new(:name => "Josh") + josh = Author.new(name: "Josh") assert_raises(NoMethodError) { josh.posts.prepend Post.new } end @@ -190,24 +190,24 @@ def test_load_does_load_target end def test_inspect_does_not_reload_a_not_yet_loaded_target - andreas = Developer.new :name => "Andreas", :log => "new developer added" + andreas = Developer.new name: "Andreas", log: "new developer added" assert !andreas.audit_logs.loaded? assert_match(/message: "new developer added"/, andreas.audit_logs.inspect) end def test_save_on_parent_saves_children - developer = Developer.create :name => "Bryan", :salary => 50_000 + developer = Developer.create name: "Bryan", salary: 50_000 assert_equal 1, developer.reload.audit_logs.size end def test_create_via_association_with_block - post = authors(:david).posts.create(:title => "New on Edge") {|p| p.body = "More cool stuff!"} + post = authors(:david).posts.create(title: "New on Edge") {|p| p.body = "More cool stuff!"} assert_equal post.title, "New on Edge" assert_equal post.body, "More cool stuff!" end def test_create_with_bang_via_association_with_block - post = authors(:david).posts.create!(:title => "New on Edge") {|p| p.body = "More cool stuff!"} + post = authors(:david).posts.create!(title: "New on Edge") {|p| p.body = "More cool stuff!"} assert_equal post.title, "New on Edge" assert_equal post.body, "More cool stuff!" end @@ -272,18 +272,18 @@ class OverridingAssociationsTest < ActiveRecord::TestCase class DifferentPerson < ActiveRecord::Base; end class PeopleList < ActiveRecord::Base - has_and_belongs_to_many :has_and_belongs_to_many, :before_add => :enlist - has_many :has_many, :before_add => :enlist + has_and_belongs_to_many :has_and_belongs_to_many, before_add: :enlist + has_many :has_many, before_add: :enlist belongs_to :belongs_to has_one :has_one end class DifferentPeopleList < PeopleList # Different association with the same name, callbacks should be omitted here. - has_and_belongs_to_many :has_and_belongs_to_many, :class_name => "DifferentPerson" - has_many :has_many, :class_name => "DifferentPerson" - belongs_to :belongs_to, :class_name => "DifferentPerson" - has_one :has_one, :class_name => "DifferentPerson" + has_and_belongs_to_many :has_and_belongs_to_many, class_name: "DifferentPerson" + has_many :has_many, class_name: "DifferentPerson" + belongs_to :belongs_to, class_name: "DifferentPerson" + has_one :has_one, class_name: "DifferentPerson" end def test_habtm_association_redefinition_callbacks_should_differ_and_not_inherited diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index cb45079597..d09e4cae3b 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -31,7 +31,7 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase def test_autosave_validation person = Class.new(ActiveRecord::Base) { self.table_name = "people" - validate :should_be_cool, :on => :create + validate :should_be_cool, on: :create def self.name; "Person"; end private @@ -97,7 +97,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas fixtures :companies, :accounts def test_should_save_parent_but_not_invalid_child - firm = Firm.new(:name => "GlobalMegaCorp") + firm = Firm.new(name: "GlobalMegaCorp") assert firm.valid? firm.build_account_using_primary_key @@ -178,7 +178,7 @@ def test_assignment_before_either_saved end def test_not_resaved_when_unchanged - firm = Firm.all.merge!(:includes => :account).first + firm = Firm.all.merge!(includes: :account).first firm.name += "-changed" assert_queries(1) { firm.save! } @@ -196,7 +196,7 @@ def test_not_resaved_when_unchanged end def test_callbacks_firing_order_on_create - eye = Eye.create(:iris_attributes => {:color => "honey"}) + eye = Eye.create(iris_attributes: {color: "honey"}) assert_equal [true, false], eye.after_create_callbacks_stack end @@ -219,7 +219,7 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test fixtures :companies, :posts, :tags, :taggings def test_should_save_parent_but_not_invalid_child - client = Client.new(:name => "Joe (the Plumber)") + client = Client.new(name: "Joe (the Plumber)") assert client.valid? client.build_firm @@ -231,7 +231,7 @@ def test_should_save_parent_but_not_invalid_child def test_save_fails_for_invalid_belongs_to # Oracle saves empty string as NULL therefore :message changed to one space - assert log = AuditLog.create(:developer_id => 0, :message => " ") + assert log = AuditLog.create(developer_id: 0, message: " ") log.developer = Developer.new assert !log.developer.valid? @@ -242,7 +242,7 @@ def test_save_fails_for_invalid_belongs_to def test_save_succeeds_for_invalid_belongs_to_with_validate_false # Oracle saves empty string as NULL therefore :message changed to one space - assert log = AuditLog.create(:developer_id => 0, :message=> " ") + assert log = AuditLog.create(developer_id: 0, message: " ") log.unvalidated_developer = Developer.new assert !log.unvalidated_developer.valid? @@ -362,22 +362,22 @@ def test_store_association_in_two_relations_with_one_save_in_existing_object_wit def test_store_association_with_a_polymorphic_relationship num_tagging = Tagging.count - tags(:misc).create_tagging(:taggable => posts(:thinking)) + tags(:misc).create_tagging(taggable: posts(:thinking)) assert_equal num_tagging + 1, Tagging.count end def test_build_and_then_save_parent_should_not_reload_target client = Client.first - apple = client.build_firm(:name => "Apple") + apple = client.build_firm(name: "Apple") client.save! assert_no_queries { assert_equal apple, client.firm } end def test_validation_does_not_validate_stale_association_target - valid_developer = Developer.create!(:name => "Dude", :salary => 50_000) + valid_developer = Developer.create!(name: "Dude", salary: 50_000) invalid_developer = Developer.new() - auditlog = AuditLog.new(:message => "foo") + auditlog = AuditLog.new(message: "foo") auditlog.developer = invalid_developer auditlog.developer_id = valid_developer.id @@ -589,7 +589,7 @@ def test_assign_ids end def test_assign_ids_for_through_a_belongs_to - post = Post.new(:title => "Assigning IDs works!", :body => "You heard it here first, folks!") + post = Post.new(title: "Assigning IDs works!", body: "You heard it here first, folks!") post.person_ids = [people(:david).id, people(:michael).id] post.save post.reload @@ -727,8 +727,8 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase self.use_transactional_tests = false setup do - @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @ship = @pirate.create_ship(:name => "Nights Dirty Lightning") + @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?") + @ship = @pirate.create_ship(name: "Nights Dirty Lightning") end teardown do @@ -858,8 +858,8 @@ def save(*args) end def test_should_save_changed_child_objects_if_parent_is_saved - @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @parrot = @pirate.parrots.create!(:name => "Posideons Killer") + @pirate = @ship.create_pirate(catchphrase: "Don' botharrr talkin' like one, savvy?") + @parrot = @pirate.parrots.create!(name: "Posideons Killer") @parrot.name = "NewName" @ship.save @@ -867,7 +867,7 @@ def test_should_save_changed_child_objects_if_parent_is_saved end def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction - 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") } + 2.times { |i| @pirate.birds.create!(name: "birds_#{i}") } assert !@pirate.birds.any?(&:marked_for_destruction?) @@ -891,7 +891,7 @@ def test_should_not_resave_destroyed_association end def test_should_skip_validation_on_has_many_if_marked_for_destruction - 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") } + 2.times { |i| @pirate.birds.create!(name: "birds_#{i}") } @pirate.birds.each { |bird| bird.name = "" } assert !@pirate.valid? @@ -904,7 +904,7 @@ def test_should_skip_validation_on_has_many_if_marked_for_destruction end def test_should_skip_validation_on_has_many_if_destroyed - @pirate.birds.create!(:name => "birds_1") + @pirate.birds.create!(name: "birds_1") @pirate.birds.each { |bird| bird.name = "" } assert !@pirate.valid? @@ -914,7 +914,7 @@ def test_should_skip_validation_on_has_many_if_destroyed end def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many - @pirate.birds.create!(:name => "birds_1") + @pirate.birds.create!(name: "birds_1") @pirate.birds.each(&:mark_for_destruction) assert @pirate.save @@ -924,7 +924,7 @@ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_savi end def test_should_rollback_destructions_if_an_exception_occurred_while_saving_has_many - 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") } + 2.times { |i| @pirate.birds.create!(name: "birds_#{i}") } before = @pirate.birds.map { |c| c.mark_for_destruction ; c } # Stub the destroy method of the second child to raise an exception @@ -940,9 +940,9 @@ def destroy(*args) end def test_when_new_record_a_child_marked_for_destruction_should_not_affect_other_records_from_saving - @pirate = @ship.build_pirate(:catchphrase => "Arr' now I shall keep me eye on you matey!") # new record + @pirate = @ship.build_pirate(catchphrase: "Arr' now I shall keep me eye on you matey!") # new record - 3.times { |i| @pirate.birds.build(:name => "birds_#{i}") } + 3.times { |i| @pirate.birds.build(name: "birds_#{i}") } @pirate.birds[1].mark_for_destruction @pirate.save! @@ -968,8 +968,8 @@ def test_should_save_new_record_that_has_same_value_as_existing_record_marked_fo define_method("test_should_run_add_callback_#{callback_type}s_for_has_many") do association_name_with_callbacks = "birds_with_#{callback_type}_callbacks" - pirate = Pirate.new(:catchphrase => "Arr") - pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed") + pirate = Pirate.new(catchphrase: "Arr") + pirate.send(association_name_with_callbacks).build(name: "Crowe the One-Eyed") expected = [ "before_adding_#{callback_type}_bird_", @@ -982,7 +982,7 @@ def test_should_save_new_record_that_has_same_value_as_existing_record_marked_fo define_method("test_should_run_remove_callback_#{callback_type}s_for_has_many") do association_name_with_callbacks = "birds_with_#{callback_type}_callbacks" - @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed") + @pirate.send(association_name_with_callbacks).create!(name: "Crowe the One-Eyed") @pirate.send(association_name_with_callbacks).each(&:mark_for_destruction) child_id = @pirate.send(association_name_with_callbacks).first.id @@ -999,7 +999,7 @@ def test_should_save_new_record_that_has_same_value_as_existing_record_marked_fo end def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction - 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } + 2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") } assert !@pirate.parrots.any?(&:marked_for_destruction?) @pirate.parrots.each(&:mark_for_destruction) @@ -1015,7 +1015,7 @@ def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marke end def test_should_skip_validation_on_habtm_if_marked_for_destruction - 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } + 2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") } @pirate.parrots.each { |parrot| parrot.name = "" } assert !@pirate.valid? @@ -1030,7 +1030,7 @@ def test_should_skip_validation_on_habtm_if_marked_for_destruction end def test_should_skip_validation_on_habtm_if_destroyed - @pirate.parrots.create!(:name => "parrots_1") + @pirate.parrots.create!(name: "parrots_1") @pirate.parrots.each { |parrot| parrot.name = "" } assert !@pirate.valid? @@ -1040,7 +1040,7 @@ def test_should_skip_validation_on_habtm_if_destroyed end def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm - @pirate.parrots.create!(:name => "parrots_1") + @pirate.parrots.create!(name: "parrots_1") @pirate.parrots.each(&:mark_for_destruction) assert @pirate.save @@ -1053,7 +1053,7 @@ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_savi end def test_should_rollback_destructions_if_an_exception_occurred_while_saving_habtm - 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } + 2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") } before = @pirate.parrots.map { |c| c.mark_for_destruction ; c } class << @pirate.association(:parrots) @@ -1072,8 +1072,8 @@ def destroy(*args) define_method("test_should_run_add_callback_#{callback_type}s_for_habtm") do association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks" - pirate = Pirate.new(:catchphrase => "Arr") - pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed") + pirate = Pirate.new(catchphrase: "Arr") + pirate.send(association_name_with_callbacks).build(name: "Crowe the One-Eyed") expected = [ "before_adding_#{callback_type}_parrot_", @@ -1086,7 +1086,7 @@ def destroy(*args) define_method("test_should_run_remove_callback_#{callback_type}s_for_habtm") do association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks" - @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed") + @pirate.send(association_name_with_callbacks).create!(name: "Crowe the One-Eyed") @pirate.send(association_name_with_callbacks).each(&:mark_for_destruction) child_id = @pirate.send(association_name_with_callbacks).first.id @@ -1108,8 +1108,8 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase def setup super - @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @ship = @pirate.create_ship(:name => "Nights Dirty Lightning") + @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?") + @ship = @pirate.create_ship(name: "Nights Dirty Lightning") end def test_should_still_work_without_an_associated_model @@ -1158,7 +1158,7 @@ def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it def test_should_not_ignore_different_error_messages_on_the_same_attribute old_validators = Ship._validators.deep_dup old_callbacks = Ship._validate_callbacks.deep_dup - Ship.validates_format_of :name, :with => /\w/ + Ship.validates_format_of :name, with: /\w/ @pirate.ship.name = "" @pirate.catchphrase = nil assert @pirate.invalid? @@ -1171,7 +1171,7 @@ def test_should_not_ignore_different_error_messages_on_the_same_attribute def test_should_still_allow_to_bypass_validations_on_the_associated_model @pirate.catchphrase = "" @pirate.ship.name = "" - @pirate.save(:validate => false) + @pirate.save(validate: false) # Oracle saves empty string as NULL if current_adapter?(:OracleAdapter) assert_equal [nil, nil], [@pirate.reload.catchphrase, @pirate.ship.name] @@ -1181,12 +1181,12 @@ def test_should_still_allow_to_bypass_validations_on_the_associated_model end def test_should_allow_to_bypass_validations_on_associated_models_at_any_depth - 2.times { |i| @pirate.ship.parts.create!(:name => "part #{i}") } + 2.times { |i| @pirate.ship.parts.create!(name: "part #{i}") } @pirate.catchphrase = "" @pirate.ship.name = "" @pirate.ship.parts.each { |part| part.name = "" } - @pirate.save(:validate => false) + @pirate.save(validate: false) values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)] # Oracle saves empty string as NULL @@ -1205,8 +1205,8 @@ def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_t end def test_should_not_save_and_return_false_if_a_callback_cancelled_saving - pirate = Pirate.new(:catchphrase => "Arr") - ship = pirate.build_ship(:name => "The Vile Insanity") + pirate = Pirate.new(catchphrase: "Arr") + ship = pirate.build_ship(name: "The Vile Insanity") ship.cancel_save_from_callback = true assert_no_difference "Pirate.count" do @@ -1272,8 +1272,8 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase def setup super - @ship = Ship.create(:name => "Nights Dirty Lightning") - @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?") + @ship = Ship.create(name: "Nights Dirty Lightning") + @pirate = @ship.create_pirate(catchphrase: "Don' botharrr talkin' like one, savvy?") end def test_should_still_work_without_an_associated_model @@ -1312,7 +1312,7 @@ def test_should_merge_errors_on_the_associated_model_onto_the_parent_even_if_it_ def test_should_still_allow_to_bypass_validations_on_the_associated_model @ship.pirate.catchphrase = "" @ship.name = "" - @ship.save(:validate => false) + @ship.save(validate: false) # Oracle saves empty string as NULL if current_adapter?(:OracleAdapter) assert_equal [nil, nil], [@ship.reload.name, @ship.pirate.catchphrase] @@ -1329,8 +1329,8 @@ def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_t end def test_should_not_save_and_return_false_if_a_callback_cancelled_saving - ship = Ship.new(:name => "The Vile Insanity") - pirate = ship.build_pirate(:catchphrase => "Arr") + ship = Ship.new(name: "The Vile Insanity") + pirate = ship.build_pirate(catchphrase: "Arr") pirate.cancel_save_from_callback = true assert_no_difference "Ship.count" do @@ -1399,7 +1399,7 @@ def test_should_automatically_validate_the_associated_models end def test_should_not_use_default_invalid_error_on_associated_models - @pirate.send(@association_name).build(:name => "") + @pirate.send(@association_name).build(name: "") assert !@pirate.valid? assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"] @@ -1434,7 +1434,7 @@ def test_should_allow_to_bypass_validations_on_the_associated_models_on_update @pirate.catchphrase = "" @pirate.send(@association_name).each { |child| child.name = "" } - assert @pirate.save(:validate => false) + assert @pirate.save(validate: false) # Oracle saves empty string as NULL if current_adapter?(:OracleAdapter) assert_equal [nil, nil, nil], [ @@ -1461,7 +1461,7 @@ def test_should_validation_the_associated_models_on_create def test_should_allow_to_bypass_validations_on_the_associated_models_on_create assert_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count", 2) do 2.times { @pirate.send(@association_name).build } - @pirate.save(:validate => false) + @pirate.save(validate: false) end end @@ -1474,8 +1474,8 @@ def test_should_not_save_and_return_false_if_a_callback_cancelled_saving_in_eith assert_equal "Don' botharrr talkin' like one, savvy?", @pirate.reload.catchphrase assert_equal "Posideons Killer", @child_1.reload.name - new_pirate = Pirate.new(:catchphrase => "Arr") - new_child = new_pirate.send(@association_name).build(:name => "Grace OMalley") + new_pirate = Pirate.new(catchphrase: "Arr") + new_child = new_pirate.send(@association_name).build(name: "Grace OMalley") new_child.cancel_save_from_callback = true assert_no_difference "Pirate.count" do @@ -1533,9 +1533,9 @@ def setup @association_name = :birds @associated_model_name = :bird - @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @child_1 = @pirate.birds.create(:name => "Posideons Killer") - @child_2 = @pirate.birds.create(:name => "Killer bandita Dionne") + @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?") + @child_1 = @pirate.birds.create(name: "Posideons Killer") + @child_2 = @pirate.birds.create(name: "Killer bandita Dionne") end include AutosaveAssociationOnACollectionAssociationTests @@ -1580,8 +1580,8 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te def setup super - @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @pirate.birds.create(:name => "cookoo") + @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?") + @pirate.birds.create(name: "cookoo") end test "should automatically validate associations" do @@ -1597,8 +1597,8 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes def setup super - @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @pirate.create_ship(:name => "titanic") + @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?") + @pirate.create_ship(name: "titanic") super end @@ -1620,18 +1620,18 @@ class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord:: def setup super - @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") + @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?") end test "should automatically validate associations with :validate => true" do assert @pirate.valid? - @pirate.parrot = Parrot.new(:name => "") + @pirate.parrot = Parrot.new(name: "") assert !@pirate.valid? end test "should not automatically validate associations without :validate => true" do assert @pirate.valid? - @pirate.non_validated_parrot = Parrot.new(:name => "") + @pirate.non_validated_parrot = Parrot.new(name: "") assert @pirate.valid? end end @@ -1641,19 +1641,19 @@ class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::Test def setup super - @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") + @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?") end test "should automatically validate associations with :validate => true" do assert @pirate.valid? - @pirate.parrots = [ Parrot.new(:name => "popuga") ] + @pirate.parrots = [ Parrot.new(name: "popuga") ] @pirate.parrots.each { |parrot| parrot.name = "" } assert !@pirate.valid? end test "should not automatically validate associations without :validate => true" do assert @pirate.valid? - @pirate.non_validated_parrots = [ Parrot.new(:name => "popuga") ] + @pirate.non_validated_parrots = [ Parrot.new(name: "popuga") ] @pirate.non_validated_parrots.each { |parrot| parrot.name = "" } assert @pirate.valid? end @@ -1695,6 +1695,6 @@ def setup class TestAutosaveAssociationWithTouch < ActiveRecord::TestCase def test_autosave_with_touch_should_not_raise_system_stack_error invoice = Invoice.create - assert_nothing_raised { invoice.line_items.create(:amount => 10) } + assert_nothing_raised { invoice.line_items.create(amount: 10) } end end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 96de9fe8d5..e26b2445b8 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -295,7 +295,7 @@ def test_initialize_with_invalid_attribute end def test_create_after_initialize_without_block - cb = CustomBulb.create(:name => "Dude") + cb = CustomBulb.create(name: "Dude") assert_equal("Dude", cb.name) assert_equal(true, cb.frickinawesome) end @@ -315,13 +315,13 @@ def test_create_after_initialize_with_array_param end def test_load - topics = Topic.all.merge!(:order => "id").to_a + topics = Topic.all.merge!(order: "id").to_a assert_equal(5, topics.size) assert_equal(topics(:first).title, topics.first.title) end def test_load_with_condition - topics = Topic.all.merge!(:where => "author_name = 'Mary'").to_a + topics = Topic.all.merge!(where: "author_name = 'Mary'").to_a assert_equal(1, topics.size) assert_equal(topics(:second).title, topics.first.title) @@ -443,7 +443,7 @@ def test_singular_table_name_guesses_for_individual_table if current_adapter?(:Mysql2Adapter) def test_update_all_with_order_and_limit - assert_equal 1, Topic.limit(1).order("id DESC").update_all(:content => "bulk updated!") + assert_equal 1, Topic.limit(1).order("id DESC").update_all(content: "bulk updated!") end end @@ -536,7 +536,7 @@ def test_equality_of_new_records end def test_equality_of_destroyed_records - topic_1 = Topic.new(:title => "test_1") + topic_1 = Topic.new(title: "test_1") topic_1.save topic_2 = Topic.find(topic_1.id) topic_1.destroy @@ -545,8 +545,8 @@ def test_equality_of_destroyed_records end def test_equality_with_blank_ids - one = Subscriber.new(:id => "") - two = Subscriber.new(:id => "") + one = Subscriber.new(id: "") + two = Subscriber.new(id: "") assert_equal one, two end @@ -604,7 +604,7 @@ def test_failed_comparison_of_unlike_class_records def test_create_without_prepared_statement topic = Topic.connection.unprepared_statement do - Topic.create(:title => "foo") + Topic.create(title: "foo") end assert_equal topic, Topic.find(topic.id) @@ -621,7 +621,7 @@ def test_destroy_without_prepared_statement def test_comparison_with_different_objects topic = Topic.create - category = Category.create(:name => "comparison") + category = Category.create(name: "comparison") assert_nil topic <=> category end @@ -635,7 +635,7 @@ def test_comparison_with_different_objects_in_array def test_readonly_attributes assert_equal Set.new([ "title" , "comments_count" ]), ReadonlyTitlePost.readonly_attributes - post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable") + post = ReadonlyTitlePost.create(title: "cannot change this", body: "changeable") post.reload assert_equal "cannot change this", post.title @@ -647,7 +647,7 @@ def test_readonly_attributes def test_unicode_column_name Weird.reset_column_information - weird = Weird.create(:ãªã¾ãˆ => "ãŸã“焼ãä»®é¢") + weird = Weird.create(ãªã¾ãˆ: "ãŸã“焼ãä»®é¢") assert_equal "ãŸã“焼ãä»®é¢", weird.ãªã¾ãˆ end @@ -790,7 +790,7 @@ def test_dup def test_dup_with_aggregate_of_same_name_as_attribute developer_with_aggregate = Class.new(ActiveRecord::Base) do self.table_name = "developers" - composed_of :salary, :class_name => "BasicsTest::DeveloperSalary", :mapping => [%w(salary amount)] + composed_of :salary, class_name: "BasicsTest::DeveloperSalary", mapping: [%w(salary amount)] end dev = developer_with_aggregate.find(1) @@ -837,7 +837,7 @@ def test_clone_of_new_object_with_defaults end def test_clone_of_new_object_marks_attributes_as_dirty - developer = Developer.new :name => "Bjorn", :salary => 100000 + developer = Developer.new name: "Bjorn", salary: 100000 assert developer.name_changed? assert developer.salary_changed? @@ -847,7 +847,7 @@ def test_clone_of_new_object_marks_attributes_as_dirty end def test_clone_of_new_object_marks_as_dirty_only_changed_attributes - developer = Developer.new :name => "Bjorn" + developer = Developer.new name: "Bjorn" assert developer.name_changed? # obviously assert !developer.salary_changed? # attribute has non-nil default value, so treated as not changed @@ -857,7 +857,7 @@ def test_clone_of_new_object_marks_as_dirty_only_changed_attributes end def test_dup_of_saved_object_marks_attributes_as_dirty - developer = Developer.create! :name => "Bjorn", :salary => 100000 + developer = Developer.create! name: "Bjorn", salary: 100000 assert !developer.name_changed? assert !developer.salary_changed? @@ -867,7 +867,7 @@ def test_dup_of_saved_object_marks_attributes_as_dirty end def test_dup_of_saved_object_marks_as_dirty_only_changed_attributes - developer = Developer.create! :name => "Bjorn" + developer = Developer.create! name: "Bjorn" assert !developer.name_changed? # both attributes of saved object should be treated as not changed assert !developer.salary_changed? @@ -911,10 +911,10 @@ class NumericData < ActiveRecord::Base def test_big_decimal_conditions m = NumericData.new( - :bank_balance => 1586.43, - :big_bank_balance => BigDecimal("1000234000567.95"), - :world_population => 6000000000, - :my_house_population => 3 + bank_balance: 1586.43, + big_bank_balance: BigDecimal("1000234000567.95"), + world_population: 6000000000, + my_house_population: 3 ) assert m.save assert_equal 0, NumericData.where("bank_balance > ?", 2000.0).count @@ -922,10 +922,10 @@ def test_big_decimal_conditions def test_numeric_fields m = NumericData.new( - :bank_balance => 1586.43, - :big_bank_balance => BigDecimal("1000234000567.95"), - :world_population => 6000000000, - :my_house_population => 3 + bank_balance: 1586.43, + big_bank_balance: BigDecimal("1000234000567.95"), + world_population: 6000000000, + my_house_population: 3 ) assert m.save @@ -950,10 +950,10 @@ def test_numeric_fields def test_numeric_fields_with_scale m = NumericData.new( - :bank_balance => 1586.43122334, - :big_bank_balance => BigDecimal("234000567.952344"), - :world_population => 6000000000, - :my_house_population => 3 + bank_balance: 1586.43122334, + big_bank_balance: BigDecimal("234000567.952344"), + world_population: 6000000000, + my_house_population: 3 ) assert m.save @@ -999,10 +999,10 @@ def test_column_name_properly_quoted end def test_quoting_arrays - replies = Reply.all.merge!(:where => [ "id IN (?)", topics(:first).replies.collect(&:id) ]).to_a + replies = Reply.all.merge!(where: [ "id IN (?)", topics(:first).replies.collect(&:id) ]).to_a assert_equal topics(:first).replies.size, replies.size - replies = Reply.all.merge!(:where => [ "id IN (?)", [] ]).to_a + replies = Reply.all.merge!(where: [ "id IN (?)", [] ]).to_a assert_equal 0, replies.size end @@ -1149,17 +1149,17 @@ def test_count_with_join def test_no_limit_offset assert_nothing_raised do - Developer.all.merge!(:offset => 2).to_a + Developer.all.merge!(offset: 2).to_a end end def test_find_last last = Developer.last - assert_equal last, Developer.all.merge!(:order => "id desc").first + assert_equal last, Developer.all.merge!(order: "id desc").first end def test_last - assert_equal Developer.all.merge!(:order => "id desc").first, Developer.last + assert_equal Developer.all.merge!(order: "id desc").first, Developer.last end def test_all @@ -1169,37 +1169,37 @@ def test_all end def test_all_with_conditions - assert_equal Developer.all.merge!(:order => "id desc").to_a, Developer.order("id desc").to_a + assert_equal Developer.all.merge!(order: "id desc").to_a, Developer.order("id desc").to_a end def test_find_ordered_last - last = Developer.all.merge!(:order => "developers.salary ASC").last - assert_equal last, Developer.all.merge!(:order => "developers.salary ASC").to_a.last + last = Developer.all.merge!(order: "developers.salary ASC").last + assert_equal last, Developer.all.merge!(order: "developers.salary ASC").to_a.last end def test_find_reverse_ordered_last - last = Developer.all.merge!(:order => "developers.salary DESC").last - assert_equal last, Developer.all.merge!(:order => "developers.salary DESC").to_a.last + last = Developer.all.merge!(order: "developers.salary DESC").last + assert_equal last, Developer.all.merge!(order: "developers.salary DESC").to_a.last end def test_find_multiple_ordered_last - last = Developer.all.merge!(:order => "developers.name, developers.salary DESC").last - assert_equal last, Developer.all.merge!(:order => "developers.name, developers.salary DESC").to_a.last + last = Developer.all.merge!(order: "developers.name, developers.salary DESC").last + assert_equal last, Developer.all.merge!(order: "developers.name, developers.salary DESC").to_a.last end def test_find_keeps_multiple_order_values - combined = Developer.all.merge!(:order => "developers.name, developers.salary").to_a - assert_equal combined, Developer.all.merge!(:order => ["developers.name", "developers.salary"]).to_a + combined = Developer.all.merge!(order: "developers.name, developers.salary").to_a + assert_equal combined, Developer.all.merge!(order: ["developers.name", "developers.salary"]).to_a end def test_find_keeps_multiple_group_values - combined = Developer.all.merge!(:group => "developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at, developers.created_on, developers.updated_on").to_a - assert_equal combined, Developer.all.merge!(:group => ["developers.name", "developers.salary", "developers.id", "developers.created_at", "developers.updated_at", "developers.created_on", "developers.updated_on"]).to_a + combined = Developer.all.merge!(group: "developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at, developers.created_on, developers.updated_on").to_a + assert_equal combined, Developer.all.merge!(group: ["developers.name", "developers.salary", "developers.id", "developers.created_at", "developers.updated_at", "developers.created_on", "developers.updated_on"]).to_a end def test_find_symbol_ordered_last - last = Developer.all.merge!(:order => :salary).last - assert_equal last, Developer.all.merge!(:order => :salary).to_a.last + last = Developer.all.merge!(order: :salary).last + assert_equal last, Developer.all.merge!(order: :salary).to_a.last end def test_abstract_class_table_name @@ -1210,7 +1210,7 @@ def test_find_on_abstract_base_class_doesnt_use_type_condition old_class = LooseDescendant Object.send :remove_const, :LooseDescendant - descendant = old_class.create! :first_name => "bob" + descendant = old_class.create! first_name: "bob" assert_not_nil LoosePerson.find(descendant.id), "Should have found instance of LooseDescendant when finding abstract LoosePerson: #{descendant.inspect}" ensure unless Object.const_defined?(:LooseDescendant) @@ -1230,9 +1230,9 @@ def test_benchmark_with_log_level log = StringIO.new ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.logger.level = Logger::WARN - ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count } - ActiveRecord::Base.benchmark("Warn Topic Count", :level => :warn) { Topic.count } - ActiveRecord::Base.benchmark("Error Topic Count", :level => :error) { Topic.count } + ActiveRecord::Base.benchmark("Debug Topic Count", level: :debug) { Topic.count } + ActiveRecord::Base.benchmark("Warn Topic Count", level: :warn) { Topic.count } + ActiveRecord::Base.benchmark("Error Topic Count", level: :error) { Topic.count } assert_no_match(/Debug Topic Count/, log.string) assert_match(/Warn Topic Count/, log.string) assert_match(/Error Topic Count/, log.string) @@ -1245,7 +1245,7 @@ def test_benchmark_with_use_silence log = StringIO.new ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.logger.level = Logger::DEBUG - ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false) { ActiveRecord::Base.logger.debug "Quiet" } + ActiveRecord::Base.benchmark("Logging", level: :debug, silence: false) { ActiveRecord::Base.logger.debug "Quiet" } assert_match(/Quiet/, log.string) ensure ActiveRecord::Base.logger = original_logger @@ -1367,7 +1367,7 @@ def test_attribute_names_on_abstract_class end def test_touch_should_raise_error_on_a_new_object - company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals") + company = Company.new(rating: 1, name: "37signals", firm_name: "37signals") assert_raises(ActiveRecord::ActiveRecordError) do company.touch :updated_at end @@ -1411,7 +1411,7 @@ def test_typecasting_aliases end def test_slice - company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals") + company = Company.new(rating: 1, name: "37signals", firm_name: "37signals") hash = company.slice(:name, :rating, "arbitrary_method") assert_equal hash[:name], company.name assert_equal hash["name"], company.name diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb index c48c356773..077e6d0bc0 100644 --- a/activerecord/test/cases/batches_test.rb +++ b/activerecord/test/cases/batches_test.rb @@ -13,7 +13,7 @@ def setup def test_each_should_execute_one_query_per_batch assert_queries(@total + 1) do - Post.find_each(:batch_size => 1) do |post| + Post.find_each(batch_size: 1) do |post| assert_kind_of Post, post end end @@ -21,14 +21,14 @@ def test_each_should_execute_one_query_per_batch def test_each_should_not_return_query_chain_and_execute_only_one_query assert_queries(1) do - result = Post.find_each(:batch_size => 100000){ } + result = Post.find_each(batch_size: 100000){ } assert_nil result end end def test_each_should_return_an_enumerator_if_no_block_is_present assert_queries(1) do - Post.find_each(:batch_size => 100000).with_index do |post, index| + Post.find_each(batch_size: 100000).with_index do |post, index| assert_kind_of Post, post assert_kind_of Integer, index end @@ -45,7 +45,7 @@ def test_each_should_return_a_sized_enumerator def test_each_enumerator_should_execute_one_query_per_batch assert_queries(@total + 1) do - Post.find_each(:batch_size => 1).with_index do |post, index| + Post.find_each(batch_size: 1).with_index do |post, index| assert_kind_of Post, post assert_kind_of Integer, index end @@ -62,7 +62,7 @@ def test_each_should_raise_if_select_is_set_without_id def test_each_should_execute_if_id_is_in_select assert_queries(6) do - Post.select("id, title, type").find_each(:batch_size => 2) do |post| + Post.select("id, title, type").find_each(batch_size: 2) do |post| assert_kind_of Post, post end end @@ -108,7 +108,7 @@ def test_logger_not_required def test_find_in_batches_should_return_batches assert_queries(@total + 1) do - Post.find_in_batches(:batch_size => 1) do |batch| + Post.find_in_batches(batch_size: 1) do |batch| assert_kind_of Array, batch assert_kind_of Post, batch.first end @@ -135,18 +135,18 @@ def test_find_in_batches_should_end_at_the_finish_option def test_find_in_batches_shouldnt_execute_query_unless_needed assert_queries(2) do - Post.find_in_batches(:batch_size => @total) {|batch| assert_kind_of Array, batch } + Post.find_in_batches(batch_size: @total) {|batch| assert_kind_of Array, batch } end assert_queries(1) do - Post.find_in_batches(:batch_size => @total + 1) {|batch| assert_kind_of Array, batch } + Post.find_in_batches(batch_size: @total + 1) {|batch| assert_kind_of Array, batch } end end def test_find_in_batches_should_quote_batch_order c = Post.connection assert_sql(/ORDER BY #{c.quote_table_name('posts')}.#{c.quote_column_name('id')}/) do - Post.find_in_batches(:batch_size => 1) do |batch| + Post.find_in_batches(batch_size: 1) do |batch| assert_kind_of Array, batch assert_kind_of Post, batch.first end @@ -158,7 +158,7 @@ def test_find_in_batches_should_not_use_records_after_yielding_them_in_case_orig def not_a_post.id; end not_a_post.stub(:id, ->{ raise StandardError.new("not_a_post had #id called on it") }) do assert_nothing_raised do - Post.find_in_batches(:batch_size => 1) do |batch| + Post.find_in_batches(batch_size: 1) do |batch| assert_kind_of Array, batch assert_kind_of Post, batch.first @@ -255,7 +255,7 @@ def test_find_in_batches_should_use_any_column_as_primary_key_when_start_is_not_ def test_find_in_batches_should_return_an_enumerator enum = nil assert_no_queries do - enum = Post.find_in_batches(:batch_size => 1) + enum = Post.find_in_batches(batch_size: 1) end assert_queries(4) do enum.first(4) do |batch| @@ -517,11 +517,11 @@ def test_in_batches_relations_update_all_should_not_affect_matching_records_in_o if Enumerator.method_defined? :size def test_find_in_batches_should_return_a_sized_enumerator - assert_equal 11, Post.find_in_batches(:batch_size => 1).size - assert_equal 6, Post.find_in_batches(:batch_size => 2).size + assert_equal 11, Post.find_in_batches(batch_size: 1).size + assert_equal 6, Post.find_in_batches(batch_size: 2).size assert_equal 4, Post.find_in_batches(batch_size: 2, start: 4).size - assert_equal 4, Post.find_in_batches(:batch_size => 3).size - assert_equal 1, Post.find_in_batches(:batch_size => 10_000).size + assert_equal 4, Post.find_in_batches(batch_size: 3).size + assert_equal 1, Post.find_in_batches(batch_size: 10_000).size end end diff --git a/activerecord/test/cases/binary_test.rb b/activerecord/test/cases/binary_test.rb index ebb4c3b5f5..1fc30e24d2 100644 --- a/activerecord/test/cases/binary_test.rb +++ b/activerecord/test/cases/binary_test.rb @@ -13,7 +13,7 @@ def test_mixed_encoding str = "\x80" str.force_encoding("ASCII-8BIT") - binary = Binary.new :name => "ã„ãŸã ãã¾ã™ï¼", :data => str + binary = Binary.new name: "ã„ãŸã ãã¾ã™ï¼", data: str binary.save! binary.reload assert_equal str, binary.data @@ -31,7 +31,7 @@ def test_load_save data.force_encoding("ASCII-8BIT") data.freeze - bin = Binary.new(:data => data) + bin = Binary.new(data: data) assert_equal data, bin.data, "Newly assigned data differs from original" bin.save! diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index 97d080b2a3..e424f13352 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -60,10 +60,10 @@ def test_logs_bind_vars_after_type_cast binds = [Relation::QueryAttribute.new("id", "10", Type::Integer.new)] type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) } payload = { - :name => "SQL", - :sql => "select * from topics where id = ?", - :binds => binds, - :type_casted_binds => type_casted_binds + name: "SQL", + sql: "select * from topics where id = ?", + binds: binds, + type_casted_binds: type_casted_binds } event = ActiveSupport::Notifications::Event.new( "foo", diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 7c3caca5d1..13f9a47980 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -57,7 +57,7 @@ def test_should_return_decimal_average_of_integer_field def test_should_return_integer_average_if_db_returns_such ShipPart.delete_all - ShipPart.create!(:id => 3, :name => "foo") + ShipPart.create!(id: 3, name: "foo") value = ShipPart.average(:id) assert_equal 3, value end @@ -258,7 +258,7 @@ def test_should_return_zero_if_sum_conditions_return_nothing end def test_sum_should_return_valid_values_for_decimals - NumericData.create(:bank_balance => 19.83) + NumericData.create(bank_balance: 19.83) assert_equal 19.83, NumericData.sum(:bank_balance) end @@ -318,7 +318,7 @@ def test_should_group_by_association_with_non_numeric_foreign_key end def test_should_calculate_grouped_association_with_foreign_key_option - Account.belongs_to :another_firm, :class_name => "Firm", :foreign_key => "firm_id" + Account.belongs_to :another_firm, class_name: "Firm", foreign_key: "firm_id" c = Account.group(:another_firm).count(:all) assert_equal 1, c[companies(:first_firm)] assert_equal 2, c[companies(:rails_core)] @@ -381,7 +381,7 @@ def test_should_not_perform_joined_include_by_default end def test_should_perform_joined_include_when_referencing_included_tables - joined_count = Account.includes(:firm).where(:companies => {:name => "37signals"}).count + joined_count = Account.includes(:firm).where(companies: {name: "37signals"}).count assert_equal 1, joined_count end @@ -504,8 +504,8 @@ def test_count_with_from_option assert_equal Company.count(:all), Company.from("companies").count(:all) assert_equal Account.where("credit_limit = 50").count(:all), Account.from("accounts").where("credit_limit = 50").count(:all) - assert_equal Company.where(:type => "Firm").count(:type), - Company.where(:type => "Firm").from("companies").count(:type) + assert_equal Company.where(type: "Firm").count(:type), + Company.where(type: "Firm").from("companies").count(:type) end def test_sum_with_from_option @@ -533,19 +533,19 @@ def test_maximum_with_from_option end def test_maximum_with_not_auto_table_name_prefix_if_column_included - Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)]) assert_equal 7, Company.includes(:contracts).maximum(:developer_id) end def test_minimum_with_not_auto_table_name_prefix_if_column_included - Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)]) assert_equal 7, Company.includes(:contracts).minimum(:developer_id) end def test_sum_with_not_auto_table_name_prefix_if_column_included - Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)]) assert_equal 7, Company.includes(:contracts).sum(:developer_id) end @@ -582,7 +582,7 @@ def test_pluck_without_column_names def test_pluck_type_cast topic = topics(:first) - relation = Topic.where(:id => topic.id) + relation = Topic.where(id: topic.id) assert_equal [ topic.approved ], relation.pluck(:approved) assert_equal [ topic.last_read ], relation.pluck(:last_read) assert_equal [ topic.written_on ], relation.pluck(:written_on) @@ -603,8 +603,8 @@ def test_pluck_on_aliased_attribute end def test_pluck_with_serialization - t = Topic.create!(:content => { :foo => :bar }) - assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content) + t = Topic.create!(content: { foo: :bar }) + assert_equal [{foo: :bar}], Topic.where(id: t.id).pluck(:content) end def test_pluck_with_qualified_column_name @@ -612,17 +612,17 @@ def test_pluck_with_qualified_column_name end def test_pluck_auto_table_name_prefix - c = Company.create!(:name => "test", :contracts => [Contract.new]) + c = Company.create!(name: "test", contracts: [Contract.new]) assert_equal [c.id], Company.joins(:contracts).pluck(:id) end def test_pluck_if_table_included - c = Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + c = Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)]) assert_equal [c.id], Company.includes(:contracts).where("contracts.id" => c.contracts.first).pluck(:id) end def test_pluck_not_auto_table_name_prefix_if_column_joined - Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)]) assert_equal [7], Company.joins(:contracts).pluck(:developer_id) end @@ -647,7 +647,7 @@ def test_pluck_with_includes_limit_and_empty_result end def test_pluck_not_auto_table_name_prefix_if_column_included - Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)]) ids = Company.includes(:contracts).pluck(:developer_id) assert_equal Company.count, ids.length assert_equal [7], ids.compact @@ -672,7 +672,7 @@ def test_pluck_with_multiple_columns_and_selection_clause end def test_pluck_with_multiple_columns_and_includes - Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)]) + Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)]) companies_and_developers = Company.order("companies.id").includes(:contracts).pluck(:name, :developer_id) assert_equal Company.count, companies_and_developers.length @@ -681,7 +681,7 @@ def test_pluck_with_multiple_columns_and_includes end def test_pluck_with_reserved_words - Possession.create!(:where => "Over There") + Possession.create!(where: "Over There") assert_equal ["Over There"], Possession.pluck(:where) end diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index 584ec759a5..2a0e63a781 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -67,7 +67,7 @@ class ChildDeveloper < ParentDeveloper class ImmutableDeveloper < ActiveRecord::Base self.table_name = "developers" - validates_inclusion_of :salary, :in => 50000..200000 + validates_inclusion_of :salary, in: 50000..200000 before_save :cancel before_destroy :cancel @@ -96,16 +96,16 @@ class OnCallbacksDeveloper < ActiveRecord::Base self.table_name = "developers" before_validation { history << :before_validation } - before_validation(:on => :create){ history << :before_validation_on_create } - before_validation(:on => :update){ history << :before_validation_on_update } + before_validation(on: :create){ history << :before_validation_on_create } + before_validation(on: :update){ history << :before_validation_on_update } validate do history << :validate end after_validation { history << :after_validation } - after_validation(:on => :create){ history << :after_validation_on_create } - after_validation(:on => :update){ history << :after_validation_on_update } + after_validation(on: :create){ history << :after_validation_on_create } + after_validation(on: :update){ history << :after_validation_on_update } def history @history ||= [] @@ -116,14 +116,14 @@ class ContextualCallbacksDeveloper < ActiveRecord::Base self.table_name = "developers" before_validation { history << :before_validation } - before_validation :before_validation_on_create_and_update, :on => [ :create, :update ] + before_validation :before_validation_on_create_and_update, on: [ :create, :update ] validate do history << :validate end after_validation { history << :after_validation } - after_validation :after_validation_on_create_and_update, :on => [ :create, :update ] + after_validation :after_validation_on_create_and_update, on: [ :create, :update ] def before_validation_on_create_and_update history << "before_validation_on_#{self.validation_context}".to_sym diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb index 78c0853992..9b38eda004 100644 --- a/activerecord/test/cases/column_definition_test.rb +++ b/activerecord/test/cases/column_definition_test.rb @@ -6,7 +6,7 @@ class ColumnDefinitionTest < ActiveRecord::TestCase def setup @adapter = AbstractAdapter.new(nil) def @adapter.native_database_types - {:string => "varchar"} + {string: "varchar"} end @viz = @adapter.schema_creation end diff --git a/activerecord/test/cases/connection_adapters/connection_specification_test.rb b/activerecord/test/cases/connection_adapters/connection_specification_test.rb index d204fce59f..10a3521c79 100644 --- a/activerecord/test/cases/connection_adapters/connection_specification_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_specification_test.rb @@ -4,7 +4,7 @@ module ActiveRecord module ConnectionAdapters class ConnectionSpecificationTest < ActiveRecord::TestCase def test_dup_deep_copy_config - spec = ConnectionSpecification.new("primary", { :a => :b }, "bar") + spec = ConnectionSpecification.new("primary", { a: :b }, "bar") assert_not_equal(spec.config.object_id, spec.dup.config.object_id) end end diff --git a/activerecord/test/cases/core_test.rb b/activerecord/test/cases/core_test.rb index 051afa4f1f..3735572898 100644 --- a/activerecord/test/cases/core_test.rb +++ b/activerecord/test/cases/core_test.rb @@ -25,8 +25,8 @@ def test_inspect_new_instance end def test_inspect_limited_select_instance - assert_equal %(#), Topic.all.merge!(:select => "id", :where => "id = 1").first.inspect - assert_equal %(#), Topic.all.merge!(:select => "id, title", :where => "id = 1").first.inspect + assert_equal %(#), Topic.all.merge!(select: "id", where: "id = 1").first.inspect + assert_equal %(#), Topic.all.merge!(select: "id, title", where: "id = 1").first.inspect end def test_inspect_class_without_table diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb index e22a243591..84f2c3a465 100644 --- a/activerecord/test/cases/counter_cache_test.rb +++ b/activerecord/test/cases/counter_cache_test.rb @@ -19,12 +19,12 @@ class CounterCacheTest < ActiveRecord::TestCase fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships, :subscribers, :subscriptions, :books class ::SpecialTopic < ::Topic - has_many :special_replies, :foreign_key => "parent_id" - has_many :lightweight_special_replies, -> { select("topics.id, topics.title") }, :foreign_key => "parent_id", :class_name => "SpecialReply" + has_many :special_replies, foreign_key: "parent_id" + has_many :lightweight_special_replies, -> { select("topics.id, topics.title") }, foreign_key: "parent_id", class_name: "SpecialReply" end class ::SpecialReply < ::Reply - belongs_to :special_topic, :foreign_key => "parent_id", :counter_cache => "replies_count" + belongs_to :special_topic, foreign_key: "parent_id", counter_cache: "replies_count" end setup do @@ -79,7 +79,7 @@ class ::SpecialReply < ::Reply end test "reset counters with modularized and camelized classnames" do - special = SpecialTopic.create!(:title => "Special") + special = SpecialTopic.create!(title: "Special") SpecialTopic.increment_counter(:replies_count, special.id) assert_difference "special.reload.replies_count", -1 do @@ -116,13 +116,13 @@ class ::SpecialReply < ::Reply assert_equal 2, category.categorizations.count assert_nil category.categorizations_count - Category.update_counters(category.id, :categorizations_count => category.categorizations.count) + Category.update_counters(category.id, categorizations_count: category.categorizations.count) assert_equal 2, category.reload.categorizations_count end test "update counter for decrement" do assert_difference "@topic.reload.replies_count", -3 do - Topic.update_counters(@topic.id, :replies_count => -3) + Topic.update_counters(@topic.id, replies_count: -3) end end @@ -130,7 +130,7 @@ class ::SpecialReply < ::Reply t1, t2 = topics(:first, :second) assert_difference ["t1.reload.replies_count", "t2.reload.replies_count"], 2 do - Topic.update_counters([t1.id, t2.id], :replies_count => 2) + Topic.update_counters([t1.id, t2.id], replies_count: 2) end end @@ -174,7 +174,7 @@ class ::SpecialReply < ::Reply end test "reset counter works with select declared on association" do - special = SpecialTopic.create!(:title => "Special") + special = SpecialTopic.create!(title: "Special") SpecialTopic.increment_counter(:replies_count, special.id) assert_difference "special.reload.replies_count", -1 do diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb index bec4311545..15c8b684e4 100644 --- a/activerecord/test/cases/custom_locking_test.rb +++ b/activerecord/test/cases/custom_locking_test.rb @@ -9,7 +9,7 @@ def test_custom_lock if current_adapter?(:Mysql2Adapter) assert_match "SHARE MODE", Person.lock("LOCK IN SHARE MODE").to_sql assert_sql(/LOCK IN SHARE MODE/) do - Person.all.merge!(:lock => "LOCK IN SHARE MODE").find(1) + Person.all.merge!(lock: "LOCK IN SHARE MODE").find(1) end end end diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index f03610bcd3..f94815d34c 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -178,10 +178,10 @@ def with_text_blob_not_null_table klass = Class.new(ActiveRecord::Base) klass.table_name = "test_mysql_text_not_null_defaults" klass.connection.create_table klass.table_name do |t| - t.column :non_null_text, :text, :null => false - t.column :non_null_blob, :blob, :null => false - t.column :null_text, :text, :null => true - t.column :null_blob, :blob, :null => true + t.column :non_null_text, :text, null: false + t.column :non_null_blob, :blob, null: false + t.column :null_text, :text, null: true + t.column :null_blob, :blob, null: true end yield klass @@ -195,8 +195,8 @@ def test_mysql_integer_not_null_defaults klass = Class.new(ActiveRecord::Base) klass.table_name = "test_integer_not_null_default_zero" klass.connection.create_table klass.table_name do |t| - t.column :zero, :integer, :null => false, :default => 0 - t.column :omit, :integer, :null => false + t.column :zero, :integer, null: false, default: 0 + t.column :omit, :integer, null: false end assert_equal "0", klass.columns_hash["zero"].default @@ -207,7 +207,7 @@ def test_mysql_integer_not_null_defaults assert_raise(ActiveRecord::StatementInvalid) { klass.create! } assert_nothing_raised do - instance = klass.create!(:omit => 1) + instance = klass.create!(omit: 1) assert_equal 0, instance.zero assert_equal 1, instance.omit end diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index 382ca7c6ac..417383211d 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -14,7 +14,7 @@ class DirtyTest < ActiveRecord::TestCase # Dummy to force column loads so query counts are clean. def setup - Person.create :first_name => "foo" + Person.create first_name: "foo" end def test_attribute_changes @@ -149,7 +149,7 @@ def test_aliased_attribute_changes end def test_restore_attribute! - pirate = Pirate.create!(:catchphrase => "Yar!") + pirate = Pirate.create!(catchphrase: "Yar!") pirate.catchphrase = "Ahoy!" pirate.restore_catchphrase! @@ -229,7 +229,7 @@ def test_integer_zero_to_integer_zero_not_marked_as_changed end def test_float_zero_to_string_zero_not_marked_as_changed - data = NumericData.new :temperature => 0.0 + data = NumericData.new temperature: 0.0 data.save! assert_not data.changed? @@ -290,7 +290,7 @@ def test_object_should_be_changed_if_any_attribute_is_changed end def test_attribute_will_change! - pirate = Pirate.create!(:catchphrase => "arr") + pirate = Pirate.create!(catchphrase: "arr") assert !pirate.catchphrase_changed? assert pirate.catchphrase_will_change! @@ -303,8 +303,8 @@ def test_attribute_will_change! end def test_association_assignment_changes_foreign_key - pirate = Pirate.create!(:catchphrase => "jarl") - pirate.parrot = Parrot.create!(:name => "Lorre") + pirate = Pirate.create!(catchphrase: "jarl") + pirate.parrot = Parrot.create!(name: "Lorre") assert pirate.changed? assert_equal %w(parrot_id), pirate.changed end @@ -315,7 +315,7 @@ def test_attribute_should_be_compared_with_type_cast assert !topic.approved_changed? # Coming from web form. - params = {:topic => {:approved => 1}} + params = {topic: {approved: 1}} # In the controller. topic.attributes = params[:topic] assert topic.approved? @@ -323,12 +323,12 @@ def test_attribute_should_be_compared_with_type_cast end def test_partial_update - pirate = Pirate.new(:catchphrase => "foo") + pirate = Pirate.new(catchphrase: "foo") old_updated_on = 1.hour.ago.beginning_of_day with_partial_writes Pirate, false do assert_queries(2) { 2.times { pirate.save! } } - Pirate.where(id: pirate.id).update_all(:updated_on => old_updated_on) + Pirate.where(id: pirate.id).update_all(updated_on: old_updated_on) end with_partial_writes Pirate, true do @@ -341,12 +341,12 @@ def test_partial_update end def test_partial_update_with_optimistic_locking - person = Person.new(:first_name => "foo") + person = Person.new(first_name: "foo") old_lock_version = 1 with_partial_writes Person, false do assert_queries(2) { 2.times { person.save! } } - Person.where(id: person.id).update_all(:first_name => "baz") + Person.where(id: person.id).update_all(first_name: "baz") end with_partial_writes Person, true do @@ -371,7 +371,7 @@ def test_changed_attributes_should_be_preserved_if_save_failure end def test_reload_should_clear_changed_attributes - pirate = Pirate.create!(:catchphrase => "shiver me timbers") + pirate = Pirate.create!(catchphrase: "shiver me timbers") pirate.catchphrase = "*hic*" assert pirate.changed? pirate.reload @@ -379,7 +379,7 @@ def test_reload_should_clear_changed_attributes end def test_dup_objects_should_not_copy_dirty_flag_from_creator - pirate = Pirate.create!(:catchphrase => "shiver me timbers") + pirate = Pirate.create!(catchphrase: "shiver me timbers") pirate_dup = pirate.dup pirate_dup.restore_catchphrase! pirate.catchphrase = "I love Rum" @@ -389,7 +389,7 @@ def test_dup_objects_should_not_copy_dirty_flag_from_creator def test_reverted_changes_are_not_dirty phrase = "shiver me timbers" - pirate = Pirate.create!(:catchphrase => phrase) + pirate = Pirate.create!(catchphrase: phrase) pirate.catchphrase = "*hic*" assert pirate.changed? pirate.catchphrase = phrase @@ -398,7 +398,7 @@ def test_reverted_changes_are_not_dirty def test_reverted_changes_are_not_dirty_after_multiple_changes phrase = "shiver me timbers" - pirate = Pirate.create!(:catchphrase => phrase) + pirate = Pirate.create!(catchphrase: phrase) 10.times do |i| pirate.catchphrase = "*hic*" * i assert pirate.changed? @@ -410,7 +410,7 @@ def test_reverted_changes_are_not_dirty_after_multiple_changes def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back - pirate = Pirate.create!(:catchphrase => "Yar!") + pirate = Pirate.create!(catchphrase: "Yar!") pirate.parrot_id = 1 assert pirate.changed? @@ -425,7 +425,7 @@ def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back def test_save_should_store_serialized_attributes_even_with_partial_writes with_partial_writes(Topic) do - topic = Topic.create!(:content => {:a => "a"}) + topic = Topic.create!(content: {a: "a"}) assert_not topic.changed? @@ -446,7 +446,7 @@ def test_save_should_store_serialized_attributes_even_with_partial_writes def test_save_always_should_update_timestamps_when_serialized_attributes_are_present with_partial_writes(Topic) do - topic = Topic.create!(:content => {:a => "a"}) + topic = Topic.create!(content: {a: "a"}) topic.save! updated_at = topic.updated_at @@ -462,7 +462,7 @@ def test_save_always_should_update_timestamps_when_serialized_attributes_are_pre def test_save_should_not_save_serialized_attribute_with_partial_writes_if_not_present with_partial_writes(Topic) do - Topic.create!(:author_name => "Bill", :content => {:a => "a"}) + Topic.create!(author_name: "Bill", content: {a: "a"}) topic = Topic.select("id, author_name").first topic.update_columns author_name: "John" topic = Topic.first @@ -582,7 +582,7 @@ def test_datetime_attribute_can_be_updated_with_fractional_seconds written_on = Time.utc(2012, 12, 1, 12, 0, 0).in_time_zone("Paris") - topic = target.create(:written_on => written_on) + topic = target.create(written_on: written_on) topic.written_on += 0.3 assert topic.written_on_changed?, "Fractional second update not detected" @@ -591,7 +591,7 @@ def test_datetime_attribute_can_be_updated_with_fractional_seconds def test_datetime_attribute_doesnt_change_if_zone_is_modified_in_string time_in_paris = Time.utc(2014, 1, 1, 12, 0, 0).in_time_zone("Paris") - pirate = Pirate.create!(:catchphrase => "rrrr", :created_on => time_in_paris) + pirate = Pirate.create!(catchphrase: "rrrr", created_on: time_in_paris) pirate.created_on = pirate.created_on.in_time_zone("Tokyo").to_s assert !pirate.created_on_changed? diff --git a/activerecord/test/cases/dup_test.rb b/activerecord/test/cases/dup_test.rb index 4e8b8db11c..3821e0c949 100644 --- a/activerecord/test/cases/dup_test.rb +++ b/activerecord/test/cases/dup_test.rb @@ -135,8 +135,8 @@ def test_dup_validity_is_independent def test_dup_with_default_scope prev_default_scopes = Topic.default_scopes - Topic.default_scopes = [proc { Topic.where(:approved => true) }] - topic = Topic.new(:approved => false) + Topic.default_scopes = [proc { Topic.where(approved: true) }] + topic = Topic.new(approved: false) assert !topic.dup.approved?, "should not be overridden by default scopes" ensure Topic.default_scopes = prev_default_scopes diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb index e8816743ea..43f1d401dd 100644 --- a/activerecord/test/cases/explain_test.rb +++ b/activerecord/test/cases/explain_test.rb @@ -15,13 +15,13 @@ def connection end def test_relation_explain - message = Car.where(:name => "honda").explain + message = Car.where(name: "honda").explain assert_match(/^EXPLAIN for:/, message) end def test_collecting_queries_for_explain queries = ActiveRecord::Base.collecting_queries_for_explain do - Car.where(:name => "honda").to_a + Car.where(name: "honda").to_a end sql, binds = queries[0] @@ -65,7 +65,7 @@ def test_exec_explain_with_binds def test_unsupported_connection_adapter connection.stub(:supports_explain?, false) do assert_not_called(base.logger, :warn) do - Car.where(:name => "honda").to_a + Car.where(name: "honda").to_a end end end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 099a79e9bc..b3745d9dec 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -23,13 +23,13 @@ class FinderTest < ActiveRecord::TestCase def test_find_by_id_with_hash assert_raises(ActiveRecord::StatementInvalid) do - Post.find_by_id(:limit => 1) + Post.find_by_id(limit: 1) end end def test_find_by_title_and_id_with_hash assert_raises(ActiveRecord::StatementInvalid) do - Post.find_by_title_and_id("foo", :limit => 1) + Post.find_by_title_and_id("foo", limit: 1) end end @@ -144,7 +144,7 @@ def test_exists assert_equal true, Topic.exists?("1") assert_equal true, Topic.exists?(title: "The First Topic") assert_equal true, Topic.exists?(heading: "The First Topic") - assert_equal true, Topic.exists?(:author_name => "Mary", :approved => true) + assert_equal true, Topic.exists?(author_name: "Mary", approved: true) assert_equal true, Topic.exists?(["parent_id = ?", 1]) assert_equal true, Topic.exists?(id: [1, 9999]) @@ -231,17 +231,14 @@ def test_exists_with_empty_table_and_no_args_given def test_exists_with_aggregate_having_three_mappings existing_address = customers(:david).address - assert_equal true, Customer.exists?(:address => existing_address) + assert_equal true, Customer.exists?(address: existing_address) end def test_exists_with_aggregate_having_three_mappings_with_one_difference existing_address = customers(:david).address - assert_equal false, Customer.exists?(:address => - Address.new(existing_address.street, existing_address.city, existing_address.country + "1")) - assert_equal false, Customer.exists?(:address => - Address.new(existing_address.street, existing_address.city + "1", existing_address.country)) - assert_equal false, Customer.exists?(:address => - Address.new(existing_address.street + "1", existing_address.city, existing_address.country)) + assert_equal false, Customer.exists?(address: Address.new(existing_address.street, existing_address.city, existing_address.country + "1")) + assert_equal false, Customer.exists?(address: Address.new(existing_address.street, existing_address.city + "1", existing_address.country)) + assert_equal false, Customer.exists?(address: Address.new(existing_address.street + "1", existing_address.city, existing_address.country)) end def test_exists_does_not_instantiate_records @@ -672,7 +669,7 @@ def test_find_on_combined_explicit_and_hashed_table_names end def test_find_with_hash_conditions_on_joined_table - firms = Firm.joins(:account).where(:accounts => { :credit_limit => 50 }) + firms = Firm.joins(:account).where(accounts: { credit_limit: 50 }) assert_equal 1, firms.size assert_equal companies(:first_firm), firms.first end @@ -772,42 +769,42 @@ def test_hash_condition_find_with_nil def test_hash_condition_find_with_aggregate_having_one_mapping balance = customers(:david).balance assert_kind_of Money, balance - found_customer = Customer.where(:balance => balance).first + found_customer = Customer.where(balance: balance).first assert_equal customers(:david), found_customer end def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_aggregate gps_location = customers(:david).gps_location assert_kind_of GpsLocation, gps_location - found_customer = Customer.where(:gps_location => gps_location).first + found_customer = Customer.where(gps_location: gps_location).first assert_equal customers(:david), found_customer end def test_hash_condition_find_with_aggregate_having_one_mapping_and_key_value_being_attribute_value balance = customers(:david).balance assert_kind_of Money, balance - found_customer = Customer.where(:balance => balance.amount).first + found_customer = Customer.where(balance: balance.amount).first assert_equal customers(:david), found_customer end def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_attribute_value gps_location = customers(:david).gps_location assert_kind_of GpsLocation, gps_location - found_customer = Customer.where(:gps_location => gps_location.gps_location).first + found_customer = Customer.where(gps_location: gps_location.gps_location).first assert_equal customers(:david), found_customer end def test_hash_condition_find_with_aggregate_having_three_mappings address = customers(:david).address assert_kind_of Address, address - found_customer = Customer.where(:address => address).first + found_customer = Customer.where(address: address).first assert_equal customers(:david), found_customer end def test_hash_condition_find_with_one_condition_being_aggregate_and_another_not address = customers(:david).address assert_kind_of Address, address - found_customer = Customer.where(:address => address, :name => customers(:david).name).first + found_customer = Customer.where(address: address, name: customers(:david).name).first assert_equal customers(:david), found_customer end @@ -1042,7 +1039,7 @@ def test_find_by_id_with_conditions_with_or end def test_find_ignores_previously_inserted_record - Post.create!(:title => "test", :body => "it out") + Post.create!(title: "test", body: "it out") assert_equal [], Post.where(id: nil) end @@ -1115,8 +1112,8 @@ def test_find_with_nil_inside_set_passed_for_attribute def test_with_limiting_with_custom_select posts = Post.references(:authors).merge( - :includes => :author, :select => 'posts.*, authors.id as "author_id"', - :limit => 3, :order => "posts.id" + includes: :author, select: 'posts.*, authors.id as "author_id"', + limit: 3, order: "posts.id" ).to_a assert_equal 3, posts.size assert_equal [0, 1, 1], posts.map(&:author_id).sort diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index b5643fe5e2..234e99919c 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -81,7 +81,7 @@ def test_multiple_clean_fixtures end def test_create_symbol_fixtures - fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :collections, :collections => Course) { Course.connection } + fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :collections, collections: Course) { Course.connection } assert Course.find_by_name("Collection"), "course is not in the database" assert fixtures.detect { |f| f.name == "collections" }, "no fixtures named 'collections' in #{fixtures.map(&:name).inspect}" @@ -115,10 +115,10 @@ def test_inserts_with_pre_and_suffix t.column :bonus_time, :time t.column :last_read, :date t.column :content, :string - t.column :approved, :boolean, :default => true - t.column :replies_count, :integer, :default => 0 + t.column :approved, :boolean, default: true + t.column :replies_count, :integer, default: 0 t.column :parent_id, :integer - t.column :type, :string, :limit => 50 + t.column :type, :string, limit: 50 end # Store existing prefix/suffix @@ -291,11 +291,11 @@ def test_has_many_through_with_default_table_name treasure = make_model "Treasure" pt.table_name = "parrots_treasures" - pt.belongs_to :parrot, :anonymous_class => parrot - pt.belongs_to :treasure, :anonymous_class => treasure + pt.belongs_to :parrot, anonymous_class: parrot + pt.belongs_to :treasure, anonymous_class: treasure - parrot.has_many :parrot_treasures, :anonymous_class => pt - parrot.has_many :treasures, :through => :parrot_treasures + parrot.has_many :parrot_treasures, anonymous_class: pt + parrot.has_many :treasures, through: :parrot_treasures parrots = File.join FIXTURES_ROOT, "parrots" @@ -309,11 +309,11 @@ def test_has_many_through_with_renamed_table parrot = make_model "Parrot" treasure = make_model "Treasure" - pt.belongs_to :parrot, :anonymous_class => parrot - pt.belongs_to :treasure, :anonymous_class => treasure + pt.belongs_to :parrot, anonymous_class: parrot + pt.belongs_to :treasure, anonymous_class: treasure - parrot.has_many :parrot_treasures, :anonymous_class => pt - parrot.has_many :treasures, :through => :parrot_treasures + parrot.has_many :parrot_treasures, anonymous_class: pt + parrot.has_many :treasures, through: :parrot_treasures parrots = File.join FIXTURES_ROOT, "parrots" @@ -339,7 +339,7 @@ class FixturesResetPkSequenceTest < ActiveRecord::TestCase fixtures :companies def setup - @instances = [Account.new(:credit_limit => 50), Company.new(:name => "RoR Consulting"), Course.new(name: "Test")] + @instances = [Account.new(credit_limit: 50), Company.new(name: "RoR Consulting"), Course.new(name: "Test")] ActiveRecord::FixtureSet.reset_cache # make sure tables get reinitialized end @@ -553,7 +553,7 @@ def test_uses_set_fixture_class end class CheckSetTableNameFixturesTest < ActiveRecord::TestCase - set_fixture_class :funny_jokes => Joke + set_fixture_class funny_jokes: Joke fixtures :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class @@ -565,7 +565,7 @@ def test_table_method end class FixtureNameIsNotTableNameFixturesTest < ActiveRecord::TestCase - set_fixture_class :items => Book + set_fixture_class items: Book fixtures :items # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class @@ -577,7 +577,7 @@ def test_named_accessor end class FixtureNameIsNotTableNameMultipleFixturesTest < ActiveRecord::TestCase - set_fixture_class :items => Book, :funny_jokes => Joke + set_fixture_class items: Book, funny_jokes: Joke fixtures :items, :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class @@ -593,7 +593,7 @@ def test_named_accessor_of_same_named_fixture end class CustomConnectionFixturesTest < ActiveRecord::TestCase - set_fixture_class :courses => Course + set_fixture_class courses: Course fixtures :courses self.use_transactional_tests = false @@ -608,7 +608,7 @@ def test_it_twice_in_whatever_order_to_check_for_fixture_leakage end class TransactionalFixturesOnCustomConnectionTest < ActiveRecord::TestCase - set_fixture_class :courses => Course + set_fixture_class courses: Course fixtures :courses self.use_transactional_tests = true @@ -627,7 +627,7 @@ class TransactionalFixturesOnConnectionNotification < ActiveRecord::TestCase self.use_instantiated_fixtures = false def test_transaction_created_on_connection_notification - connection = stub(:transaction_open? => false) + connection = stub(transaction_open?: false) connection.expects(:begin_transaction).with(joinable: false) fire_connection_notification(connection) end @@ -676,7 +676,7 @@ def test_raises_error end class CheckEscapedYamlFixturesTest < ActiveRecord::TestCase - set_fixture_class :funny_jokes => Joke + set_fixture_class funny_jokes: Joke fixtures :funny_jokes # Set to false to blow away fixtures cache and ensure our fixtures are loaded # and thus takes into account our set_fixture_class diff --git a/activerecord/test/cases/habtm_destroy_order_test.rb b/activerecord/test/cases/habtm_destroy_order_test.rb index 8484bbd2e4..365d4576dd 100644 --- a/activerecord/test/cases/habtm_destroy_order_test.rb +++ b/activerecord/test/cases/habtm_destroy_order_test.rb @@ -4,8 +4,8 @@ class HabtmDestroyOrderTest < ActiveRecord::TestCase test "may not delete a lesson with students" do - sicp = Lesson.new(:name => "SICP") - ben = Student.new(:name => "Ben Bitdiddle") + sicp = Lesson.new(name: "SICP") + ben = Student.new(name: "Ben Bitdiddle") sicp.students << ben sicp.save! assert_raises LessonError do @@ -17,8 +17,8 @@ class HabtmDestroyOrderTest < ActiveRecord::TestCase end test "should not raise error if have foreign key in the join table" do - student = Student.new(:name => "Ben Bitdiddle") - lesson = Lesson.new(:name => "SICP") + student = Student.new(name: "Ben Bitdiddle") + lesson = Lesson.new(name: "SICP") lesson.students << student lesson.save! assert_nothing_raised do @@ -29,8 +29,8 @@ class HabtmDestroyOrderTest < ActiveRecord::TestCase test "not destroying a student with lessons leaves student<=>lesson association intact" do # test a normal before_destroy doesn't destroy the habtm joins begin - sicp = Lesson.new(:name => "SICP") - ben = Student.new(:name => "Ben Bitdiddle") + sicp = Lesson.new(name: "SICP") + ben = Student.new(name: "Ben Bitdiddle") # add a before destroy to student Student.class_eval do before_destroy do @@ -49,8 +49,8 @@ class HabtmDestroyOrderTest < ActiveRecord::TestCase test "not destroying a lesson with students leaves student<=>lesson association intact" do # test a more aggressive before_destroy doesn't destroy the habtm joins and still throws the exception - sicp = Lesson.new(:name => "SICP") - ben = Student.new(:name => "Ben Bitdiddle") + sicp = Lesson.new(name: "SICP") + ben = Student.new(name: "Ben Bitdiddle") sicp.students << ben sicp.save! assert_raises LessonError do diff --git a/activerecord/test/cases/i18n_test.rb b/activerecord/test/cases/i18n_test.rb index f28d6f65d9..6c90dc4996 100644 --- a/activerecord/test/cases/i18n_test.rb +++ b/activerecord/test/cases/i18n_test.rb @@ -9,37 +9,37 @@ def setup end def test_translated_model_attributes - I18n.backend.store_translations "en", :activerecord => {:attributes => {:topic => {:title => "topic title attribute"} } } + I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } } assert_equal "topic title attribute", Topic.human_attribute_name("title") end def test_translated_model_attributes_with_symbols - I18n.backend.store_translations "en", :activerecord => {:attributes => {:topic => {:title => "topic title attribute"} } } + I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } } assert_equal "topic title attribute", Topic.human_attribute_name(:title) end def test_translated_model_attributes_with_sti - I18n.backend.store_translations "en", :activerecord => {:attributes => {:reply => {:title => "reply title attribute"} } } + I18n.backend.store_translations "en", activerecord: {attributes: {reply: {title: "reply title attribute"} } } assert_equal "reply title attribute", Reply.human_attribute_name("title") end def test_translated_model_attributes_with_sti_fallback - I18n.backend.store_translations "en", :activerecord => {:attributes => {:topic => {:title => "topic title attribute"} } } + I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } } assert_equal "topic title attribute", Reply.human_attribute_name("title") end def test_translated_model_names - I18n.backend.store_translations "en", :activerecord => {:models => {:topic => "topic model"} } + I18n.backend.store_translations "en", activerecord: {models: {topic: "topic model"} } assert_equal "topic model", Topic.model_name.human end def test_translated_model_names_with_sti - I18n.backend.store_translations "en", :activerecord => {:models => {:reply => "reply model"} } + I18n.backend.store_translations "en", activerecord: {models: {reply: "reply model"} } assert_equal "reply model", Reply.model_name.human end def test_translated_model_names_with_sti_fallback - I18n.backend.store_translations "en", :activerecord => {:models => {:topic => "topic model"} } + I18n.backend.store_translations "en", activerecord: {models: {topic: "topic model"} } assert_equal "topic model", Reply.model_name.human end end diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 24e049c18a..9f9bb63a4d 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -229,13 +229,13 @@ def test_alt_becomes_bang_resets_inheritance_type_column end def test_inheritance_find_all - companies = Company.all.merge!(:order => "id").to_a + companies = Company.all.merge!(order: "id").to_a assert_kind_of Firm, companies[0], "37signals should be a firm" assert_kind_of Client, companies[1], "Summit should be a client" end def test_alt_inheritance_find_all - companies = Vegetable.all.merge!(:order => "id").to_a + companies = Vegetable.all.merge!(order: "id").to_a assert_kind_of Cucumber, companies[0] assert_kind_of Cabbage, companies[1] end @@ -250,7 +250,7 @@ def test_inheritance_save end def test_alt_inheritance_save - cabbage = Cabbage.new(:name => "Savoy") + cabbage = Cabbage.new(name: "Savoy") cabbage.save! savoy = Vegetable.find(cabbage.id) @@ -263,12 +263,12 @@ def test_inheritance_new_with_default_class end def test_inheritance_new_with_base_class - company = Company.new(:type => "Company") + company = Company.new(type: "Company") assert_equal Company, company.class end def test_inheritance_new_with_subclass - firm = Company.new(:type => "Firm") + firm = Company.new(type: "Firm") assert_equal Firm, firm.class end @@ -287,11 +287,11 @@ def test_new_with_ar_base end def test_new_with_invalid_type - assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => "InvalidType") } + assert_raise(ActiveRecord::SubclassNotFound) { Company.new(type: "InvalidType") } end def test_new_with_unrelated_type - assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => "Account") } + assert_raise(ActiveRecord::SubclassNotFound) { Company.new(type: "Account") } end def test_new_with_unrelated_namespaced_type @@ -319,7 +319,7 @@ def test_new_with_autoload_paths path = File.expand_path("../../models/autoloadable", __FILE__) ActiveSupport::Dependencies.autoload_paths << path - firm = Company.new(:type => "ExtraFirm") + firm = Company.new(type: "ExtraFirm") assert_equal ExtraFirm, firm.class ensure ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path } @@ -352,7 +352,7 @@ def test_update_all_within_inheritance Client.update_all "name = 'I am a client'" assert_equal "I am a client", Client.first.name # Order by added as otherwise Oracle tests were failing because of different order of results - assert_equal "37signals", Firm.all.merge!(:order => "id").to_a.first.name + assert_equal "37signals", Firm.all.merge!(order: "id").to_a.first.name end def test_alt_update_all_within_inheritance @@ -374,51 +374,51 @@ def test_alt_destroy_all_within_inheritance end def test_find_first_within_inheritance - assert_kind_of Firm, Company.all.merge!(:where => "name = '37signals'").first - assert_kind_of Firm, Firm.all.merge!(:where => "name = '37signals'").first - assert_nil Client.all.merge!(:where => "name = '37signals'").first + assert_kind_of Firm, Company.all.merge!(where: "name = '37signals'").first + assert_kind_of Firm, Firm.all.merge!(where: "name = '37signals'").first + assert_nil Client.all.merge!(where: "name = '37signals'").first end def test_alt_find_first_within_inheritance - assert_kind_of Cabbage, Vegetable.all.merge!(:where => "name = 'his cabbage'").first - assert_kind_of Cabbage, Cabbage.all.merge!(:where => "name = 'his cabbage'").first - assert_nil Cucumber.all.merge!(:where => "name = 'his cabbage'").first + assert_kind_of Cabbage, Vegetable.all.merge!(where: "name = 'his cabbage'").first + assert_kind_of Cabbage, Cabbage.all.merge!(where: "name = 'his cabbage'").first + assert_nil Cucumber.all.merge!(where: "name = 'his cabbage'").first end def test_complex_inheritance very_special_client = VerySpecialClient.create("name" => "veryspecial") assert_equal very_special_client, VerySpecialClient.where("name = 'veryspecial'").first - assert_equal very_special_client, SpecialClient.all.merge!(:where => "name = 'veryspecial'").first - assert_equal very_special_client, Company.all.merge!(:where => "name = 'veryspecial'").first - assert_equal very_special_client, Client.all.merge!(:where => "name = 'veryspecial'").first - assert_equal 1, Client.all.merge!(:where => "name = 'Summit'").to_a.size + assert_equal very_special_client, SpecialClient.all.merge!(where: "name = 'veryspecial'").first + assert_equal very_special_client, Company.all.merge!(where: "name = 'veryspecial'").first + assert_equal very_special_client, Client.all.merge!(where: "name = 'veryspecial'").first + assert_equal 1, Client.all.merge!(where: "name = 'Summit'").to_a.size assert_equal very_special_client, Client.find(very_special_client.id) end def test_alt_complex_inheritance king_cole = KingCole.create("name" => "uniform heads") assert_equal king_cole, KingCole.where("name = 'uniform heads'").first - assert_equal king_cole, GreenCabbage.all.merge!(:where => "name = 'uniform heads'").first - assert_equal king_cole, Cabbage.all.merge!(:where => "name = 'uniform heads'").first - assert_equal king_cole, Vegetable.all.merge!(:where => "name = 'uniform heads'").first - assert_equal 1, Cabbage.all.merge!(:where => "name = 'his cabbage'").to_a.size + assert_equal king_cole, GreenCabbage.all.merge!(where: "name = 'uniform heads'").first + assert_equal king_cole, Cabbage.all.merge!(where: "name = 'uniform heads'").first + assert_equal king_cole, Vegetable.all.merge!(where: "name = 'uniform heads'").first + assert_equal 1, Cabbage.all.merge!(where: "name = 'his cabbage'").to_a.size assert_equal king_cole, Cabbage.find(king_cole.id) end def test_eager_load_belongs_to_something_inherited - account = Account.all.merge!(:includes => :firm).find(1) + account = Account.all.merge!(includes: :firm).find(1) assert account.association(:firm).loaded?, "association was not eager loaded" end def test_alt_eager_loading - cabbage = RedCabbage.all.merge!(:includes => :seller).find(4) + cabbage = RedCabbage.all.merge!(includes: :seller).find(4) assert cabbage.association(:seller).loaded?, "association was not eager loaded" end def test_eager_load_belongs_to_primary_key_quoting con = Account.connection assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} = 1/) do - Account.all.merge!(:includes => :firm).find(1) + Account.all.merge!(includes: :firm).find(1) end end @@ -471,7 +471,7 @@ def test_instantiation_doesnt_try_to_require_corresponding_file def test_sti_type_from_attributes_disabled_in_non_sti_class phone = Shop::Product::Type.new(name: "Phone") - product = Shop::Product.new(:type => phone) + product = Shop::Product.new(type: phone) assert product.save end diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb index bfa6a05d00..7f407f84da 100644 --- a/activerecord/test/cases/json_serialization_test.rb +++ b/activerecord/test/cases/json_serialization_test.rb @@ -27,12 +27,12 @@ class NamespacedContact < Contact def setup @contact = Contact.new( - :name => "Konata Izumi", - :age => 16, - :avatar => "binarydata", - :created_at => Time.utc(2006, 8, 1), - :awesome => true, - :preferences => { :shows => "anime" } + name: "Konata Izumi", + age: 16, + avatar: "binarydata", + created_at: Time.utc(2006, 8, 1), + awesome: true, + preferences: { shows: "anime" } ) end @@ -68,7 +68,7 @@ def test_should_encode_all_encodable_attributes end def test_should_allow_attribute_filtering_with_only - json = @contact.to_json(:only => [:name, :age]) + json = @contact.to_json(only: [:name, :age]) assert_match %r{"name":"Konata Izumi"}, json assert_match %r{"age":16}, json @@ -78,7 +78,7 @@ def test_should_allow_attribute_filtering_with_only end def test_should_allow_attribute_filtering_with_except - json = @contact.to_json(:except => [:name, :age]) + json = @contact.to_json(except: [:name, :age]) assert_no_match %r{"name":"Konata Izumi"}, json assert_no_match %r{"age":16}, json @@ -93,10 +93,10 @@ def @contact.label; "Has cheezburger"; end def @contact.favorite_quote; "Constraints are liberating"; end # Single method. - assert_match %r{"label":"Has cheezburger"}, @contact.to_json(:only => :name, :methods => :label) + assert_match %r{"label":"Has cheezburger"}, @contact.to_json(only: :name, methods: :label) # Both methods. - methods_json = @contact.to_json(:only => :name, :methods => [:label, :favorite_quote]) + methods_json = @contact.to_json(only: :name, methods: [:label, :favorite_quote]) assert_match %r{"label":"Has cheezburger"}, methods_json assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json end @@ -149,7 +149,7 @@ def @contact.serializable_hash(options={}) end def test_serializable_hash_should_not_modify_options_in_argument - options = { :only => :name } + options = { only: :name } @contact.serializable_hash(options) assert_nil options[:except] @@ -167,7 +167,7 @@ def setup end def test_includes_uses_association_name - json = @david.to_json(:include => :posts) + json = @david.to_json(include: :posts) assert_match %r{"posts":\[}, json @@ -183,7 +183,7 @@ def test_includes_uses_association_name end def test_includes_uses_association_name_and_applies_attribute_filters - json = @david.to_json(:include => { :posts => { :only => :title } }) + json = @david.to_json(include: { posts: { only: :title } }) assert_match %r{"name":"David"}, json assert_match %r{"posts":\[}, json @@ -196,7 +196,7 @@ def test_includes_uses_association_name_and_applies_attribute_filters end def test_includes_fetches_second_level_associations - json = @david.to_json(:include => { :posts => { :include => { :comments => { :only => :body } } } }) + json = @david.to_json(include: { posts: { include: { comments: { only: :body } } } }) assert_match %r{"name":"David"}, json assert_match %r{"posts":\[}, json @@ -209,12 +209,12 @@ def test_includes_fetches_second_level_associations def test_includes_fetches_nth_level_associations json = @david.to_json( - :include => { - :posts => { - :include => { - :taggings => { - :include => { - :tag => { :only => :name } + include: { + posts: { + include: { + taggings: { + include: { + tag: { only: :name } } } } @@ -230,8 +230,8 @@ def test_includes_fetches_nth_level_associations def test_includes_doesnt_merge_opts_from_base json = @david.to_json( - :only => :id, - :include => :posts + only: :id, + include: :posts ) assert_match %{"title":"Welcome to the weblog"}, json @@ -239,7 +239,7 @@ def test_includes_doesnt_merge_opts_from_base def test_should_not_call_methods_on_associations_that_dont_respond def @david.favorite_quote; "Constraints are liberating"; end - json = @david.to_json(:include => :posts, :methods => :favorite_quote) + json = @david.to_json(include: :posts, methods: :favorite_quote) assert !@david.posts.first.respond_to?(:favorite_quote) assert_match %r{"favorite_quote":"Constraints are liberating"}, json @@ -267,9 +267,9 @@ def test_should_allow_except_option_for_list_of_authors def test_should_allow_includes_for_list_of_authors authors = [@david, @mary] json = ActiveSupport::JSON.encode(authors, - :only => :name, - :include => { - :posts => { :only => :id } + only: :name, + include: { + posts: { only: :id } } ) diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index d0184ad2b3..f5c9945b37 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -125,7 +125,7 @@ def test_lock_repeating end def test_lock_new - p1 = Person.new(:first_name => "anika") + p1 = Person.new(first_name: "anika") assert_equal 0, p1.lock_version p1.first_name = "anika2" @@ -144,7 +144,7 @@ def test_lock_new end def test_lock_exception_record - p1 = Person.new(:first_name => "mira") + p1 = Person.new(first_name: "mira") assert_equal 0, p1.lock_version p1.first_name = "mira2" @@ -162,7 +162,7 @@ def test_lock_exception_record end def test_lock_new_with_nil - p1 = Person.new(:first_name => "anika") + p1 = Person.new(first_name: "anika") p1.save! p1.lock_version = nil # simulate bad fixture or column with no default p1.save! @@ -170,7 +170,7 @@ def test_lock_new_with_nil end def test_lock_new_when_explicitly_passing_nil - p1 = Person.new(:first_name => "anika", lock_version: nil) + p1 = Person.new(first_name: "anika", lock_version: nil) p1.save! assert_equal 0, p1.lock_version end @@ -209,7 +209,7 @@ def test_lock_column_name_existing end def test_lock_column_is_mass_assignable - p1 = Person.create(:first_name => "bianca") + p1 = Person.create(first_name: "bianca") assert_equal 0, p1.lock_version assert_equal p1.lock_version, Person.new(p1.attributes).lock_version @@ -242,7 +242,7 @@ def test_lock_with_custom_column_without_default_sets_version_to_zero def test_readonly_attributes assert_equal Set.new([ "name" ]), ReadonlyNameShip.readonly_attributes - s = ReadonlyNameShip.create(:name => "unchangeable name") + s = ReadonlyNameShip.create(name: "unchangeable name") s.reload assert_equal "unchangeable name", s.name @@ -261,7 +261,7 @@ def test_quote_table_name # is nothing else being updated. def test_update_without_attributes_does_not_only_update_lock_version assert_nothing_raised do - p1 = Person.create!(:first_name => "anika") + p1 = Person.create!(first_name: "anika") lock_version = p1.lock_version p1.save p1.reload @@ -306,7 +306,7 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase # of a test (see test_increment_counter_*). self.use_transactional_tests = false - { :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model| + { lock_version: Person, custom_lock_version: LegacyThing }.each do |name, model| define_method("test_increment_counter_updates_#{name}") do counter_test model, 1 do |id| model.increment_counter :test_count, id @@ -321,7 +321,7 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase define_method("test_update_counters_updates_#{name}") do counter_test model, 1 do |id| - model.update_counters id, :test_count => 1 + model.update_counters id, test_count: 1 end end end @@ -333,9 +333,9 @@ def test_destroy_dependents PersonalLegacyThing.reset_column_information # Make sure that counter incrementing doesn't cause problems - p1 = Person.new(:first_name => "fjord") + p1 = Person.new(first_name: "fjord") p1.save! - t = PersonalLegacyThing.new(:person => p1) + t = PersonalLegacyThing.new(person: p1) t.save! p1.reload assert_equal 1, p1.personal_legacy_things_count @@ -351,7 +351,7 @@ def test_destroy_dependents private def add_counter_column_to(model, col="test_count") - model.connection.add_column model.table_name, col, :integer, :null => false, :default => 0 + model.connection.add_column model.table_name, col, :integer, null: false, default: 0 model.reset_column_information end diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb index 974a0ea8e2..7f6364bc57 100644 --- a/activerecord/test/cases/migration/change_schema_test.rb +++ b/activerecord/test/cases/migration/change_schema_test.rb @@ -40,7 +40,7 @@ def test_create_table_adds_id def test_create_table_with_not_null_column connection.create_table :testings do |t| - t.column :foo, :string, :null => false + t.column :foo, :string, null: false end assert_raises(ActiveRecord::StatementInvalid) do @@ -53,11 +53,11 @@ def test_create_table_with_defaults mysql = current_adapter?(:Mysql2Adapter) connection.create_table :testings do |t| - t.column :one, :string, :default => "hello" - t.column :two, :boolean, :default => true - t.column :three, :boolean, :default => false - t.column :four, :integer, :default => 1 - t.column :five, :text, :default => "hello" unless mysql + t.column :one, :string, default: "hello" + t.column :two, :boolean, default: true + t.column :three, :boolean, default: false + t.column :four, :integer, default: 1 + t.column :five, :text, default: "hello" unless mysql end columns = connection.columns(:testings) @@ -77,7 +77,7 @@ def test_create_table_with_defaults if current_adapter?(:PostgreSQLAdapter) def test_add_column_with_array connection.create_table :testings - connection.add_column :testings, :foo, :string, :array => true + connection.add_column :testings, :foo, :string, array: true columns = connection.columns(:testings) array_column = columns.detect { |c| c.name == "foo" } @@ -87,7 +87,7 @@ def test_add_column_with_array def test_create_table_with_array_column connection.create_table :testings do |t| - t.string :foo, :array => true + t.string :foo, array: true end columns = connection.columns(:testings) @@ -118,13 +118,13 @@ def test_create_table_with_bigint def test_create_table_with_limits connection.create_table :testings do |t| - t.column :foo, :string, :limit => 255 + t.column :foo, :string, limit: 255 t.column :default_int, :integer - t.column :one_int, :integer, :limit => 1 - t.column :four_int, :integer, :limit => 4 - t.column :eight_int, :integer, :limit => 8 + t.column :one_int, :integer, limit: 1 + t.column :four_int, :integer, limit: 4 + t.column :eight_int, :integer, limit: 8 end columns = connection.columns(:testings) @@ -231,7 +231,7 @@ def test_add_column_not_null_without_default connection.create_table :testings do |t| t.column :foo, :string end - connection.add_column :testings, :bar, :string, :null => false + connection.add_column :testings, :bar, :string, null: false assert_raise(ActiveRecord::StatementInvalid) do connection.execute "insert into testings (foo, bar) values ('hello', NULL)" @@ -246,7 +246,7 @@ def test_add_column_not_null_with_default con = connection connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}) values (1, 'hello')" - assert_nothing_raised {connection.add_column :testings, :bar, :string, :null => false, :default => "default" } + assert_nothing_raised {connection.add_column :testings, :bar, :string, null: false, default: "default" } assert_raises(ActiveRecord::StatementInvalid) do connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) values (2, 'hello', NULL)" @@ -275,7 +275,7 @@ def test_change_column_quotes_column_names t.column :select, :string end - connection.change_column :testings, :select, :string, :limit => 10 + connection.change_column :testings, :select, :string, limit: 10 # Oracle needs primary key value from sequence if current_adapter?(:OracleAdapter) @@ -292,7 +292,7 @@ def test_keeping_default_and_notnull_constraints_on_change person_klass = Class.new(ActiveRecord::Base) person_klass.table_name = "testings" - person_klass.connection.add_column "testings", "wealth", :integer, :null => false, :default => 99 + person_klass.connection.add_column "testings", "wealth", :integer, null: false, default: 99 person_klass.reset_column_information assert_equal 99, person_klass.column_defaults["wealth"] assert_equal false, person_klass.columns_hash["wealth"].null @@ -317,13 +317,13 @@ def test_keeping_default_and_notnull_constraints_on_change assert_equal false, person_klass.columns_hash["money"].null # change column - person_klass.connection.change_column "testings", "money", :integer, :null => false, :default => 1000 + person_klass.connection.change_column "testings", "money", :integer, null: false, default: 1000 person_klass.reset_column_information assert_equal 1000, person_klass.column_defaults["money"] assert_equal false, person_klass.columns_hash["money"].null # change column, make it nullable and clear default - person_klass.connection.change_column "testings", "money", :integer, :null => true, :default => nil + person_klass.connection.change_column "testings", "money", :integer, null: true, default: nil person_klass.reset_column_information assert_nil person_klass.columns_hash["money"].default assert_equal true, person_klass.columns_hash["money"].null @@ -365,7 +365,7 @@ def test_column_exists def test_column_exists_with_type connection.create_table :testings do |t| t.column :foo, :string - t.column :bar, :decimal, :precision => 8, :scale => 2 + t.column :bar, :decimal, precision: 8, scale: 2 end assert connection.column_exists?(:testings, :foo, :string) @@ -416,7 +416,7 @@ def test_drop_table_if_exists_nothing_raised private def testing_table_with_only_foo_attribute - connection.create_table :testings, :id => false do |t| + connection.create_table :testings, id: false do |t| t.column :foo, :string end diff --git a/activerecord/test/cases/migration/change_table_test.rb b/activerecord/test/cases/migration/change_table_test.rb index 2f9c50141f..045c18eb3f 100644 --- a/activerecord/test/cases/migration/change_table_test.rb +++ b/activerecord/test/cases/migration/change_table_test.rb @@ -157,8 +157,8 @@ def test_column_creates_column def test_column_creates_column_with_options with_change_table do |t| - @connection.expect :add_column, nil, [:delete_me, :bar, :integer, {:null => false}] - t.column :bar, :integer, :null => false + @connection.expect :add_column, nil, [:delete_me, :bar, :integer, {null: false}] + t.column :bar, :integer, null: false end end @@ -171,8 +171,8 @@ def test_index_creates_index def test_index_creates_index_with_options with_change_table do |t| - @connection.expect :add_index, nil, [:delete_me, :bar, {:unique => true}] - t.index :bar, :unique => true + @connection.expect :add_index, nil, [:delete_me, :bar, {unique: true}] + t.index :bar, unique: true end end @@ -185,8 +185,8 @@ def test_index_exists def test_index_exists_with_options with_change_table do |t| - @connection.expect :index_exists?, nil, [:delete_me, :bar, {:unique => true}] - t.index_exists?(:bar, :unique => true) + @connection.expect :index_exists?, nil, [:delete_me, :bar, {unique: true}] + t.index_exists?(:bar, unique: true) end end @@ -206,8 +206,8 @@ def test_change_changes_column def test_change_changes_column_with_options with_change_table do |t| - @connection.expect :change_column, nil, [:delete_me, :bar, :string, {:null => true}] - t.change :bar, :string, :null => true + @connection.expect :change_column, nil, [:delete_me, :bar, :string, {null: true}] + t.change :bar, :string, null: true end end @@ -234,8 +234,8 @@ def test_remove_drops_multiple_columns def test_remove_index_removes_index_with_options with_change_table do |t| - @connection.expect :remove_index, nil, [:delete_me, {:unique => true}] - t.remove_index :unique => true + @connection.expect :remove_index, nil, [:delete_me, {unique: true}] + t.remove_index unique: true end end diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb index 847000fa0e..ab8229dbae 100644 --- a/activerecord/test/cases/migration/column_attributes_test.rb +++ b/activerecord/test/cases/migration/column_attributes_test.rb @@ -9,7 +9,7 @@ class ColumnAttributesTest < ActiveRecord::TestCase def test_add_column_newline_default string = "foo\nbar" - add_column "test_models", "command", :string, :default => string + add_column "test_models", "command", :string, default: string TestModel.reset_column_information assert_equal string, TestModel.new.command @@ -58,7 +58,7 @@ def test_unabstracted_database_dependent_types def test_native_decimal_insert_manual_vs_automatic correct_value = "0012345678901234567890.0123456789".to_d - connection.add_column "test_models", "wealth", :decimal, :precision => "30", :scale => "10" + connection.add_column "test_models", "wealth", :decimal, precision: "30", scale: "10" # Do a manual insertion if current_adapter?(:OracleAdapter) @@ -82,7 +82,7 @@ def test_native_decimal_insert_manual_vs_automatic TestModel.delete_all # Now use the Rails insertion - TestModel.create :wealth => BigDecimal.new("12345678901234567890.0123456789") + TestModel.create wealth: BigDecimal.new("12345678901234567890.0123456789") # SELECT row = TestModel.first @@ -94,7 +94,7 @@ def test_native_decimal_insert_manual_vs_automatic end def test_add_column_with_precision_and_scale - connection.add_column "test_models", "wealth", :decimal, :precision => 9, :scale => 7 + connection.add_column "test_models", "wealth", :decimal, precision: 9, scale: 7 wealth_column = TestModel.columns_hash["wealth"] assert_equal 9, wealth_column.precision @@ -104,13 +104,13 @@ def test_add_column_with_precision_and_scale if current_adapter?(:SQLite3Adapter) def test_change_column_preserve_other_column_precision_and_scale connection.add_column "test_models", "last_name", :string - connection.add_column "test_models", "wealth", :decimal, :precision => 9, :scale => 7 + connection.add_column "test_models", "wealth", :decimal, precision: 9, scale: 7 wealth_column = TestModel.columns_hash["wealth"] assert_equal 9, wealth_column.precision assert_equal 7, wealth_column.scale - connection.change_column "test_models", "last_name", :string, :null => false + connection.change_column "test_models", "last_name", :string, null: false TestModel.reset_column_information wealth_column = TestModel.columns_hash["wealth"] @@ -126,17 +126,17 @@ def test_native_types add_column "test_models", "bio", :text add_column "test_models", "age", :integer add_column "test_models", "height", :float - add_column "test_models", "wealth", :decimal, :precision => "30", :scale => "10" + add_column "test_models", "wealth", :decimal, precision: "30", scale: "10" add_column "test_models", "birthday", :datetime add_column "test_models", "favorite_day", :date add_column "test_models", "moment_of_truth", :datetime add_column "test_models", "male", :boolean - TestModel.create :first_name => "bob", :last_name => "bobsen", - :bio => "I was born ....", :age => 18, :height => 1.78, - :wealth => BigDecimal.new("12345678901234567890.0123456789"), - :birthday => 18.years.ago, :favorite_day => 10.days.ago, - :moment_of_truth => "1782-10-10 21:40:18", :male => true + TestModel.create first_name: "bob", last_name: "bobsen", + bio: "I was born ....", age: 18, height: 1.78, + wealth: BigDecimal.new("12345678901234567890.0123456789"), + birthday: 18.years.ago, favorite_day: 10.days.ago, + moment_of_truth: "1782-10-10 21:40:18", male: true bob = TestModel.first assert_equal "bob", bob.first_name @@ -164,10 +164,10 @@ def test_native_types if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter) def test_out_of_range_limit_should_raise - assert_raise(ActiveRecordError) { add_column :test_models, :integer_too_big, :integer, :limit => 10 } + assert_raise(ActiveRecordError) { add_column :test_models, :integer_too_big, :integer, limit: 10 } unless current_adapter?(:PostgreSQLAdapter) - assert_raise(ActiveRecordError) { add_column :test_models, :text_too_big, :integer, :limit => 0xfffffffff } + assert_raise(ActiveRecordError) { add_column :test_models, :text_too_big, :integer, limit: 0xfffffffff } end end end diff --git a/activerecord/test/cases/migration/column_positioning_test.rb b/activerecord/test/cases/migration/column_positioning_test.rb index 0a4215fa78..f2162d91b1 100644 --- a/activerecord/test/cases/migration/column_positioning_test.rb +++ b/activerecord/test/cases/migration/column_positioning_test.rb @@ -11,7 +11,7 @@ def setup @connection = ActiveRecord::Base.connection - connection.create_table :testings, :id => false do |t| + connection.create_table :testings, id: false do |t| t.column :first, :integer t.column :second, :integer t.column :third, :integer @@ -34,20 +34,20 @@ def test_add_column_with_positioning end def test_add_column_with_positioning_first - conn.add_column :testings, :new_col, :integer, :first => true + conn.add_column :testings, :new_col, :integer, first: true assert_equal %w(new_col first second third), conn.columns(:testings).map(&:name) end def test_add_column_with_positioning_after - conn.add_column :testings, :new_col, :integer, :after => :first + conn.add_column :testings, :new_col, :integer, after: :first assert_equal %w(first new_col second third), conn.columns(:testings).map(&:name) end def test_change_column_with_positioning - conn.change_column :testings, :second, :integer, :first => true + conn.change_column :testings, :second, :integer, first: true assert_equal %w(second first third), conn.columns(:testings).map(&:name) - conn.change_column :testings, :second, :integer, :after => :third + conn.change_column :testings, :second, :integer, after: :third assert_equal %w(first third second), conn.columns(:testings).map(&:name) end end diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb index 7098eb1d2c..95c3f51539 100644 --- a/activerecord/test/cases/migration/columns_test.rb +++ b/activerecord/test/cases/migration/columns_test.rb @@ -13,7 +13,7 @@ def test_add_rename add_column "test_models", "girlfriend", :string TestModel.reset_column_information - TestModel.create :girlfriend => "bobette" + TestModel.create girlfriend: "bobette" rename_column "test_models", "girlfriend", "exgirlfriend" @@ -28,7 +28,7 @@ def test_add_rename def test_rename_column_using_symbol_arguments add_column :test_models, :first_name, :string - TestModel.create :first_name => "foo" + TestModel.create first_name: "foo" rename_column :test_models, :first_name, :nick_name TestModel.reset_column_information @@ -41,7 +41,7 @@ def test_rename_column_using_symbol_arguments def test_rename_column add_column "test_models", "first_name", "string" - TestModel.create :first_name => "foo" + TestModel.create first_name: "foo" rename_column "test_models", "first_name", "nick_name" TestModel.reset_column_information @@ -50,7 +50,7 @@ def test_rename_column end def test_rename_column_preserves_default_value_not_null - add_column "test_models", "salary", :integer, :default => 70000 + add_column "test_models", "salary", :integer, default: 70000 default_before = connection.columns("test_models").find { |c| c.name == "salary" }.default assert_equal "70000", default_before @@ -122,7 +122,7 @@ def test_rename_column_with_multi_column_index def test_rename_column_does_not_rename_custom_named_index add_column "test_models", :hat_name, :string - add_index :test_models, :hat_name, :name => "idx_hat_name" + add_index :test_models, :hat_name, name: "idx_hat_name" assert_equal 1, connection.indexes("test_models").size rename_column "test_models", "hat_name", "name" @@ -140,8 +140,8 @@ def test_remove_column_with_index def test_remove_column_with_multi_column_index add_column "test_models", :hat_size, :integer - add_column "test_models", :hat_style, :string, :limit => 100 - add_index "test_models", ["hat_style", "hat_size"], :unique => true + add_column "test_models", :hat_style, :string, limit: 100 + add_index "test_models", ["hat_style", "hat_size"], unique: true assert_equal 1, connection.indexes("test_models").size remove_column("test_models", "hat_size") @@ -156,32 +156,32 @@ def test_remove_column_with_multi_column_index end def test_change_type_of_not_null_column - change_column "test_models", "updated_at", :datetime, :null => false - change_column "test_models", "updated_at", :datetime, :null => false + change_column "test_models", "updated_at", :datetime, null: false + change_column "test_models", "updated_at", :datetime, null: false TestModel.reset_column_information assert_equal false, TestModel.columns_hash["updated_at"].null ensure - change_column "test_models", "updated_at", :datetime, :null => true + change_column "test_models", "updated_at", :datetime, null: true end def test_change_column_nullability add_column "test_models", "funny", :boolean assert TestModel.columns_hash["funny"].null, "Column 'funny' must initially allow nulls" - change_column "test_models", "funny", :boolean, :null => false, :default => true + change_column "test_models", "funny", :boolean, null: false, default: true TestModel.reset_column_information assert_not TestModel.columns_hash["funny"].null, "Column 'funny' must *not* allow nulls at this point" - change_column "test_models", "funny", :boolean, :null => true + change_column "test_models", "funny", :boolean, null: true TestModel.reset_column_information assert TestModel.columns_hash["funny"].null, "Column 'funny' must allow nulls again at this point" end def test_change_column add_column "test_models", "age", :integer - add_column "test_models", "approved", :boolean, :default => true + add_column "test_models", "approved", :boolean, default: true old_columns = connection.columns(TestModel.table_name) @@ -200,7 +200,7 @@ def test_change_column c.name == "approved" && c.type == :boolean && default == true } - change_column :test_models, :approved, :boolean, :default => false + change_column :test_models, :approved, :boolean, default: false new_columns = connection.columns(TestModel.table_name) assert_not new_columns.find { |c| @@ -211,24 +211,24 @@ def test_change_column default = connection.lookup_cast_type_from_column(c).deserialize(c.default) c.name == "approved" and c.type == :boolean and default == false } - change_column :test_models, :approved, :boolean, :default => true + change_column :test_models, :approved, :boolean, default: true end def test_change_column_with_nil_default - add_column "test_models", "contributor", :boolean, :default => true + add_column "test_models", "contributor", :boolean, default: true assert TestModel.new.contributor? - change_column "test_models", "contributor", :boolean, :default => nil + change_column "test_models", "contributor", :boolean, default: nil TestModel.reset_column_information assert_not TestModel.new.contributor? assert_nil TestModel.new.contributor end def test_change_column_with_new_default - add_column "test_models", "administrator", :boolean, :default => true + add_column "test_models", "administrator", :boolean, default: true assert TestModel.new.administrator? - change_column "test_models", "administrator", :boolean, :default => false + change_column "test_models", "administrator", :boolean, default: false TestModel.reset_column_information assert_not TestModel.new.administrator? end diff --git a/activerecord/test/cases/migration/compatibility_test.rb b/activerecord/test/cases/migration/compatibility_test.rb index bb249e5deb..0a4b604601 100644 --- a/activerecord/test/cases/migration/compatibility_test.rb +++ b/activerecord/test/cases/migration/compatibility_test.rb @@ -13,8 +13,8 @@ def setup ActiveRecord::Migration.verbose = false connection.create_table :testings do |t| - t.column :foo, :string, :limit => 100 - t.column :bar, :string, :limit => 100 + t.column :foo, :string, limit: 100 + t.column :bar, :string, limit: 100 end end @@ -25,7 +25,7 @@ def setup end def test_migration_doesnt_remove_named_index - connection.add_index :testings, :foo, :name => "custom_index_name" + connection.add_index :testings, :foo, name: "custom_index_name" migration = Class.new(ActiveRecord::Migration[4.2]) { def version; 101 end diff --git a/activerecord/test/cases/migration/index_test.rb b/activerecord/test/cases/migration/index_test.rb index d9b2bc9957..f59aec040f 100644 --- a/activerecord/test/cases/migration/index_test.rb +++ b/activerecord/test/cases/migration/index_test.rb @@ -11,12 +11,12 @@ def setup @table_name = :testings connection.create_table table_name do |t| - t.column :foo, :string, :limit => 100 - t.column :bar, :string, :limit => 100 + t.column :foo, :string, limit: 100 + t.column :bar, :string, limit: 100 t.string :first_name - t.string :last_name, :limit => 100 - t.string :key, :limit => 100 + t.string :last_name, limit: 100 + t.string :key, limit: 100 t.boolean :administrator end end @@ -28,7 +28,7 @@ def setup def test_rename_index # keep the names short to make Oracle and similar behave - connection.add_index(table_name, [:foo], :name => "old_idx") + connection.add_index(table_name, [:foo], name: "old_idx") connection.rename_index(table_name, "old_idx", "new_idx") # if the adapter doesn't support the indexes call, pick defaults that let the test pass @@ -39,7 +39,7 @@ def test_rename_index def test_rename_index_too_long too_long_index_name = good_index_name + "x" # keep the names short to make Oracle and similar behave - connection.add_index(table_name, [:foo], :name => "old_idx") + connection.add_index(table_name, [:foo], name: "old_idx") e = assert_raises(ArgumentError) { connection.rename_index(table_name, "old_idx", too_long_index_name) } @@ -51,9 +51,9 @@ def test_rename_index_too_long def test_double_add_index - connection.add_index(table_name, [:foo], :name => "some_idx") + connection.add_index(table_name, [:foo], name: "some_idx") assert_raises(ArgumentError) { - connection.add_index(table_name, [:foo], :name => "some_idx") + connection.add_index(table_name, [:foo], name: "some_idx") } end @@ -77,7 +77,7 @@ def test_add_index_does_not_accept_too_long_index_names assert_match(/too long; the limit is #{connection.allowed_index_name_length} characters/, e.message) assert_not connection.index_name_exists?(table_name, too_long_index_name, false) - connection.add_index(table_name, "foo", :name => good_index_name) + connection.add_index(table_name, "foo", name: good_index_name) end def test_internal_index_with_name_matching_database_limit @@ -89,11 +89,11 @@ def test_internal_index_with_name_matching_database_limit end def test_index_symbol_names - connection.add_index table_name, :foo, :name => :symbol_index_name - assert connection.index_exists?(table_name, :foo, :name => :symbol_index_name) + connection.add_index table_name, :foo, name: :symbol_index_name + assert connection.index_exists?(table_name, :foo, name: :symbol_index_name) - connection.remove_index table_name, :name => :symbol_index_name - assert_not connection.index_exists?(table_name, :foo, :name => :symbol_index_name) + connection.remove_index table_name, name: :symbol_index_name + assert_not connection.index_exists?(table_name, :foo, name: :symbol_index_name) end def test_index_exists @@ -122,21 +122,21 @@ def test_valid_index_options end def test_unique_index_exists - connection.add_index :testings, :foo, :unique => true + connection.add_index :testings, :foo, unique: true - assert connection.index_exists?(:testings, :foo, :unique => true) + assert connection.index_exists?(:testings, :foo, unique: true) end def test_named_index_exists - connection.add_index :testings, :foo, :name => "custom_index_name" + connection.add_index :testings, :foo, name: "custom_index_name" assert connection.index_exists?(:testings, :foo) - assert connection.index_exists?(:testings, :foo, :name => "custom_index_name") - assert !connection.index_exists?(:testings, :foo, :name => "other_index_name") + assert connection.index_exists?(:testings, :foo, name: "custom_index_name") + assert !connection.index_exists?(:testings, :foo, name: "other_index_name") end def test_remove_named_index - connection.add_index :testings, :foo, :name => "custom_index_name" + connection.add_index :testings, :foo, name: "custom_index_name" assert connection.index_exists?(:testings, :foo) connection.remove_index :testings, :foo @@ -144,7 +144,7 @@ def test_remove_named_index end def test_add_index_attribute_length_limit - connection.add_index :testings, [:foo, :bar], :length => {:foo => 10, :bar => nil} + connection.add_index :testings, [:foo, :bar], length: {foo: 10, bar: nil} assert connection.index_exists?(:testings, [:foo, :bar]) end @@ -154,53 +154,53 @@ def test_add_index connection.remove_index("testings", "last_name") connection.add_index("testings", ["last_name", "first_name"]) - connection.remove_index("testings", :column => ["last_name", "first_name"]) + connection.remove_index("testings", column: ["last_name", "first_name"]) # Oracle adapter cannot have specified index name larger than 30 characters # Oracle adapter is shortening index name when just column list is given unless current_adapter?(:OracleAdapter) connection.add_index("testings", ["last_name", "first_name"]) - connection.remove_index("testings", :name => :index_testings_on_last_name_and_first_name) + connection.remove_index("testings", name: :index_testings_on_last_name_and_first_name) connection.add_index("testings", ["last_name", "first_name"]) connection.remove_index("testings", "last_name_and_first_name") end connection.add_index("testings", ["last_name", "first_name"]) connection.remove_index("testings", ["last_name", "first_name"]) - connection.add_index("testings", ["last_name"], :length => 10) + connection.add_index("testings", ["last_name"], length: 10) connection.remove_index("testings", "last_name") - connection.add_index("testings", ["last_name"], :length => {:last_name => 10}) + connection.add_index("testings", ["last_name"], length: {last_name: 10}) connection.remove_index("testings", ["last_name"]) - connection.add_index("testings", ["last_name", "first_name"], :length => 10) + connection.add_index("testings", ["last_name", "first_name"], length: 10) connection.remove_index("testings", ["last_name", "first_name"]) - connection.add_index("testings", ["last_name", "first_name"], :length => {:last_name => 10, :first_name => 20}) + connection.add_index("testings", ["last_name", "first_name"], length: {last_name: 10, first_name: 20}) connection.remove_index("testings", ["last_name", "first_name"]) - connection.add_index("testings", ["key"], :name => "key_idx", :unique => true) - connection.remove_index("testings", :name => "key_idx", :unique => true) + connection.add_index("testings", ["key"], name: "key_idx", unique: true) + connection.remove_index("testings", name: "key_idx", unique: true) - connection.add_index("testings", %w(last_name first_name administrator), :name => "named_admin") - connection.remove_index("testings", :name => "named_admin") + connection.add_index("testings", %w(last_name first_name administrator), name: "named_admin") + connection.remove_index("testings", name: "named_admin") # Selected adapters support index sort order if current_adapter?(:SQLite3Adapter, :Mysql2Adapter, :PostgreSQLAdapter) - connection.add_index("testings", ["last_name"], :order => {:last_name => :desc}) + connection.add_index("testings", ["last_name"], order: {last_name: :desc}) connection.remove_index("testings", ["last_name"]) - connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc}) + connection.add_index("testings", ["last_name", "first_name"], order: {last_name: :desc}) connection.remove_index("testings", ["last_name", "first_name"]) - connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc, :first_name => :asc}) + connection.add_index("testings", ["last_name", "first_name"], order: {last_name: :desc, first_name: :asc}) connection.remove_index("testings", ["last_name", "first_name"]) - connection.add_index("testings", ["last_name", "first_name"], :order => :desc) + connection.add_index("testings", ["last_name", "first_name"], order: :desc) connection.remove_index("testings", ["last_name", "first_name"]) end end if current_adapter?(:PostgreSQLAdapter) def test_add_partial_index - connection.add_index("testings", "last_name", :where => "first_name = 'john doe'") + connection.add_index("testings", "last_name", where: "first_name = 'john doe'") assert connection.index_exists?("testings", "last_name") connection.remove_index("testings", "last_name") diff --git a/activerecord/test/cases/migration/references_index_test.rb b/activerecord/test/cases/migration/references_index_test.rb index 481fe42a8b..0d0b0a193b 100644 --- a/activerecord/test/cases/migration/references_index_test.rb +++ b/activerecord/test/cases/migration/references_index_test.rb @@ -17,10 +17,10 @@ def setup def test_creates_index connection.create_table table_name do |t| - t.references :foo, :index => true + t.references :foo, index: true end - assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id) + assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id) end def test_creates_index_by_default_even_if_index_option_is_not_passed @@ -28,31 +28,31 @@ def test_creates_index_by_default_even_if_index_option_is_not_passed t.references :foo end - assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id) + assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id) end def test_does_not_create_index_explicit connection.create_table table_name do |t| - t.references :foo, :index => false + t.references :foo, index: false end - assert_not connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id) + assert_not connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id) end def test_creates_index_with_options connection.create_table table_name do |t| - t.references :foo, :index => {:name => :index_testings_on_yo_momma} - t.references :bar, :index => {:unique => true} + t.references :foo, index: {name: :index_testings_on_yo_momma} + t.references :bar, index: {unique: true} end - assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_yo_momma) - assert connection.index_exists?(table_name, :bar_id, :name => :index_testings_on_bar_id, :unique => true) + assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_yo_momma) + assert connection.index_exists?(table_name, :bar_id, name: :index_testings_on_bar_id, unique: true) end unless current_adapter? :OracleAdapter def test_creates_polymorphic_index connection.create_table table_name do |t| - t.references :foo, :polymorphic => true, :index => true + t.references :foo, polymorphic: true, index: true end assert connection.index_exists?(table_name, [:foo_type, :foo_id], name: :index_testings_on_foo_type_and_foo_id) @@ -62,10 +62,10 @@ def test_creates_polymorphic_index def test_creates_index_for_existing_table connection.create_table table_name connection.change_table table_name do |t| - t.references :foo, :index => true + t.references :foo, index: true end - assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id) + assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id) end def test_creates_index_for_existing_table_even_if_index_option_is_not_passed @@ -74,23 +74,23 @@ def test_creates_index_for_existing_table_even_if_index_option_is_not_passed t.references :foo end - assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id) + assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id) end def test_does_not_create_index_for_existing_table_explicit connection.create_table table_name connection.change_table table_name do |t| - t.references :foo, :index => false + t.references :foo, index: false end - assert_not connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id) + assert_not connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id) end unless current_adapter? :OracleAdapter def test_creates_polymorphic_index_for_existing_table connection.create_table table_name connection.change_table table_name do |t| - t.references :foo, :polymorphic => true, :index => true + t.references :foo, polymorphic: true, index: true end assert connection.index_exists?(table_name, [:foo_type, :foo_id], name: :index_testings_on_foo_type_and_foo_id) diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index edfde0a52b..61c754fc0e 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -128,7 +128,7 @@ def test_create_table_with_force_true_does_not_drop_nonexisting_table assert_not_equal temp_conn, Person.connection - temp_conn.create_table :testings2, :force => true do |t| + temp_conn.create_table :testings2, force: true do |t| t.column :foo, :string end ensure @@ -160,11 +160,11 @@ def test_add_table_with_decimals BigNumber.reset_column_information assert BigNumber.create( - :bank_balance => 1586.43, - :big_bank_balance => BigDecimal("1000234000567.95"), - :world_population => 6000000000, - :my_house_population => 3, - :value_of_e => BigDecimal("2.7182818284590452353602875") + bank_balance: 1586.43, + big_bank_balance: BigDecimal("1000234000567.95"), + world_population: 6000000000, + my_house_population: 3, + value_of_e: BigDecimal("2.7182818284590452353602875") ) b = BigNumber.first @@ -514,7 +514,7 @@ def test_add_drop_table_with_prefix_and_suffix def test_create_table_with_binary_column assert_nothing_raised { Person.connection.create_table :binary_testings do |t| - t.column "data", :binary, :null => false + t.column "data", :binary, null: false end } @@ -559,7 +559,7 @@ def test_create_table_with_custom_sequence_name assert_nothing_raised do begin Person.connection.create_table :table_with_name_thats_just_ok do |t| - t.column :foo, :string, :null => false + t.column :foo, :string, null: false end ensure Person.connection.drop_table :table_with_name_thats_just_ok rescue nil @@ -570,15 +570,15 @@ def test_create_table_with_custom_sequence_name assert_nothing_raised do begin Person.connection.create_table :table_with_name_thats_just_ok, - :sequence_name => "suitably_short_seq" do |t| - t.column :foo, :string, :null => false + sequence_name: "suitably_short_seq" do |t| + t.column :foo, :string, null: false end Person.connection.execute("select suitably_short_seq.nextval from dual") ensure Person.connection.drop_table :table_with_name_thats_just_ok, - :sequence_name => "suitably_short_seq" rescue nil + sequence_name: "suitably_short_seq" rescue nil end end @@ -592,8 +592,8 @@ def test_create_table_with_custom_sequence_name if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter) def test_out_of_range_integer_limit_should_raise e = assert_raise(ActiveRecord::ActiveRecordError, "integer limit didn't raise") do - Person.connection.create_table :test_integer_limits, :force => true do |t| - t.column :bigone, :integer, :limit => 10 + Person.connection.create_table :test_integer_limits, force: true do |t| + t.column :bigone, :integer, limit: 10 end end @@ -727,13 +727,13 @@ def with_another_process_holding_lock(lock_id) class ReservedWordsMigrationTest < ActiveRecord::TestCase def test_drop_index_from_table_named_values connection = Person.connection - connection.create_table :values, :force => true do |t| + connection.create_table :values, force: true do |t| t.integer :value end assert_nothing_raised do connection.add_index :values, :value - connection.remove_index :values, :column => :value + connection.remove_index :values, column: :value end ensure connection.drop_table :values rescue nil @@ -760,7 +760,7 @@ def test_drop_index_by_name class BulkAlterTableMigrationsTest < ActiveRecord::TestCase def setup @connection = Person.connection - @connection.create_table(:delete_me, :force => true) {|t| } + @connection.create_table(:delete_me, force: true) {|t| } Person.reset_column_information Person.reset_sequence_name end @@ -774,7 +774,7 @@ def test_adding_multiple_columns with_bulk_change_table do |t| t.column :name, :string t.string :qualification, :experience - t.integer :age, :default => 0 + t.integer :age, default: 0 t.date :birthdate t.timestamps null: true end @@ -813,7 +813,7 @@ def test_adding_indexes # Adding an index fires a query every time to check if an index already exists or not assert_queries(3) do with_bulk_change_table do |t| - t.index :username, :unique => true, :name => :awesome_username_index + t.index :username, unique: true, name: :awesome_username_index t.index [:name, :age] end end @@ -838,7 +838,7 @@ def test_removing_index assert_queries(3) do with_bulk_change_table do |t| t.remove_index :name - t.index :name, :name => :new_name_index, :unique => true + t.index :name, name: :new_name_index, unique: true end end @@ -860,9 +860,9 @@ def test_changing_columns # One query for columns (delete_me table) # One query for primary key (delete_me table) # One query to do the bulk change - assert_queries(3, :ignore_none => true) do + assert_queries(3, ignore_none: true) do with_bulk_change_table do |t| - t.change :name, :string, :default => "NONAME" + t.change :name, :string, default: "NONAME" t.change :birthdate, :datetime end end @@ -877,7 +877,7 @@ def with_bulk_change_table # Reset columns/indexes cache as we're changing the table @columns = @indexes = nil - Person.connection.change_table(:delete_me, :bulk => true) do |t| + Person.connection.change_table(:delete_me, bulk: true) do |t| yield t end end @@ -918,7 +918,7 @@ def test_copying_migrations_without_timestamps @migrations_path = MIGRATIONS_ROOT + "/valid" @existing_migrations = Dir[@migrations_path + "/*.rb"] - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy"}) assert File.exist?(@migrations_path + "/4_people_have_hobbies.bukkits.rb") assert File.exist?(@migrations_path + "/5_people_have_descriptions.bukkits.rb") assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename) @@ -927,7 +927,7 @@ def test_copying_migrations_without_timestamps assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp files_count = Dir[@migrations_path + "/*.rb"].length - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy"}) assert_equal files_count, Dir[@migrations_path + "/*.rb"].length assert copied.empty? ensure @@ -960,7 +960,7 @@ def test_copying_migrations_with_timestamps @existing_migrations = Dir[@migrations_path + "/*.rb"] travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb", @@ -968,7 +968,7 @@ def test_copying_migrations_with_timestamps assert_equal expected, copied.map(&:filename) files_count = Dir[@migrations_path + "/*.rb"].length - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) assert_equal files_count, Dir[@migrations_path + "/*.rb"].length assert copied.empty? end @@ -1005,12 +1005,12 @@ def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_fu @existing_migrations = Dir[@migrations_path + "/*.rb"] travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do - ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) assert File.exist?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb") assert File.exist?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb") files_count = Dir[@migrations_path + "/*.rb"].length - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) assert_equal files_count, Dir[@migrations_path + "/*.rb"].length assert copied.empty? end @@ -1023,7 +1023,7 @@ def test_copying_migrations_preserving_magic_comments @migrations_path = MIGRATIONS_ROOT + "/valid" @existing_migrations = Dir[@migrations_path + "/*.rb"] - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/magic"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/magic"}) assert File.exist?(@migrations_path + "/4_currencies_have_symbols.bukkits.rb") assert_equal [@migrations_path + "/4_currencies_have_symbols.bukkits.rb"], copied.map(&:filename) @@ -1031,7 +1031,7 @@ def test_copying_migrations_preserving_magic_comments assert_equal expected, IO.readlines(@migrations_path + "/4_currencies_have_symbols.bukkits.rb")[0..1].join.chomp files_count = Dir[@migrations_path + "/*.rb"].length - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/magic"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/magic"}) assert_equal files_count, Dir[@migrations_path + "/*.rb"].length assert copied.empty? ensure @@ -1048,7 +1048,7 @@ def test_skipping_migrations skipped = [] on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" } - copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) + copied = ActiveRecord::Migration.copy(@migrations_path, sources, on_skip: on_skip) assert_equal 2, copied.length assert_equal 1, skipped.length @@ -1066,8 +1066,8 @@ def test_skip_is_not_called_if_migrations_are_from_the_same_plugin skipped = [] on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" } - copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) - ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) + copied = ActiveRecord::Migration.copy(@migrations_path, sources, on_skip: on_skip) + ActiveRecord::Migration.copy(@migrations_path, sources, on_skip: on_skip) assert_equal 2, copied.length assert_equal 0, skipped.length @@ -1080,7 +1080,7 @@ def test_copying_migrations_to_non_existing_directory @existing_migrations = [] travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") assert_equal 2, copied.length @@ -1095,7 +1095,7 @@ def test_copying_migrations_to_empty_directory @existing_migrations = [] travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do - copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) + copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") assert_equal 2, copied.length diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb index 8e73deb80c..67af04e2e8 100644 --- a/activerecord/test/cases/migrator_test.rb +++ b/activerecord/test/cases/migrator_test.rb @@ -115,7 +115,7 @@ def test_relative_migrations end def test_finds_pending_migrations - ActiveRecord::SchemaMigration.create!(:version => "1") + ActiveRecord::SchemaMigration.create!(version: "1") migration_list = [ActiveRecord::Migration.new("foo", 1), ActiveRecord::Migration.new("bar", 3)] migrations = ActiveRecord::Migrator.new(:up, migration_list).pending_migrations @@ -165,7 +165,7 @@ def test_down_calls_down end def test_current_version - ActiveRecord::SchemaMigration.create!(:version => "1000") + ActiveRecord::SchemaMigration.create!(version: "1000") assert_equal 1000, ActiveRecord::Migrator.current_version end @@ -332,7 +332,7 @@ def test_migrator_forward def test_only_loads_pending_migrations # migrate up to 1 - ActiveRecord::SchemaMigration.create!(:version => "1") + ActiveRecord::SchemaMigration.create!(version: "1") calls, migrator = migrator_class(3) migrator.migrate("valid", nil) diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb index 870eda45ed..1b7720e4f8 100644 --- a/activerecord/test/cases/modules_test.rb +++ b/activerecord/test/cases/modules_test.rb @@ -41,7 +41,7 @@ def test_module_spanning_has_and_belongs_to_many_associations end def test_associations_spanning_cross_modules - account = MyApplication::Billing::Account.all.merge!(:order => "id").first + account = MyApplication::Billing::Account.all.merge!(order: "id").first assert_kind_of MyApplication::Business::Firm, account.firm assert_kind_of MyApplication::Billing::Firm, account.qualified_billing_firm assert_kind_of MyApplication::Billing::Firm, account.unqualified_billing_firm @@ -50,7 +50,7 @@ def test_associations_spanning_cross_modules end def test_find_account_and_include_company - account = MyApplication::Billing::Account.all.merge!(:includes => :firm).find(1) + account = MyApplication::Billing::Account.all.merge!(includes: :firm).find(1) assert_kind_of MyApplication::Business::Firm, account.firm end @@ -73,8 +73,8 @@ def test_eager_loading_in_modules clients = [] assert_nothing_raised do - clients << MyApplication::Business::Client.references(:accounts).merge!(:includes => {:firm => :account}, :where => "accounts.id IS NOT NULL").find(3) - clients << MyApplication::Business::Client.includes(:firm => :account).find(3) + clients << MyApplication::Business::Client.references(:accounts).merge!(includes: {firm: :account}, where: "accounts.id IS NOT NULL").find(3) + clients << MyApplication::Business::Client.includes(firm: :account).find(3) end clients.each do |client| diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index c72890aa2b..d1ff270b07 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -13,7 +13,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase teardown do - Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?) + Pirate.accepts_nested_attributes_for :ship, allow_destroy: true, reject_if: proc(&:empty?) end def test_base_should_have_an_empty_nested_attributes_options @@ -30,24 +30,24 @@ def test_should_add_a_proc_to_nested_attributes_options end def test_should_not_build_a_new_record_using_reject_all_even_if_destroy_is_given - pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") - pirate.birds_with_reject_all_blank_attributes = [{:name => "", :color => "", :_destroy => "0"}] + pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") + pirate.birds_with_reject_all_blank_attributes = [{name: "", color: "", _destroy: "0"}] pirate.save! assert pirate.birds_with_reject_all_blank.empty? end def test_should_not_build_a_new_record_if_reject_all_blank_returns_false - pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") - pirate.birds_with_reject_all_blank_attributes = [{:name => "", :color => ""}] + pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") + pirate.birds_with_reject_all_blank_attributes = [{name: "", color: ""}] pirate.save! assert pirate.birds_with_reject_all_blank.empty? end def test_should_build_a_new_record_if_reject_all_blank_does_not_return_false - pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") - pirate.birds_with_reject_all_blank_attributes = [{:name => "Tweetie", :color => ""}] + pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") + pirate.birds_with_reject_all_blank_attributes = [{name: "Tweetie", color: ""}] pirate.save! assert_equal 1, pirate.birds_with_reject_all_blank.count @@ -63,7 +63,7 @@ def test_should_raise_an_ArgumentError_for_non_existing_associations def test_should_raise_an_UnknownAttributeError_for_non_existing_nested_attributes exception = assert_raise ActiveModel::UnknownAttributeError do - Pirate.new(:ship_attributes => { :sail => true }) + Pirate.new(ship_attributes: { sail: true }) end assert_equal "unknown attribute 'sail' for Ship.", exception.message end @@ -80,43 +80,43 @@ def test_should_disable_allow_destroy_by_default end def test_a_model_should_respond_to_underscore_destroy_and_return_if_it_is_marked_for_destruction - ship = Ship.create!(:name => "Nights Dirty Lightning") + ship = Ship.create!(name: "Nights Dirty Lightning") assert !ship._destroy ship.mark_for_destruction assert ship._destroy end def test_reject_if_method_without_arguments - Pirate.accepts_nested_attributes_for :ship, :reject_if => :new_record? + Pirate.accepts_nested_attributes_for :ship, reject_if: :new_record? - pirate = Pirate.new(:catchphrase => "Stop wastin' me time") - pirate.ship_attributes = { :name => "Black Pearl" } + pirate = Pirate.new(catchphrase: "Stop wastin' me time") + pirate.ship_attributes = { name: "Black Pearl" } assert_no_difference("Ship.count") { pirate.save! } end def test_reject_if_method_with_arguments - Pirate.accepts_nested_attributes_for :ship, :reject_if => :reject_empty_ships_on_create + Pirate.accepts_nested_attributes_for :ship, reject_if: :reject_empty_ships_on_create - pirate = Pirate.new(:catchphrase => "Stop wastin' me time") - pirate.ship_attributes = { :name => "Red Pearl", :_reject_me_if_new => true } + pirate = Pirate.new(catchphrase: "Stop wastin' me time") + pirate.ship_attributes = { name: "Red Pearl", _reject_me_if_new: true } assert_no_difference("Ship.count") { pirate.save! } # pirate.reject_empty_ships_on_create returns false for saved pirate records # in the previous step note that pirate gets saved but ship fails - pirate.ship_attributes = { :name => "Red Pearl", :_reject_me_if_new => true } + pirate.ship_attributes = { name: "Red Pearl", _reject_me_if_new: true } assert_difference("Ship.count") { pirate.save! } end def test_reject_if_with_indifferent_keys - Pirate.accepts_nested_attributes_for :ship, :reject_if => proc {|attributes| attributes[:name].blank? } + Pirate.accepts_nested_attributes_for :ship, reject_if: proc {|attributes| attributes[:name].blank? } - pirate = Pirate.new(:catchphrase => "Stop wastin' me time") - pirate.ship_attributes = { :name => "Hello Pearl" } + pirate = Pirate.new(catchphrase: "Stop wastin' me time") + pirate.ship_attributes = { name: "Hello Pearl" } assert_difference("Ship.count") { pirate.save! } end def test_reject_if_with_a_proc_which_returns_true_always_for_has_one - Pirate.accepts_nested_attributes_for :ship, :reject_if => proc {|attributes| true } + Pirate.accepts_nested_attributes_for :ship, reject_if: proc {|attributes| true } pirate = Pirate.new(catchphrase: "Stop wastin' me time") ship = pirate.create_ship(name: "s1") pirate.update({ship_attributes: { name: "s2", id: ship.id } }) @@ -138,7 +138,7 @@ def test_do_not_allow_assigning_foreign_key_when_reusing_existing_new_record end def test_reject_if_with_a_proc_which_returns_true_always_for_has_many - Man.accepts_nested_attributes_for :interests, :reject_if => proc {|attributes| true } + Man.accepts_nested_attributes_for :interests, reject_if: proc {|attributes| true } man = Man.create(name: "John") interest = man.interests.create(topic: "photography") man.update({interests_attributes: { topic: "gardening", id: interest.id } }) @@ -146,7 +146,7 @@ def test_reject_if_with_a_proc_which_returns_true_always_for_has_many end def test_destroy_works_independent_of_reject_if - Man.accepts_nested_attributes_for :interests, :reject_if => proc {|attributes| true }, :allow_destroy => true + Man.accepts_nested_attributes_for :interests, reject_if: proc {|attributes| true }, allow_destroy: true man = Man.create(name: "Jon") interest = man.interests.create(topic: "the ladies") man.update({interests_attributes: { _destroy: "1", id: interest.id } }) @@ -176,19 +176,19 @@ def test_has_many_association_updating_a_single_record def test_reject_if_with_blank_nested_attributes_id # When using a select list to choose an existing 'ship' id, with include_blank: true - Pirate.accepts_nested_attributes_for :ship, :reject_if => proc {|attributes| attributes[:id].blank? } + Pirate.accepts_nested_attributes_for :ship, reject_if: proc {|attributes| attributes[:id].blank? } - pirate = Pirate.new(:catchphrase => "Stop wastin' me time") - pirate.ship_attributes = { :id => "" } + pirate = Pirate.new(catchphrase: "Stop wastin' me time") + pirate.ship_attributes = { id: "" } assert_nothing_raised { pirate.save! } end def test_first_and_array_index_zero_methods_return_the_same_value_when_nested_attributes_are_set_to_update_existing_record Man.accepts_nested_attributes_for(:interests) - man = Man.create(:name => "John") - interest = man.interests.create :topic => "gardening" + man = Man.create(name: "John") + interest = man.interests.create topic: "gardening" man = Man.find man.id - man.interests_attributes = [{:id => interest.id, :topic => "gardening"}] + man.interests_attributes = [{id: interest.id, topic: "gardening"}] assert_equal man.interests.first.topic, man.interests[0].topic end @@ -196,11 +196,11 @@ def test_allows_class_to_override_setter_and_call_super mean_pirate_class = Class.new(Pirate) do accepts_nested_attributes_for :parrot def parrot_attributes=(attrs) - super(attrs.merge(:color => "blue")) + super(attrs.merge(color: "blue")) end end mean_pirate = mean_pirate_class.new - mean_pirate.parrot_attributes = { :name => "James" } + mean_pirate.parrot_attributes = { name: "James" } assert_equal "James", mean_pirate.parrot.name assert_equal "blue", mean_pirate.parrot.color end @@ -212,20 +212,20 @@ def test_accepts_nested_attributes_for_can_be_overridden_in_subclasses accepts_nested_attributes_for :parrot end mean_pirate = mean_pirate_class.new - mean_pirate.parrot_attributes = { :name => "James" } + mean_pirate.parrot_attributes = { name: "James" } assert_equal "James", mean_pirate.parrot.name end end class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase def setup - @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @ship = @pirate.create_ship(:name => "Nights Dirty Lightning") + @pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") + @ship = @pirate.create_ship(name: "Nights Dirty Lightning") end def test_should_raise_argument_error_if_trying_to_build_polymorphic_belongs_to exception = assert_raise ArgumentError do - Treasure.new(:name => "pearl", :looter_attributes => {:catchphrase => "Arrr"}) + Treasure.new(name: "pearl", looter_attributes: {catchphrase: "Arrr"}) end assert_equal "Cannot build association `looter'. Are you trying to build a polymorphic one-to-one association?", exception.message end @@ -236,7 +236,7 @@ def test_should_define_an_attribute_writer_method_for_the_association def test_should_build_a_new_record_if_there_is_no_id @ship.destroy - @pirate.reload.ship_attributes = { :name => "Davy Jones Gold Dagger" } + @pirate.reload.ship_attributes = { name: "Davy Jones Gold Dagger" } assert !@pirate.ship.persisted? assert_equal "Davy Jones Gold Dagger", @pirate.ship.name @@ -244,7 +244,7 @@ def test_should_build_a_new_record_if_there_is_no_id def test_should_not_build_a_new_record_if_there_is_no_id_and_destroy_is_truthy @ship.destroy - @pirate.reload.ship_attributes = { :name => "Davy Jones Gold Dagger", :_destroy => "1" } + @pirate.reload.ship_attributes = { name: "Davy Jones Gold Dagger", _destroy: "1" } assert_nil @pirate.ship end @@ -257,7 +257,7 @@ def test_should_not_build_a_new_record_if_a_reject_if_proc_returns_false end def test_should_replace_an_existing_record_if_there_is_no_id - @pirate.reload.ship_attributes = { :name => "Davy Jones Gold Dagger" } + @pirate.reload.ship_attributes = { name: "Davy Jones Gold Dagger" } assert !@pirate.ship.persisted? assert_equal "Davy Jones Gold Dagger", @pirate.ship.name @@ -265,14 +265,14 @@ def test_should_replace_an_existing_record_if_there_is_no_id end def test_should_not_replace_an_existing_record_if_there_is_no_id_and_destroy_is_truthy - @pirate.reload.ship_attributes = { :name => "Davy Jones Gold Dagger", :_destroy => "1" } + @pirate.reload.ship_attributes = { name: "Davy Jones Gold Dagger", _destroy: "1" } assert_equal @ship, @pirate.ship assert_equal "Nights Dirty Lightning", @pirate.ship.name end def test_should_modify_an_existing_record_if_there_is_a_matching_id - @pirate.reload.ship_attributes = { :id => @ship.id, :name => "Davy Jones Gold Dagger" } + @pirate.reload.ship_attributes = { id: @ship.id, name: "Davy Jones Gold Dagger" } assert_equal @ship, @pirate.ship assert_equal "Davy Jones Gold Dagger", @pirate.ship.name @@ -280,7 +280,7 @@ def test_should_modify_an_existing_record_if_there_is_a_matching_id def test_should_raise_RecordNotFound_if_an_id_is_given_but_doesnt_return_a_record exception = assert_raise ActiveRecord::RecordNotFound do - @pirate.ship_attributes = { :id => 1234567890 } + @pirate.ship_attributes = { id: 1234567890 } end assert_equal "Couldn't find Ship with ID=1234567890 for Pirate with ID=#{@pirate.id}", exception.message end @@ -294,7 +294,7 @@ def test_should_take_a_hash_with_string_keys_and_update_the_associated_model def test_should_modify_an_existing_record_if_there_is_a_matching_composite_id @ship.stub(:id, "ABC1X") do - @pirate.ship_attributes = { :id => @ship.id, :name => "Davy Jones Gold Dagger" } + @pirate.ship_attributes = { id: @ship.id, name: "Davy Jones Gold Dagger" } assert_equal "Davy Jones Gold Dagger", @pirate.ship.name end @@ -321,17 +321,17 @@ def test_should_not_destroy_an_existing_record_if_destroy_is_not_truthy end def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false - Pirate.accepts_nested_attributes_for :ship, :allow_destroy => false, :reject_if => proc(&:empty?) + Pirate.accepts_nested_attributes_for :ship, allow_destroy: false, reject_if: proc(&:empty?) @pirate.update(ship_attributes: { id: @pirate.ship.id, _destroy: "1" }) assert_equal @ship, @pirate.reload.ship - Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?) + Pirate.accepts_nested_attributes_for :ship, allow_destroy: true, reject_if: proc(&:empty?) end def test_should_also_work_with_a_HashWithIndifferentAccess - @pirate.ship_attributes = ActiveSupport::HashWithIndifferentAccess.new(:id => @ship.id, :name => "Davy Jones Gold Dagger") + @pirate.ship_attributes = ActiveSupport::HashWithIndifferentAccess.new(id: @ship.id, name: "Davy Jones Gold Dagger") assert @pirate.ship.persisted? assert_equal "Davy Jones Gold Dagger", @pirate.ship.name @@ -346,7 +346,7 @@ def test_should_work_with_update_as_well end def test_should_not_destroy_the_associated_model_until_the_parent_is_saved - @pirate.attributes = { :ship_attributes => { :id => @ship.id, :_destroy => "1" } } + @pirate.attributes = { ship_attributes: { id: @ship.id, _destroy: "1" } } assert !@pirate.ship.destroyed? assert @pirate.ship.marked_for_destruction? @@ -394,7 +394,7 @@ def test_should_update_existing_when_update_only_is_true_and_id_is_given end def test_should_destroy_existing_when_update_only_is_true_and_id_is_given_and_is_marked_for_destruction - Pirate.accepts_nested_attributes_for :update_only_ship, :update_only => true, :allow_destroy => true + Pirate.accepts_nested_attributes_for :update_only_ship, update_only: true, allow_destroy: true @ship.delete @ship = @pirate.create_update_only_ship(name: "Nights Dirty Lightning") @@ -403,15 +403,15 @@ def test_should_destroy_existing_when_update_only_is_true_and_id_is_given_and_is assert_nil @pirate.reload.ship assert_raise(ActiveRecord::RecordNotFound) { Ship.find(@ship.id) } - Pirate.accepts_nested_attributes_for :update_only_ship, :update_only => true, :allow_destroy => false + Pirate.accepts_nested_attributes_for :update_only_ship, update_only: true, allow_destroy: false end end class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase def setup - @ship = Ship.new(:name => "Nights Dirty Lightning") - @pirate = @ship.build_pirate(:catchphrase => "Aye") + @ship = Ship.new(name: "Nights Dirty Lightning") + @pirate = @ship.build_pirate(catchphrase: "Aye") @ship.save! end @@ -421,7 +421,7 @@ def test_should_define_an_attribute_writer_method_for_the_association def test_should_build_a_new_record_if_there_is_no_id @pirate.destroy - @ship.reload.pirate_attributes = { :catchphrase => "Arr" } + @ship.reload.pirate_attributes = { catchphrase: "Arr" } assert !@ship.pirate.persisted? assert_equal "Arr", @ship.pirate.catchphrase @@ -429,7 +429,7 @@ def test_should_build_a_new_record_if_there_is_no_id def test_should_not_build_a_new_record_if_there_is_no_id_and_destroy_is_truthy @pirate.destroy - @ship.reload.pirate_attributes = { :catchphrase => "Arr", :_destroy => "1" } + @ship.reload.pirate_attributes = { catchphrase: "Arr", _destroy: "1" } assert_nil @ship.pirate end @@ -442,7 +442,7 @@ def test_should_not_build_a_new_record_if_a_reject_if_proc_returns_false end def test_should_replace_an_existing_record_if_there_is_no_id - @ship.reload.pirate_attributes = { :catchphrase => "Arr" } + @ship.reload.pirate_attributes = { catchphrase: "Arr" } assert !@ship.pirate.persisted? assert_equal "Arr", @ship.pirate.catchphrase @@ -450,14 +450,14 @@ def test_should_replace_an_existing_record_if_there_is_no_id end def test_should_not_replace_an_existing_record_if_there_is_no_id_and_destroy_is_truthy - @ship.reload.pirate_attributes = { :catchphrase => "Arr", :_destroy => "1" } + @ship.reload.pirate_attributes = { catchphrase: "Arr", _destroy: "1" } assert_equal @pirate, @ship.pirate assert_equal "Aye", @ship.pirate.catchphrase end def test_should_modify_an_existing_record_if_there_is_a_matching_id - @ship.reload.pirate_attributes = { :id => @pirate.id, :catchphrase => "Arr" } + @ship.reload.pirate_attributes = { id: @pirate.id, catchphrase: "Arr" } assert_equal @pirate, @ship.pirate assert_equal "Arr", @ship.pirate.catchphrase @@ -465,7 +465,7 @@ def test_should_modify_an_existing_record_if_there_is_a_matching_id def test_should_raise_RecordNotFound_if_an_id_is_given_but_doesnt_return_a_record exception = assert_raise ActiveRecord::RecordNotFound do - @ship.pirate_attributes = { :id => 1234567890 } + @ship.pirate_attributes = { id: 1234567890 } end assert_equal "Couldn't find Pirate with ID=1234567890 for Ship with ID=#{@ship.id}", exception.message end @@ -479,7 +479,7 @@ def test_should_take_a_hash_with_string_keys_and_update_the_associated_model def test_should_modify_an_existing_record_if_there_is_a_matching_composite_id @pirate.stub(:id, "ABC1X") do - @ship.pirate_attributes = { :id => @pirate.id, :catchphrase => "Arr" } + @ship.pirate_attributes = { id: @pirate.id, catchphrase: "Arr" } assert_equal "Arr", @ship.pirate.catchphrase end @@ -516,12 +516,12 @@ def test_should_not_destroy_an_existing_record_if_destroy_is_not_truthy end def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false - Ship.accepts_nested_attributes_for :pirate, :allow_destroy => false, :reject_if => proc(&:empty?) + Ship.accepts_nested_attributes_for :pirate, allow_destroy: false, reject_if: proc(&:empty?) @ship.update(pirate_attributes: { id: @ship.pirate.id, _destroy: "1" }) assert_nothing_raised { @ship.pirate.reload } ensure - Ship.accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc(&:empty?) + Ship.accepts_nested_attributes_for :pirate, allow_destroy: true, reject_if: proc(&:empty?) end def test_should_work_with_update_as_well @@ -535,7 +535,7 @@ def test_should_work_with_update_as_well def test_should_not_destroy_the_associated_model_until_the_parent_is_saved pirate = @ship.pirate - @ship.attributes = { :pirate_attributes => { :id => pirate.id, "_destroy" => true } } + @ship.attributes = { pirate_attributes: { :id => pirate.id, "_destroy" => true } } assert_nothing_raised { Pirate.find(pirate.id) } @ship.save assert_raise(ActiveRecord::RecordNotFound) { Pirate.find(pirate.id) } @@ -547,7 +547,7 @@ def test_should_automatically_enable_autosave_on_the_association def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true @pirate.delete - @ship.reload.attributes = { :update_only_pirate_attributes => { :catchphrase => "Arr" } } + @ship.reload.attributes = { update_only_pirate_attributes: { catchphrase: "Arr" } } assert !@ship.update_only_pirate.persisted? end @@ -572,7 +572,7 @@ def test_should_update_existing_when_update_only_is_true_and_id_is_given end def test_should_destroy_existing_when_update_only_is_true_and_id_is_given_and_is_marked_for_destruction - Ship.accepts_nested_attributes_for :update_only_pirate, :update_only => true, :allow_destroy => true + Ship.accepts_nested_attributes_for :update_only_pirate, update_only: true, allow_destroy: true @pirate.delete @pirate = @ship.create_update_only_pirate(catchphrase: "Aye") @@ -580,7 +580,7 @@ def test_should_destroy_existing_when_update_only_is_true_and_id_is_given_and_is assert_raise(ActiveRecord::RecordNotFound) { @pirate.reload } - Ship.accepts_nested_attributes_for :update_only_pirate, :update_only => true, :allow_destroy => false + Ship.accepts_nested_attributes_for :update_only_pirate, update_only: true, allow_destroy: false end end @@ -599,7 +599,7 @@ def test_should_raise_an_UnknownAttributeError_for_non_existing_nested_attribute def test_should_save_only_one_association_on_create pirate = Pirate.create!({ :catchphrase => "Arr", - association_getter => { "foo" => { :name => "Grace OMalley" } } + association_getter => { "foo" => { name: "Grace OMalley" } } }) assert_equal 1, pirate.reload.send(@association_name).count @@ -618,7 +618,7 @@ def test_should_take_an_array_and_assign_the_attributes_to_the_associated_models end def test_should_also_work_with_a_HashWithIndifferentAccess - @pirate.send(association_setter, ActiveSupport::HashWithIndifferentAccess.new("foo" => ActiveSupport::HashWithIndifferentAccess.new(:id => @child_1.id, :name => "Grace OMalley"))) + @pirate.send(association_setter, ActiveSupport::HashWithIndifferentAccess.new("foo" => ActiveSupport::HashWithIndifferentAccess.new(id: @child_1.id, name: "Grace OMalley"))) @pirate.save assert_equal "Grace OMalley", @child_1.reload.name end @@ -631,7 +631,7 @@ def test_should_take_a_hash_and_assign_the_attributes_to_the_associated_models def test_should_not_load_association_when_updating_existing_records @pirate.reload - @pirate.send(association_setter, [{ :id => @child_1.id, :name => "Grace OMalley" }]) + @pirate.send(association_setter, [{ id: @child_1.id, name: "Grace OMalley" }]) assert ! @pirate.send(@association_name).loaded? @pirate.save @@ -641,13 +641,13 @@ def test_should_not_load_association_when_updating_existing_records def test_should_not_overwrite_unsaved_updates_when_loading_association @pirate.reload - @pirate.send(association_setter, [{ :id => @child_1.id, :name => "Grace OMalley" }]) + @pirate.send(association_setter, [{ id: @child_1.id, name: "Grace OMalley" }]) assert_equal "Grace OMalley", @pirate.send(@association_name).load_target.find { |r| r.id == @child_1.id }.name end def test_should_preserve_order_when_not_overwriting_unsaved_updates @pirate.reload - @pirate.send(association_setter, [{ :id => @child_1.id, :name => "Grace OMalley" }]) + @pirate.send(association_setter, [{ id: @child_1.id, name: "Grace OMalley" }]) assert_equal @child_1.id, @pirate.send(@association_name).load_target.first.id end @@ -662,7 +662,7 @@ def test_should_refresh_saved_records_when_not_overwriting_unsaved_updates def test_should_not_remove_scheduled_destroys_when_loading_association @pirate.reload - @pirate.send(association_setter, [{ :id => @child_1.id, :_destroy => "1" }]) + @pirate.send(association_setter, [{ id: @child_1.id, _destroy: "1" }]) assert @pirate.send(@association_name).load_target.find { |r| r.id == @child_1.id }.marked_for_destruction? end @@ -672,8 +672,8 @@ def test_should_take_a_hash_with_composite_id_keys_and_assign_the_attributes_to_ @pirate.attributes = { association_getter => [ - { :id => @child_1.id, :name => "Grace OMalley" }, - { :id => @child_2.id, :name => "Privateers Greed" } + { id: @child_1.id, name: "Grace OMalley" }, + { id: @child_2.id, name: "Privateers Greed" } ] } @@ -684,7 +684,7 @@ def test_should_take_a_hash_with_composite_id_keys_and_assign_the_attributes_to_ def test_should_raise_RecordNotFound_if_an_id_is_given_but_doesnt_return_a_record exception = assert_raise ActiveRecord::RecordNotFound do - @pirate.attributes = { association_getter => [{ :id => 1234567890 }] } + @pirate.attributes = { association_getter => [{ id: 1234567890 }] } end assert_equal "Couldn't find #{@child_1.class.name} with ID=1234567890 for Pirate with ID=#{@pirate.id}", exception.message end @@ -702,7 +702,7 @@ def test_should_raise_RecordNotFound_if_an_id_belonging_to_a_different_record_is def test_should_automatically_build_new_associated_models_for_each_entry_in_a_hash_where_the_id_is_missing @pirate.send(@association_name).destroy_all @pirate.reload.attributes = { - association_getter => { "foo" => { :name => "Grace OMalley" }, "bar" => { :name => "Privateers Greed" }} + association_getter => { "foo" => { name: "Grace OMalley" }, "bar" => { name: "Privateers Greed" }} } assert !@pirate.send(@association_name).first.persisted? @@ -722,7 +722,7 @@ def test_should_ignore_new_associated_records_with_truthy_destroy_attribute @pirate.send(@association_name).destroy_all @pirate.reload.attributes = { association_getter => { - "foo" => { :name => "Grace OMalley" }, + "foo" => { name: "Grace OMalley" }, "bar" => { :name => "Privateers Greed", "_destroy" => "1" } } } @@ -740,8 +740,8 @@ def test_should_ignore_new_associated_records_if_a_reject_if_proc_returns_false def test_should_sort_the_hash_by_the_keys_before_building_new_associated_models attributes = {} - attributes["123726353"] = { :name => "Grace OMalley" } - attributes["2"] = { :name => "Privateers Greed" } # 2 is lower then 123726353 + attributes["123726353"] = { name: "Grace OMalley" } + attributes["2"] = { name: "Privateers Greed" } # 2 is lower then 123726353 @pirate.send(association_setter, attributes) assert_equal ["Posideons Killer", "Killer bandita Dionne", "Privateers Greed", "Grace OMalley"].to_set, @pirate.send(@association_name).map(&:name).to_set @@ -759,7 +759,7 @@ def test_should_raise_an_argument_error_if_something_else_than_a_hash_is_passed def test_should_work_with_update_as_well @pirate.update(catchphrase: "Arr", - association_getter => { "foo" => { :id => @child_1.id, :name => "Grace OMalley" }}) + association_getter => { "foo" => { id: @child_1.id, name: "Grace OMalley" }}) assert_equal "Grace OMalley", @child_1.reload.name end @@ -774,7 +774,7 @@ def test_should_update_existing_records_and_add_new_ones_that_have_no_id def test_should_be_possible_to_destroy_a_record ["1", 1, "true", true].each do |true_variable| - record = @pirate.reload.send(@association_name).create!(:name => "Grace OMalley") + record = @pirate.reload.send(@association_name).create!(name: "Grace OMalley") @pirate.send(association_setter, @alternate_params[association_getter].merge("baz" => { :id => record.id, "_destroy" => true_variable }) ) @@ -814,8 +814,8 @@ def test_validate_presence_of_parent_works_with_inverse_of Interest.validates_presence_of(:man) assert_difference "Man.count" do assert_difference "Interest.count", 2 do - man = Man.create!(:name => "John", - :interests_attributes => [{:topic=>"Cars"}, {:topic=>"Sports"}]) + man = Man.create!(name: "John", + interests_attributes: [{topic: "Cars"}, {topic: "Sports"}]) assert_equal 2, man.interests.count end end @@ -823,7 +823,7 @@ def test_validate_presence_of_parent_works_with_inverse_of end def test_can_use_symbols_as_object_identifier - @pirate.attributes = { :parrots_attributes => { :foo => { :name => "Lovely Day" }, :bar => { :name => "Blown Away" } } } + @pirate.attributes = { parrots_attributes: { foo: { name: "Lovely Day" }, bar: { name: "Blown Away" } } } assert_nothing_raised { @pirate.save! } end @@ -855,16 +855,16 @@ def setup @association_type = :has_many @association_name = :birds - @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @pirate.birds.create!(:name => "Posideons Killer") - @pirate.birds.create!(:name => "Killer bandita Dionne") + @pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") + @pirate.birds.create!(name: "Posideons Killer") + @pirate.birds.create!(name: "Killer bandita Dionne") @child_1, @child_2 = @pirate.birds @alternate_params = { - :birds_attributes => { - "foo" => { :id => @child_1.id, :name => "Grace OMalley" }, - "bar" => { :id => @child_2.id, :name => "Privateers Greed" } + birds_attributes: { + "foo" => { id: @child_1.id, name: "Grace OMalley" }, + "bar" => { id: @child_2.id, name: "Privateers Greed" } } } end @@ -877,16 +877,16 @@ def setup @association_type = :has_and_belongs_to_many @association_name = :parrots - @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") - @pirate.parrots.create!(:name => "Posideons Killer") - @pirate.parrots.create!(:name => "Killer bandita Dionne") + @pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") + @pirate.parrots.create!(name: "Posideons Killer") + @pirate.parrots.create!(name: "Killer bandita Dionne") @child_1, @child_2 = @pirate.parrots @alternate_params = { - :parrots_attributes => { - "foo" => { :id => @child_1.id, :name => "Grace OMalley" }, - "bar" => { :id => @child_2.id, :name => "Privateers Greed" } + parrots_attributes: { + "foo" => { id: @child_1.id, name: "Grace OMalley" }, + "bar" => { id: @child_2.id, name: "Privateers Greed" } } } end @@ -896,33 +896,33 @@ def setup module NestedAttributesLimitTests def teardown - Pirate.accepts_nested_attributes_for :parrots, :allow_destroy => true, :reject_if => proc(&:empty?) + Pirate.accepts_nested_attributes_for :parrots, allow_destroy: true, reject_if: proc(&:empty?) end def test_limit_with_less_records - @pirate.attributes = { :parrots_attributes => { "foo" => { :name => "Big Big Love" } } } + @pirate.attributes = { parrots_attributes: { "foo" => { name: "Big Big Love" } } } assert_difference("Parrot.count") { @pirate.save! } end def test_limit_with_number_exact_records - @pirate.attributes = { :parrots_attributes => { "foo" => { :name => "Lovely Day" }, "bar" => { :name => "Blown Away" } } } + @pirate.attributes = { parrots_attributes: { "foo" => { name: "Lovely Day" }, "bar" => { name: "Blown Away" } } } assert_difference("Parrot.count", 2) { @pirate.save! } end def test_limit_with_exceeding_records assert_raises(ActiveRecord::NestedAttributes::TooManyRecords) do - @pirate.attributes = { :parrots_attributes => { "foo" => { :name => "Lovely Day" }, - "bar" => { :name => "Blown Away" }, - "car" => { :name => "The Happening" }} } + @pirate.attributes = { parrots_attributes: { "foo" => { name: "Lovely Day" }, + "bar" => { name: "Blown Away" }, + "car" => { name: "The Happening" }} } end end end class TestNestedAttributesLimitNumeric < ActiveRecord::TestCase def setup - Pirate.accepts_nested_attributes_for :parrots, :limit => 2 + Pirate.accepts_nested_attributes_for :parrots, limit: 2 - @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") + @pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") end include NestedAttributesLimitTests @@ -930,9 +930,9 @@ def setup class TestNestedAttributesLimitSymbol < ActiveRecord::TestCase def setup - Pirate.accepts_nested_attributes_for :parrots, :limit => :parrots_limit + Pirate.accepts_nested_attributes_for :parrots, limit: :parrots_limit - @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?", :parrots_limit => 2) + @pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?", parrots_limit: 2) end include NestedAttributesLimitTests @@ -940,9 +940,9 @@ def setup class TestNestedAttributesLimitProc < ActiveRecord::TestCase def setup - Pirate.accepts_nested_attributes_for :parrots, :limit => proc { 2 } + Pirate.accepts_nested_attributes_for :parrots, limit: proc { 2 } - @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") + @pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") end include NestedAttributesLimitTests @@ -952,15 +952,15 @@ class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase fixtures :owners, :pets def setup - Owner.accepts_nested_attributes_for :pets, :allow_destroy => true + Owner.accepts_nested_attributes_for :pets, allow_destroy: true @owner = owners(:ashley) @pet1, @pet2 = pets(:chew), pets(:mochi) @params = { - :pets_attributes => { - "0" => { :id => @pet1.id, :name => "Foo" }, - "1" => { :id => @pet2.id, :name => "Bar" } + pets_attributes: { + "0" => { id: @pet1.id, name: "Foo" }, + "1" => { id: @pet2.id, name: "Bar" } } } end @@ -973,10 +973,10 @@ def test_should_update_existing_records_with_non_standard_primary_key def test_attr_accessor_of_child_should_be_value_provided_during_update @owner = owners(:ashley) @pet1 = pets(:chew) - attributes = {:pets_attributes => { "1"=> { :id => @pet1.id, - :name => "Foo2", - :current_user => "John", - :_destroy=>true }}} + attributes = {pets_attributes: { "1"=> { id: @pet1.id, + name: "Foo2", + current_user: "John", + _destroy: true }}} @owner.update(attributes) assert_equal "John", Pet.after_destroy_output end @@ -987,10 +987,10 @@ class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRe self.use_transactional_tests = false unless supports_savepoints? def setup - @pirate = Pirate.create!(:catchphrase => "My baby takes tha mornin' train!") - @ship = @pirate.create_ship(:name => "The good ship Dollypop") - @part = @ship.parts.create!(:name => "Mast") - @trinket = @part.trinkets.create!(:name => "Necklace") + @pirate = Pirate.create!(catchphrase: "My baby takes tha mornin' train!") + @ship = @pirate.create_ship(name: "The good ship Dollypop") + @part = @ship.parts.create!(name: "Mast") + @trinket = @part.trinkets.create!(name: "Necklace") end test "when great-grandchild changed in memory, saving parent should save great-grandchild" do @@ -1000,25 +1000,25 @@ def setup end test "when great-grandchild changed via attributes, saving parent should save great-grandchild" do - @pirate.attributes = {:ship_attributes => {:id => @ship.id, :parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:id => @trinket.id, :name => "changed"}]}]}} + @pirate.attributes = {ship_attributes: {id: @ship.id, parts_attributes: [{id: @part.id, trinkets_attributes: [{id: @trinket.id, name: "changed"}]}]}} @pirate.save assert_equal "changed", @trinket.reload.name end test "when great-grandchild marked_for_destruction via attributes, saving parent should destroy great-grandchild" do - @pirate.attributes = {:ship_attributes => {:id => @ship.id, :parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:id => @trinket.id, :_destroy => true}]}]}} + @pirate.attributes = {ship_attributes: {id: @ship.id, parts_attributes: [{id: @part.id, trinkets_attributes: [{id: @trinket.id, _destroy: true}]}]}} assert_difference("@part.trinkets.count", -1) { @pirate.save } end test "when great-grandchild added via attributes, saving parent should create great-grandchild" do - @pirate.attributes = {:ship_attributes => {:id => @ship.id, :parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:name => "created"}]}]}} + @pirate.attributes = {ship_attributes: {id: @ship.id, parts_attributes: [{id: @part.id, trinkets_attributes: [{name: "created"}]}]}} assert_difference("@part.trinkets.count", 1) { @pirate.save } end test "when extra records exist for associations, validate (which calls nested_records_changed_for_autosave?) should not load them up" do @trinket.name = "changed" - Ship.create!(:pirate => @pirate, :name => "The Black Rock") - ShipPart.create!(:ship => @ship, :name => "Stern") + Ship.create!(pirate: @pirate, name: "The Black Rock") + ShipPart.create!(ship: @ship, name: "Stern") assert_no_queries { @pirate.valid? } end end @@ -1027,19 +1027,19 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR self.use_transactional_tests = false unless supports_savepoints? def setup - @ship = Ship.create!(:name => "The good ship Dollypop") - @part = @ship.parts.create!(:name => "Mast") - @trinket = @part.trinkets.create!(:name => "Necklace") + @ship = Ship.create!(name: "The good ship Dollypop") + @part = @ship.parts.create!(name: "Mast") + @trinket = @part.trinkets.create!(name: "Necklace") end test "if association is not loaded and association record is saved and then in memory record attributes should be saved" do - @ship.parts_attributes=[{:id => @part.id,:name =>"Deck"}] + @ship.parts_attributes=[{id: @part.id,name: "Deck"}] assert_equal 1, @ship.association(:parts).target.size assert_equal "Deck", @ship.parts[0].name end test "if association is not loaded and child doesn't change and I am saving a grandchild then in memory record should be used" do - @ship.parts_attributes=[{:id => @part.id,:trinkets_attributes =>[{:id => @trinket.id, :name => "Ruby"}]}] + @ship.parts_attributes=[{id: @part.id,trinkets_attributes: [{id: @trinket.id, name: "Ruby"}]}] assert_equal 1, @ship.association(:parts).target.size assert_equal "Mast", @ship.parts[0].name assert_no_difference("@ship.parts[0].association(:trinkets).target.size") do @@ -1057,25 +1057,25 @@ def setup end test "when grandchild changed via attributes, saving parent should save grandchild" do - @ship.attributes = {:parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:id => @trinket.id, :name => "changed"}]}]} + @ship.attributes = {parts_attributes: [{id: @part.id, trinkets_attributes: [{id: @trinket.id, name: "changed"}]}]} @ship.save assert_equal "changed", @trinket.reload.name end test "when grandchild marked_for_destruction via attributes, saving parent should destroy grandchild" do - @ship.attributes = {:parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:id => @trinket.id, :_destroy => true}]}]} + @ship.attributes = {parts_attributes: [{id: @part.id, trinkets_attributes: [{id: @trinket.id, _destroy: true}]}]} assert_difference("@part.trinkets.count", -1) { @ship.save } end test "when grandchild added via attributes, saving parent should create grandchild" do - @ship.attributes = {:parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:name => "created"}]}]} + @ship.attributes = {parts_attributes: [{id: @part.id, trinkets_attributes: [{name: "created"}]}]} assert_difference("@part.trinkets.count", 1) { @ship.save } end test "when extra records exist for associations, validate (which calls nested_records_changed_for_autosave?) should not load them up" do @trinket.name = "changed" - Ship.create!(:name => "The Black Rock") - ShipPart.create!(:ship => @ship, :name => "Stern") + Ship.create!(name: "The Black Rock") + ShipPart.create!(ship: @ship, name: "Stern") assert_no_queries { @ship.valid? } end diff --git a/activerecord/test/cases/nested_attributes_with_callbacks_test.rb b/activerecord/test/cases/nested_attributes_with_callbacks_test.rb index 3f87e514b5..d41b7c2213 100644 --- a/activerecord/test/cases/nested_attributes_with_callbacks_test.rb +++ b/activerecord/test/cases/nested_attributes_with_callbacks_test.rb @@ -4,24 +4,24 @@ class NestedAttributesWithCallbacksTest < ActiveRecord::TestCase Pirate.has_many(:birds_with_add_load, - :class_name => "Bird", - :before_add => proc { |p,b| + class_name: "Bird", + before_add: proc { |p,b| @@add_callback_called << b p.birds_with_add_load.to_a }) Pirate.has_many(:birds_with_add, - :class_name => "Bird", - :before_add => proc { |p,b| @@add_callback_called << b }) + class_name: "Bird", + before_add: proc { |p,b| @@add_callback_called << b }) Pirate.accepts_nested_attributes_for(:birds_with_add_load, :birds_with_add, - :allow_destroy => true) + allow_destroy: true) def setup @@add_callback_called = [] @pirate = Pirate.new.tap do |pirate| pirate.catchphrase = "Don't call me!" - pirate.birds_attributes = [{:name => "Bird1"},{:name => "Bird2"}] + pirate.birds_attributes = [{name: "Bird1"},{name: "Bird2"}] pirate.save! end @birds = @pirate.birds.to_a diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index ec8fe53158..1dbf4fcdd6 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -83,7 +83,7 @@ def test_delete_all end def test_delete_all_with_joins_and_where_part_is_hash - where_args = {:toys => {:name => "Bone"}} + where_args = {toys: {name: "Bone"}} count = Pet.joins(:toys).where(where_args).count assert_equal count, 1 @@ -133,7 +133,7 @@ def test_increment_updates_counter_in_db_using_offset def test_destroy_all conditions = "author_name = 'Mary'" - topics_by_mary = Topic.all.merge!(:where => conditions, :order => "id").to_a + topics_by_mary = Topic.all.merge!(where: conditions, order: "id").to_a assert ! topics_by_mary.empty? assert_difference("Topic.count", -topics_by_mary.size) do @@ -144,7 +144,7 @@ def test_destroy_all end def test_destroy_many - clients = Client.all.merge!(:order => "id").find([2, 3]) + clients = Client.all.merge!(order: "id").find([2, 3]) assert_difference("Client.count", -2) do destroyed = Client.destroy([2, 3]).sort_by(&:id) @@ -159,7 +159,7 @@ def test_becomes end def test_becomes_includes_errors - company = Company.new(:name => nil) + company = Company.new(name: nil) assert !company.valid? original_errors = company.errors client = company.becomes(Client) @@ -231,7 +231,7 @@ def test_create end def test_save! - topic = Topic.new(:title => "New Topic") + topic = Topic.new(title: "New Topic") assert topic.save! reply = WrongReply.new @@ -261,7 +261,7 @@ def test_save_for_record_with_only_primary_key end def test_save_for_record_with_only_primary_key_that_is_provided - assert_nothing_raised { Minimalistic.create!(:id => 2) } + assert_nothing_raised { Minimalistic.create!(id: 2) } end def test_save_with_duping_of_destroyed_object @@ -446,7 +446,7 @@ def test_update_all def test_update_all_with_hash assert_not_nil Topic.find(1).last_read - assert_equal Topic.count, Topic.update_all(:content => "bulk updated with hash!", :last_read => nil) + assert_equal Topic.count, Topic.update_all(content: "bulk updated with hash!", last_read: nil) assert_equal "bulk updated with hash!", Topic.find(1).content assert_equal "bulk updated with hash!", Topic.find(2).content assert_nil Topic.find(1).last_read @@ -840,7 +840,7 @@ def test_destroyed_returns_boolean end def test_persisted_returns_boolean - developer = Developer.new(:name => "Jose") + developer = Developer.new(name: "Jose") assert_equal false, developer.persisted? developer.save! assert_equal true, developer.persisted? @@ -931,7 +931,7 @@ def test_reload_via_querycache ActiveRecord::Base.connection.enable_query_cache! ActiveRecord::Base.connection.clear_query_cache assert ActiveRecord::Base.connection.query_cache_enabled, "cache should be on" - parrot = Parrot.create(:name => "Shane") + parrot = Parrot.create(name: "Shane") # populate the cache with the SELECT result found_parrot = Parrot.find(parrot.id) diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index bca50dd008..71fc0881c1 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -18,7 +18,7 @@ def setup # Will deadlock due to lack of Monitor timeouts in 1.9 def checkout_checkin_connections(pool_size, threads) - ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :checkout_timeout => 0.5})) + ActiveRecord::Base.establish_connection(@connection.merge({pool: pool_size, checkout_timeout: 0.5})) @connection_count = 0 @timed_out = 0 threads.times do @@ -36,7 +36,7 @@ def checkout_checkin_connections(pool_size, threads) end def checkout_checkin_connections_loop(pool_size, loops) - ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :checkout_timeout => 0.5})) + ActiveRecord::Base.establish_connection(@connection.merge({pool: pool_size, checkout_timeout: 0.5})) @connection_count = 0 @timed_out = 0 loops.times do @@ -66,7 +66,7 @@ def test_pooled_connection_checkin_two end def test_pooled_connection_remove - ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :checkout_timeout => 0.5})) + ActiveRecord::Base.establish_connection(@connection.merge({pool: 2, checkout_timeout: 0.5})) old_connection = ActiveRecord::Base.connection extra_connection = ActiveRecord::Base.connection_pool.checkout ActiveRecord::Base.connection_pool.remove(extra_connection) @@ -76,6 +76,6 @@ def test_pooled_connection_remove private def add_record(name) - ActiveRecord::Base.connection_pool.with_connection { Project.create! :name => name } + ActiveRecord::Base.connection_pool.with_connection { Project.create! name: name } end end unless in_memory_db? diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb index 5bfacd7ce3..31d612abd1 100644 --- a/activerecord/test/cases/primary_keys_test.rb +++ b/activerecord/test/cases/primary_keys_test.rb @@ -54,7 +54,7 @@ def test_integer_key def test_customized_primary_key_auto_assigns_on_save Keyboard.delete_all - keyboard = Keyboard.new(:name => "HHKB") + keyboard = Keyboard.new(name: "HHKB") assert_nothing_raised { keyboard.save! } assert_equal keyboard.id, Keyboard.find_by_name("HHKB").id end @@ -114,7 +114,7 @@ def test_delete_should_quote_pkey assert_nothing_raised { MixedCaseMonkey.delete(1) } end def test_update_counters_should_quote_pkey_and_quote_counter_columns - assert_nothing_raised { MixedCaseMonkey.update_counters(1, :fleaCount => 99) } + assert_nothing_raised { MixedCaseMonkey.update_counters(1, fleaCount: 99) } end def test_find_with_one_id_should_quote_pkey assert_nothing_raised { MixedCaseMonkey.find(1) } diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 3e58de4258..d71b30af69 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -100,7 +100,7 @@ def test_non_existent_types_are_identity_types end def test_reflection_klass_for_nested_class_name - reflection = ActiveRecord::Reflection.create(:has_many, nil, nil, { :class_name => "MyApplication::Business::Company" }, ActiveRecord::Base) + reflection = ActiveRecord::Reflection.create(:has_many, nil, nil, { class_name: "MyApplication::Business::Company" }, ActiveRecord::Base) assert_nothing_raised do assert_equal MyApplication::Business::Company, reflection.klass end @@ -116,11 +116,11 @@ def test_irregular_reflection_class_name def test_aggregation_reflection reflection_for_address = AggregateReflection.new( - :address, nil, { :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer + :address, nil, { mapping: [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer ) reflection_for_balance = AggregateReflection.new( - :balance, nil, { :class_name => "Money", :mapping => %w(balance amount) }, Customer + :balance, nil, { class_name: "Money", mapping: %w(balance amount) }, Customer ) reflection_for_gps_location = AggregateReflection.new( @@ -148,7 +148,7 @@ def test_reflect_on_all_autosave_associations end def test_has_many_reflection - reflection_for_clients = ActiveRecord::Reflection.create(:has_many, :clients, nil, { :order => "id", :dependent => :destroy }, Firm) + reflection_for_clients = ActiveRecord::Reflection.create(:has_many, :clients, nil, { order: "id", dependent: :destroy }, Firm) assert_equal reflection_for_clients, Firm.reflect_on_association(:clients) @@ -160,7 +160,7 @@ def test_has_many_reflection end def test_has_one_reflection - reflection_for_account = ActiveRecord::Reflection.create(:has_one, :account, nil, { :foreign_key => "firm_id", :dependent => :destroy }, Firm) + reflection_for_account = ActiveRecord::Reflection.create(:has_one, :account, nil, { foreign_key: "firm_id", dependent: :destroy }, Firm) assert_equal reflection_for_account, Firm.reflect_on_association(:account) assert_equal Account, Firm.reflect_on_association(:account).klass @@ -170,9 +170,9 @@ def test_has_one_reflection def test_belongs_to_inferred_foreign_key_from_assoc_name Company.belongs_to :foo assert_equal "foo_id", Company.reflect_on_association(:foo).foreign_key - Company.belongs_to :bar, :class_name => "Xyzzy" + Company.belongs_to :bar, class_name: "Xyzzy" assert_equal "bar_id", Company.reflect_on_association(:bar).foreign_key - Company.belongs_to :baz, :class_name => "Xyzzy", :foreign_key => "xyzzy_id" + Company.belongs_to :baz, class_name: "Xyzzy", foreign_key: "xyzzy_id" assert_equal "xyzzy_id", Company.reflect_on_association(:baz).foreign_key end @@ -181,39 +181,39 @@ def test_association_reflection_in_modules assert_reflection MyApplication::Business::Firm, :clients_of_firm, - :klass => MyApplication::Business::Client, - :class_name => "Client", - :table_name => "companies" + klass: MyApplication::Business::Client, + class_name: "Client", + table_name: "companies" assert_reflection MyApplication::Billing::Account, :firm, - :klass => MyApplication::Business::Firm, - :class_name => "MyApplication::Business::Firm", - :table_name => "companies" + klass: MyApplication::Business::Firm, + class_name: "MyApplication::Business::Firm", + table_name: "companies" assert_reflection MyApplication::Billing::Account, :qualified_billing_firm, - :klass => MyApplication::Billing::Firm, - :class_name => "MyApplication::Billing::Firm", - :table_name => "companies" + klass: MyApplication::Billing::Firm, + class_name: "MyApplication::Billing::Firm", + table_name: "companies" assert_reflection MyApplication::Billing::Account, :unqualified_billing_firm, - :klass => MyApplication::Billing::Firm, - :class_name => "Firm", - :table_name => "companies" + klass: MyApplication::Billing::Firm, + class_name: "Firm", + table_name: "companies" assert_reflection MyApplication::Billing::Account, :nested_qualified_billing_firm, - :klass => MyApplication::Billing::Nested::Firm, - :class_name => "MyApplication::Billing::Nested::Firm", - :table_name => "companies" + klass: MyApplication::Billing::Nested::Firm, + class_name: "MyApplication::Billing::Nested::Firm", + table_name: "companies" assert_reflection MyApplication::Billing::Account, :nested_unqualified_billing_firm, - :klass => MyApplication::Billing::Nested::Firm, - :class_name => "Nested::Firm", - :table_name => "companies" + klass: MyApplication::Billing::Nested::Firm, + class_name: "Nested::Firm", + table_name: "companies" ensure ActiveRecord::Base.store_full_sti_class = true end @@ -366,21 +366,21 @@ def test_default_association_validation end def test_always_validate_association_if_explicit - assert ActiveRecord::Reflection.create(:has_one, :client, nil, { :validate => true }, Firm).validate? - assert ActiveRecord::Reflection.create(:belongs_to, :client, nil, { :validate => true }, Firm).validate? - assert ActiveRecord::Reflection.create(:has_many, :clients, nil, { :validate => true }, Firm).validate? + assert ActiveRecord::Reflection.create(:has_one, :client, nil, { validate: true }, Firm).validate? + assert ActiveRecord::Reflection.create(:belongs_to, :client, nil, { validate: true }, Firm).validate? + assert ActiveRecord::Reflection.create(:has_many, :clients, nil, { validate: true }, Firm).validate? end def test_validate_association_if_autosave - assert ActiveRecord::Reflection.create(:has_one, :client, nil, { :autosave => true }, Firm).validate? - assert ActiveRecord::Reflection.create(:belongs_to, :client, nil, { :autosave => true }, Firm).validate? - assert ActiveRecord::Reflection.create(:has_many, :clients, nil, { :autosave => true }, Firm).validate? + assert ActiveRecord::Reflection.create(:has_one, :client, nil, { autosave: true }, Firm).validate? + assert ActiveRecord::Reflection.create(:belongs_to, :client, nil, { autosave: true }, Firm).validate? + assert ActiveRecord::Reflection.create(:has_many, :clients, nil, { autosave: true }, Firm).validate? end def test_never_validate_association_if_explicit - assert !ActiveRecord::Reflection.create(:has_one, :client, nil, { :autosave => true, :validate => false }, Firm).validate? - assert !ActiveRecord::Reflection.create(:belongs_to, :client, nil, { :autosave => true, :validate => false }, Firm).validate? - assert !ActiveRecord::Reflection.create(:has_many, :clients, nil, { :autosave => true, :validate => false }, Firm).validate? + assert !ActiveRecord::Reflection.create(:has_one, :client, nil, { autosave: true, validate: false }, Firm).validate? + assert !ActiveRecord::Reflection.create(:belongs_to, :client, nil, { autosave: true, validate: false }, Firm).validate? + assert !ActiveRecord::Reflection.create(:has_many, :clients, nil, { autosave: true, validate: false }, Firm).validate? end def test_foreign_key @@ -447,12 +447,12 @@ def test_join_table_can_be_overridden category = Struct.new(:table_name, :pluralize_table_names).new("categories", true) product = Struct.new(:table_name, :pluralize_table_names).new("products", true) - reflection = ActiveRecord::Reflection.create(:has_many, :categories, nil, { :join_table => "product_categories" }, product) + reflection = ActiveRecord::Reflection.create(:has_many, :categories, nil, { join_table: "product_categories" }, product) reflection.stub(:klass, category) do assert_equal "product_categories", reflection.join_table end - reflection = ActiveRecord::Reflection.create(:has_many, :products, nil, { :join_table => "product_categories" }, category) + reflection = ActiveRecord::Reflection.create(:has_many, :products, nil, { join_table: "product_categories" }, category) reflection.stub(:klass, product) do assert_equal "product_categories", reflection.join_table end diff --git a/activerecord/test/cases/relation/merging_test.rb b/activerecord/test/cases/relation/merging_test.rb index b55084eee6..bc3b1de697 100644 --- a/activerecord/test/cases/relation/merging_test.rb +++ b/activerecord/test/cases/relation/merging_test.rb @@ -66,14 +66,14 @@ def test_relation_merging_with_preload end def test_relation_merging_with_joins - comments = Comment.joins(:post).where(:body => "Thank you for the welcome").merge(Post.where(:body => "Such a lovely day")) + comments = Comment.joins(:post).where(body: "Thank you for the welcome").merge(Post.where(body: "Such a lovely day")) assert_equal 1, comments.count end def test_relation_merging_with_association assert_queries(2) do # one for loading post, and another one merged query - post = Post.where(:body => "Such a lovely day").first - comments = Comment.where(:body => "Thank you for the welcome").merge(post.comments) + post = Post.where(body: "Such a lovely day").first + comments = Comment.where(body: "Thank you for the welcome").merge(post.comments) assert_equal 1, comments.count end end diff --git a/activerecord/test/cases/relation/or_test.rb b/activerecord/test/cases/relation/or_test.rb index e746f1d55c..4efc742d5a 100644 --- a/activerecord/test/cases/relation/or_test.rb +++ b/activerecord/test/cases/relation/or_test.rb @@ -47,13 +47,13 @@ def test_or_without_right_where def test_or_preserves_other_querying_methods expected = Post.where("id = 1 or id = 2 or id = 3").order("body asc").to_a partial = Post.order("body asc") - assert_equal expected, partial.where("id = 1").or(partial.where(:id => [2, 3])).to_a - assert_equal expected, Post.order("body asc").where("id = 1").or(Post.order("body asc").where(:id => [2, 3])).to_a + assert_equal expected, partial.where("id = 1").or(partial.where(id: [2, 3])).to_a + assert_equal expected, Post.order("body asc").where("id = 1").or(Post.order("body asc").where(id: [2, 3])).to_a end def test_or_with_incompatible_relations error = assert_raises ArgumentError do - Post.order("body asc").where("id = 1").or(Post.order("id desc").where(:id => [2, 3])).to_a + Post.order("body asc").where("id = 1").or(Post.order("id desc").where(id: [2, 3])).to_a end assert_equal "Relation passed to #or must be structurally compatible. Incompatible values: [:order]", error.message diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb index c7d6018872..ad9008ea4d 100644 --- a/activerecord/test/cases/relation/where_test.rb +++ b/activerecord/test/cases/relation/where_test.rb @@ -197,25 +197,25 @@ def test_aliased_attribute def test_where_error assert_raises(ActiveRecord::StatementInvalid) do - Post.where(:id => { "posts.author_id" => 10 }).first + Post.where(id: { "posts.author_id" => 10 }).first end end def test_where_with_table_name post = Post.first - assert_equal post, Post.where(:posts => { "id" => post.id }).first + assert_equal post, Post.where(posts: { "id" => post.id }).first end def test_where_with_table_name_and_empty_hash - assert_equal 0, Post.where(:posts => {}).count + assert_equal 0, Post.where(posts: {}).count end def test_where_with_table_name_and_empty_array - assert_equal 0, Post.where(:id => []).count + assert_equal 0, Post.where(id: []).count end def test_where_with_empty_hash_and_no_foreign_key - assert_equal 0, Edge.where(:sink => {}).count + assert_equal 0, Edge.where(sink: {}).count end def test_where_with_blank_conditions @@ -225,32 +225,32 @@ def test_where_with_blank_conditions end def test_where_with_integer_for_string_column - count = Post.where(:title => 0).count + count = Post.where(title: 0).count assert_equal 0, count end def test_where_with_float_for_string_column - count = Post.where(:title => 0.0).count + count = Post.where(title: 0.0).count assert_equal 0, count end def test_where_with_boolean_for_string_column - count = Post.where(:title => false).count + count = Post.where(title: false).count assert_equal 0, count end def test_where_with_decimal_for_string_column - count = Post.where(:title => BigDecimal.new(0)).count + count = Post.where(title: BigDecimal.new(0)).count assert_equal 0, count end def test_where_with_duration_for_string_column - count = Post.where(:title => 0.seconds).count + count = Post.where(title: 0.seconds).count assert_equal 0, count end def test_where_with_integer_for_binary_column - count = Binary.where(:data => 0).count + count = Binary.where(data: 0).count assert_equal 0, count end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index 4776261bd2..99f739c6c9 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -70,7 +70,7 @@ def test_empty_where_values_hash def test_has_values relation = Relation.new(Post, Post.arel_table, Post.predicate_builder) relation.where! relation.table[:id].eq(10) - assert_equal({:id => 10}, relation.where_values_hash) + assert_equal({id: 10}, relation.where_values_hash) end def test_values_wrong_table @@ -100,7 +100,7 @@ def test_scope_for_create def test_create_with_value relation = Relation.new(Post, Post.arel_table, Post.predicate_builder) - hash = { :hello => "world" } + hash = { hello: "world" } relation.create_with_value = hash assert_equal hash, relation.scope_for_create end @@ -108,8 +108,8 @@ def test_create_with_value def test_create_with_value_with_wheres relation = Relation.new(Post, Post.arel_table, Post.predicate_builder) relation.where! relation.table[:id].eq(10) - relation.create_with_value = {:hello => "world"} - assert_equal({:hello => "world", :id => 10}, relation.scope_for_create) + relation.create_with_value = {hello: "world"} + assert_equal({hello: "world", id: 10}, relation.scope_for_create) end # FIXME: is this really wanted or expected behavior? @@ -120,7 +120,7 @@ def test_scope_for_create_is_cached relation.where! relation.table[:id].eq(10) assert_equal({}, relation.scope_for_create) - relation.create_with_value = {:hello => "world"} + relation.create_with_value = {hello: "world"} assert_equal({}, relation.scope_for_create) end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 9ace34835c..d5aee29102 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -33,13 +33,13 @@ class TopicWithCallbacks < ActiveRecord::Base def test_do_not_double_quote_string_id van = Minivan.last assert van - assert_equal van.id, Minivan.where(:minivan_id => van).to_a.first.minivan_id + assert_equal van.id, Minivan.where(minivan_id: van).to_a.first.minivan_id end def test_do_not_double_quote_string_id_with_array van = Minivan.last assert van - assert_equal van, Minivan.where(:minivan_id => [van]).to_a.first + assert_equal van, Minivan.where(minivan_id: [van]).to_a.first end def test_two_scopes_with_includes_should_not_drop_any_include @@ -154,7 +154,7 @@ def test_reload assert topics.loaded? original_size = topics.to_a.size - Topic.create! :title => "fake" + Topic.create! title: "fake" assert_queries(1) { topics.reload } assert_equal original_size + 1, topics.size @@ -162,7 +162,7 @@ def test_reload end def test_finding_with_subquery - relation = Topic.where(:approved => true) + relation = Topic.where(approved: true) assert_equal relation.to_a, Topic.select("*").from(relation).to_a assert_equal relation.to_a, Topic.select("subquery.*").from(relation).to_a assert_equal relation.to_a, Topic.select("a.*").from(relation, :a).to_a @@ -195,7 +195,7 @@ def test_group_with_subquery_in_from_does_not_use_original_table_name end def test_finding_with_conditions - assert_equal ["David"], Author.where(:name => "David").map(&:name) + assert_equal ["David"], Author.where(name: "David").map(&:name) assert_equal ["Mary"], Author.where(["name = ?", "Mary"]).map(&:name) assert_equal ["Mary"], Author.where("name = ?", "Mary").map(&:name) end @@ -213,13 +213,13 @@ def test_finding_with_arel_order end def test_finding_with_assoc_order - topics = Topic.order(:id => :desc) + topics = Topic.order(id: :desc) assert_equal 5, topics.to_a.size assert_equal topics(:fifth).title, topics.first.title end def test_finding_with_reverted_assoc_order - topics = Topic.order(:id => :asc).reverse_order + topics = Topic.order(id: :asc).reverse_order assert_equal 5, topics.to_a.size assert_equal topics(:fifth).title, topics.first.title end @@ -258,7 +258,7 @@ def test_default_reverse_order_on_table_without_primary_key end def test_order_with_hash_and_symbol_generates_the_same_sql - assert_equal Topic.order(:id).to_sql, Topic.order(:id => :asc).to_sql + assert_equal Topic.order(:id).to_sql, Topic.order(id: :asc).to_sql end def test_finding_with_desc_order_with_string @@ -397,7 +397,7 @@ def test_none def test_none_chainable assert_no_queries(ignore_none: false) do - assert_equal [], Developer.none.where(:name => "David") + assert_equal [], Developer.none.where(name: "David") end end @@ -411,7 +411,7 @@ def test_none_chained_to_methods_firing_queries_straight_to_db assert_no_queries(ignore_none: false) do assert_equal [], Developer.none.pluck(:id, :name) assert_equal 0, Developer.none.delete_all - assert_equal 0, Developer.none.update_all(:name => "David") + assert_equal 0, Developer.none.update_all(name: "David") assert_equal 0, Developer.none.delete(1) assert_equal false, Developer.none.exists?(1) end @@ -510,7 +510,7 @@ def test_joins_with_nil_argument end def test_finding_with_hash_conditions_on_joined_table - firms = DependentFirm.joins(:account).where({:name => "RailsCore", :accounts => { :credit_limit => 55..60 }}).to_a + firms = DependentFirm.joins(:account).where({name: "RailsCore", accounts: { credit_limit: 55..60 }}).to_a assert_equal 1, firms.size assert_equal companies(:rails_core), firms.first end @@ -526,7 +526,7 @@ def test_find_all_with_join end def test_find_on_hash_conditions - assert_equal Topic.all.merge!(:where => {:approved => false}).to_a, Topic.where({ :approved => false }).to_a + assert_equal Topic.all.merge!(where: {approved: false}).to_a, Topic.where({ approved: false }).to_a end def test_joins_with_string_array @@ -599,7 +599,7 @@ def test_find_with_readonly_option end def test_eager_association_loading_of_stis_with_multiple_references - authors = Author.eager_load(:posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } }). + authors = Author.eager_load(posts: { special_comments: { post: [ :special_comments, :very_special_comment ] } }). order("comments.body, very_special_comments_posts.body").where("posts.id = 4").to_a assert_equal [authors(:david)], authors @@ -798,7 +798,7 @@ def test_find_id david = authors.find(authors(:david).id) assert_equal "David", david.name - assert_raises(ActiveRecord::RecordNotFound) { authors.where(:name => "lifo").find("42") } + assert_raises(ActiveRecord::RecordNotFound) { authors.where(name: "lifo").find("42") } end def test_find_ids @@ -811,18 +811,18 @@ def test_find_ids assert_equal "Mary", results[1].name assert_equal results, authors.find([authors(:david).id, authors(:mary).id]) - assert_raises(ActiveRecord::RecordNotFound) { authors.where(:name => "lifo").find(authors(:david).id, "42") } + assert_raises(ActiveRecord::RecordNotFound) { authors.where(name: "lifo").find(authors(:david).id, "42") } assert_raises(ActiveRecord::RecordNotFound) { authors.find(["42", 43]) } end def test_find_in_empty_array - authors = Author.all.where(:id => []) + authors = Author.all.where(id: []) assert authors.to_a.blank? end def test_where_with_ar_object author = Author.first - authors = Author.all.where(:id => author) + authors = Author.all.where(id: author) assert_equal 1, authors.to_a.length end @@ -835,9 +835,9 @@ def test_find_with_list_of_ar class Mary < Author; end def test_find_by_classname - Author.create!(:name => Mary.name) + Author.create!(name: Mary.name) assert_deprecated do - assert_equal 1, Author.where(:name => Mary).size + assert_equal 1, Author.where(name: Mary).size end end @@ -850,25 +850,25 @@ def test_find_by_id_with_list_of_ar def test_find_all_using_where_twice_should_or_the_relation david = authors(:david) relation = Author.unscoped - relation = relation.where(:name => david.name) - relation = relation.where(:name => "Santiago") - relation = relation.where(:id => david.id) + relation = relation.where(name: david.name) + relation = relation.where(name: "Santiago") + relation = relation.where(id: david.id) assert_equal [], relation.to_a end def test_multi_where_ands_queries relation = Author.unscoped david = authors(:david) - sql = relation.where(:name => david.name).where(:name => "Santiago").to_sql + sql = relation.where(name: david.name).where(name: "Santiago").to_sql assert_match("AND", sql) end def test_find_all_with_multiple_should_use_and david = authors(:david) relation = [ - { :name => david.name }, - { :name => "Santiago" }, - { :name => "tenderlove" }, + { name: david.name }, + { name: "Santiago" }, + { name: "tenderlove" }, ].inject(Author.unscoped) do |memo, param| memo.where(param) end @@ -887,7 +887,7 @@ def test_find_all_using_where_with_relation # switching the lines below would succeed in current rails # assert_queries(2) { assert_queries(1) { - relation = Author.where(:id => Author.where(:id => david.id)) + relation = Author.where(id: Author.where(id: david.id)) assert_equal [david], relation.to_a } @@ -927,7 +927,7 @@ def test_find_all_using_where_with_relation_and_alternate_primary_key # switching the lines below would succeed in current rails # assert_queries(2) { assert_queries(1) { - relation = Minivan.where(:minivan_id => Minivan.where(:name => cool_first.name)) + relation = Minivan.where(minivan_id: Minivan.where(name: cool_first.name)) assert_equal [cool_first], relation.to_a } end @@ -935,10 +935,10 @@ def test_find_all_using_where_with_relation_and_alternate_primary_key def test_find_all_using_where_with_relation_does_not_alter_select_values david = authors(:david) - subquery = Author.where(:id => david.id) + subquery = Author.where(id: david.id) assert_queries(1) { - relation = Author.where(:id => subquery) + relation = Author.where(id: subquery) assert_equal [david], relation.to_a } @@ -948,7 +948,7 @@ def test_find_all_using_where_with_relation_does_not_alter_select_values def test_find_all_using_where_with_relation_with_joins david = authors(:david) assert_queries(1) { - relation = Author.where(:id => Author.joins(:posts).where(:id => david.id)) + relation = Author.where(id: Author.joins(:posts).where(id: david.id)) assert_equal [david], relation.to_a } end @@ -957,13 +957,13 @@ def test_find_all_using_where_with_relation_with_joins def test_find_all_using_where_with_relation_with_select_to_build_subquery david = authors(:david) assert_queries(1) { - relation = Author.where(:name => Author.where(:id => david.id).select(:name)) + relation = Author.where(name: Author.where(id: david.id).select(:name)) assert_equal [david], relation.to_a } end def test_exists - davids = Author.where(:name => "David") + davids = Author.where(name: "David") assert davids.exists? assert davids.exists?(authors(:david).id) assert ! davids.exists?(authors(:mary).id) @@ -971,7 +971,7 @@ def test_exists assert ! davids.exists?(42) assert ! davids.exists?(davids.new.id) - fake = Author.where(:name => "fake author") + fake = Author.where(name: "fake author") assert ! fake.exists? assert ! fake.exists?(authors(:david).id) end @@ -994,7 +994,7 @@ def test_last end def test_destroy_all - davids = Author.where(:name => "David") + davids = Author.where(name: "David") # Force load assert_equal [authors(:david)], davids.to_a @@ -1013,7 +1013,7 @@ def test_destroy_all_with_conditions_is_deprecated end def test_delete_all - davids = Author.where(:name => "David") + davids = Author.where(name: "David") assert_difference("Author.count", -1) { davids.delete_all } assert ! davids.loaded? @@ -1026,7 +1026,7 @@ def test_delete_all_with_conditions_is_deprecated end def test_delete_all_loaded - davids = Author.where(:name => "David") + davids = Author.where(name: "David") # Force load assert_equal [authors(:david)], davids.to_a @@ -1083,7 +1083,7 @@ def test_count assert_equal 11, posts.count(:id) assert_equal 1, posts.where("comments_count > 1").count - assert_equal 9, posts.where(:comments_count => 0).count + assert_equal 9, posts.where(comments_count: 0).count end def test_count_with_block @@ -1121,7 +1121,7 @@ def test_update_all_with_scope end def test_count_explicit_columns - Post.update_all(:comments_count => nil) + Post.update_all(comments_count: nil) posts = Post.all assert_equal [0], posts.select("comments_count").where("id is not null").group("id").order("id").count.values.uniq @@ -1145,7 +1145,7 @@ def test_size assert_queries(1) { assert_equal 11, posts.size } assert ! posts.loaded? - best_posts = posts.where(:comments_count => 0) + best_posts = posts.where(comments_count: 0) best_posts.to_a # force load assert_no_queries { assert_equal 9, best_posts.size } end @@ -1156,7 +1156,7 @@ def test_size_with_limit assert_queries(1) { assert_equal 10, posts.size } assert ! posts.loaded? - best_posts = posts.where(:comments_count => 0) + best_posts = posts.where(comments_count: 0) best_posts.to_a # force load assert_no_queries { assert_equal 9, best_posts.size } end @@ -1191,11 +1191,11 @@ def test_empty assert_queries(1) { assert_equal false, posts.empty? } assert ! posts.loaded? - no_posts = posts.where(:title => "") + no_posts = posts.where(title: "") assert_queries(1) { assert_equal true, no_posts.empty? } assert ! no_posts.loaded? - best_posts = posts.where(:comments_count => 0) + best_posts = posts.where(comments_count: 0) best_posts.to_a # force load assert_no_queries { assert_equal false, best_posts.empty? } end @@ -1206,7 +1206,7 @@ def test_empty_complex_chained_relations assert_queries(1) { assert_equal false, posts.empty? } assert ! posts.loaded? - no_posts = posts.where(:title => "") + no_posts = posts.where(title: "") assert_queries(1) { assert_equal true, no_posts.empty? } assert ! no_posts.loaded? end @@ -1220,11 +1220,11 @@ def test_any # the SHOW TABLES result to be cached so we don't have to do it again in the block. # # This is obviously a rubbish fix but it's the best I can come up with for now... - posts.where(:id => nil).any? + posts.where(id: nil).any? assert_queries(3) do assert posts.any? # Uses COUNT() - assert ! posts.where(:id => nil).any? + assert ! posts.where(id: nil).any? assert posts.any? {|p| p.id > 0 } assert ! posts.any? {|p| p.id <= 0 } @@ -1302,7 +1302,7 @@ def test_build end def test_scoped_build - posts = Post.where(:title => "You told a lie") + posts = Post.where(title: "You told a lie") post = posts.new assert_kind_of Post, post @@ -1316,7 +1316,7 @@ def test_create assert_kind_of Bird, sparrow assert !sparrow.persisted? - hen = birds.where(:name => "hen").create + hen = birds.where(name: "hen").create assert hen.persisted? assert_equal "hen", hen.name end @@ -1326,107 +1326,107 @@ def test_create_bang assert_raises(ActiveRecord::RecordInvalid) { birds.create! } - hen = birds.where(:name => "hen").create! + hen = birds.where(name: "hen").create! assert_kind_of Bird, hen assert hen.persisted? assert_equal "hen", hen.name end def test_first_or_create - parrot = Bird.where(:color => "green").first_or_create(:name => "parrot") + parrot = Bird.where(color: "green").first_or_create(name: "parrot") assert_kind_of Bird, parrot assert parrot.persisted? assert_equal "parrot", parrot.name assert_equal "green", parrot.color - same_parrot = Bird.where(:color => "green").first_or_create(:name => "parakeet") + same_parrot = Bird.where(color: "green").first_or_create(name: "parakeet") assert_kind_of Bird, same_parrot assert same_parrot.persisted? assert_equal parrot, same_parrot end def test_first_or_create_with_no_parameters - parrot = Bird.where(:color => "green").first_or_create + parrot = Bird.where(color: "green").first_or_create assert_kind_of Bird, parrot assert !parrot.persisted? assert_equal "green", parrot.color end def test_first_or_create_with_block - parrot = Bird.where(:color => "green").first_or_create { |bird| bird.name = "parrot" } + parrot = Bird.where(color: "green").first_or_create { |bird| bird.name = "parrot" } assert_kind_of Bird, parrot assert parrot.persisted? assert_equal "green", parrot.color assert_equal "parrot", parrot.name - same_parrot = Bird.where(:color => "green").first_or_create { |bird| bird.name = "parakeet" } + same_parrot = Bird.where(color: "green").first_or_create { |bird| bird.name = "parakeet" } assert_equal parrot, same_parrot end def test_first_or_create_with_array - several_green_birds = Bird.where(:color => "green").first_or_create([{:name => "parrot"}, {:name => "parakeet"}]) + several_green_birds = Bird.where(color: "green").first_or_create([{name: "parrot"}, {name: "parakeet"}]) assert_kind_of Array, several_green_birds several_green_birds.each { |bird| assert bird.persisted? } - same_parrot = Bird.where(:color => "green").first_or_create([{:name => "hummingbird"}, {:name => "macaw"}]) + same_parrot = Bird.where(color: "green").first_or_create([{name: "hummingbird"}, {name: "macaw"}]) assert_kind_of Bird, same_parrot assert_equal several_green_birds.first, same_parrot end def test_first_or_create_bang_with_valid_options - parrot = Bird.where(:color => "green").first_or_create!(:name => "parrot") + parrot = Bird.where(color: "green").first_or_create!(name: "parrot") assert_kind_of Bird, parrot assert parrot.persisted? assert_equal "parrot", parrot.name assert_equal "green", parrot.color - same_parrot = Bird.where(:color => "green").first_or_create!(:name => "parakeet") + same_parrot = Bird.where(color: "green").first_or_create!(name: "parakeet") assert_kind_of Bird, same_parrot assert same_parrot.persisted? assert_equal parrot, same_parrot end def test_first_or_create_bang_with_invalid_options - assert_raises(ActiveRecord::RecordInvalid) { Bird.where(:color => "green").first_or_create!(:pirate_id => 1) } + assert_raises(ActiveRecord::RecordInvalid) { Bird.where(color: "green").first_or_create!(pirate_id: 1) } end def test_first_or_create_bang_with_no_parameters - assert_raises(ActiveRecord::RecordInvalid) { Bird.where(:color => "green").first_or_create! } + assert_raises(ActiveRecord::RecordInvalid) { Bird.where(color: "green").first_or_create! } end def test_first_or_create_bang_with_valid_block - parrot = Bird.where(:color => "green").first_or_create! { |bird| bird.name = "parrot" } + parrot = Bird.where(color: "green").first_or_create! { |bird| bird.name = "parrot" } assert_kind_of Bird, parrot assert parrot.persisted? assert_equal "green", parrot.color assert_equal "parrot", parrot.name - same_parrot = Bird.where(:color => "green").first_or_create! { |bird| bird.name = "parakeet" } + same_parrot = Bird.where(color: "green").first_or_create! { |bird| bird.name = "parakeet" } assert_equal parrot, same_parrot end def test_first_or_create_bang_with_invalid_block assert_raise(ActiveRecord::RecordInvalid) do - Bird.where(:color => "green").first_or_create! { |bird| bird.pirate_id = 1 } + Bird.where(color: "green").first_or_create! { |bird| bird.pirate_id = 1 } end end def test_first_or_create_with_valid_array - several_green_birds = Bird.where(:color => "green").first_or_create!([{:name => "parrot"}, {:name => "parakeet"}]) + several_green_birds = Bird.where(color: "green").first_or_create!([{name: "parrot"}, {name: "parakeet"}]) assert_kind_of Array, several_green_birds several_green_birds.each { |bird| assert bird.persisted? } - same_parrot = Bird.where(:color => "green").first_or_create!([{:name => "hummingbird"}, {:name => "macaw"}]) + same_parrot = Bird.where(color: "green").first_or_create!([{name: "hummingbird"}, {name: "macaw"}]) assert_kind_of Bird, same_parrot assert_equal several_green_birds.first, same_parrot end def test_first_or_create_with_invalid_array - assert_raises(ActiveRecord::RecordInvalid) { Bird.where(:color => "green").first_or_create!([ {:name => "parrot"}, {:pirate_id => 1} ]) } + assert_raises(ActiveRecord::RecordInvalid) { Bird.where(color: "green").first_or_create!([ {name: "parrot"}, {pirate_id: 1} ]) } end def test_first_or_initialize - parrot = Bird.where(:color => "green").first_or_initialize(:name => "parrot") + parrot = Bird.where(color: "green").first_or_initialize(name: "parrot") assert_kind_of Bird, parrot assert !parrot.persisted? assert parrot.valid? @@ -1436,7 +1436,7 @@ def test_first_or_initialize end def test_first_or_initialize_with_no_parameters - parrot = Bird.where(:color => "green").first_or_initialize + parrot = Bird.where(color: "green").first_or_initialize assert_kind_of Bird, parrot assert !parrot.persisted? assert !parrot.valid? @@ -1445,7 +1445,7 @@ def test_first_or_initialize_with_no_parameters end def test_first_or_initialize_with_block - parrot = Bird.where(:color => "green").first_or_initialize { |bird| bird.name = "parrot" } + parrot = Bird.where(color: "green").first_or_initialize { |bird| bird.name = "parrot" } assert_kind_of Bird, parrot assert !parrot.persisted? assert parrot.valid? @@ -1488,37 +1488,37 @@ def test_find_or_initialize_by end def test_explicit_create_scope - hens = Bird.where(:name => "hen") + hens = Bird.where(name: "hen") assert_equal "hen", hens.new.name - hens = hens.create_with(:name => "cock") + hens = hens.create_with(name: "cock") assert_equal "cock", hens.new.name end def test_except - relation = Post.where(:author_id => 1).order("id ASC").limit(1) + relation = Post.where(author_id: 1).order("id ASC").limit(1) assert_equal [posts(:welcome)], relation.to_a author_posts = relation.except(:order, :limit) - assert_equal Post.where(:author_id => 1).to_a, author_posts.to_a + assert_equal Post.where(author_id: 1).to_a, author_posts.to_a all_posts = relation.except(:where, :order, :limit) assert_equal Post.all, all_posts end def test_only - relation = Post.where(:author_id => 1).order("id ASC").limit(1) + relation = Post.where(author_id: 1).order("id ASC").limit(1) assert_equal [posts(:welcome)], relation.to_a author_posts = relation.only(:where) - assert_equal Post.where(:author_id => 1).to_a, author_posts.to_a + assert_equal Post.where(author_id: 1).to_a, author_posts.to_a all_posts = relation.only(:limit) assert_equal Post.limit(1).to_a.first, all_posts.first end def test_anonymous_extension - relation = Post.where(:author_id => 1).order("id ASC").extending do + relation = Post.where(author_id: 1).order("id ASC").extending do def author "lifo" end @@ -1529,7 +1529,7 @@ def author end def test_named_extension - relation = Post.where(:author_id => 1).order("id ASC").extending(Post::NamedExtension) + relation = Post.where(author_id: 1).order("id ASC").extending(Post::NamedExtension) assert_equal "lifo", relation.author assert_equal "lifo", relation.limit(1).author end @@ -1561,7 +1561,7 @@ def test_unscoped_block_style end def test_intersection_with_array - relation = Author.where(:name => "David") + relation = Author.where(name: "David") rails_author = relation.first assert_equal [rails_author], [rails_author] & relation @@ -1584,18 +1584,18 @@ def test_update_all_with_joins comments = Comment.joins(:post).where("posts.id" => posts(:welcome).id) count = comments.count - assert_equal count, comments.update_all(:post_id => posts(:thinking).id) + assert_equal count, comments.update_all(post_id: posts(:thinking).id) assert_equal posts(:thinking), comments(:greetings).post end def test_update_all_with_joins_and_limit comments = Comment.joins(:post).where("posts.id" => posts(:welcome).id).limit(1) - assert_equal 1, comments.update_all(:post_id => posts(:thinking).id) + assert_equal 1, comments.update_all(post_id: posts(:thinking).id) end def test_update_all_with_joins_and_limit_and_order comments = Comment.joins(:post).where("posts.id" => posts(:welcome).id).order("comments.id").limit(1) - assert_equal 1, comments.update_all(:post_id => posts(:thinking).id) + assert_equal 1, comments.update_all(post_id: posts(:thinking).id) assert_equal posts(:thinking), comments(:greetings).post assert_equal posts(:welcome), comments(:more_greetings).post end @@ -1605,7 +1605,7 @@ def test_update_all_with_joins_and_offset count = all_comments.count comments = all_comments.offset(1) - assert_equal count - 1, comments.update_all(:post_id => posts(:thinking).id) + assert_equal count - 1, comments.update_all(post_id: posts(:thinking).id) end def test_update_all_with_joins_and_offset_and_order @@ -1613,7 +1613,7 @@ def test_update_all_with_joins_and_offset_and_order count = all_comments.count comments = all_comments.offset(1) - assert_equal count - 1, comments.update_all(:post_id => posts(:thinking).id) + assert_equal count - 1, comments.update_all(post_id: posts(:thinking).id) assert_equal posts(:thinking), comments(:more_greetings).post assert_equal posts(:welcome), comments(:greetings).post end @@ -1639,10 +1639,10 @@ def test_update_on_relation_passing_active_record_object_is_deprecated end def test_distinct - tag1 = Tag.create(:name => "Foo") - tag2 = Tag.create(:name => "Foo") + tag1 = Tag.create(name: "Foo") + tag2 = Tag.create(name: "Foo") - query = Tag.select(:name).where(:id => [tag1.id, tag2.id]) + query = Tag.select(:name).where(id: [tag1.id, tag2.id]) assert_equal ["Foo", "Foo"], query.map(&:name) assert_sql(/DISTINCT/) do @@ -1701,7 +1701,7 @@ def test_references_doesnt_trigger_eager_loading_if_reference_not_included end def test_automatically_added_where_references - scope = Post.where(:comments => { :body => "Bla" }) + scope = Post.where(comments: { body: "Bla" }) assert_equal ["comments"], scope.references_values scope = Post.where("comments.body" => "Bla") @@ -1717,7 +1717,7 @@ def test_automatically_added_where_not_references end def test_automatically_added_having_references - scope = Post.having(:comments => { :body => "Bla" }) + scope = Post.having(comments: { body: "Bla" }) assert_equal ["comments"], scope.references_values scope = Post.having("comments.body" => "Bla") @@ -1915,7 +1915,7 @@ def test_presence table_metadata = ActiveRecord::TableMetadata.new(Post, table_alias) predicate_builder = ActiveRecord::PredicateBuilder.new(table_metadata) relation = ActiveRecord::Relation.new(Post, table_alias, predicate_builder) - relation.where!(:foo => "bar") + relation.where!(foo: "bar") node = relation.arel.constraints.first.grep(Arel::Attributes::Attribute).first assert_equal table_alias, node.relation diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb index f649ef3660..fc7a653557 100644 --- a/activerecord/test/cases/sanitize_test.rb +++ b/activerecord/test/cases/sanitize_test.rb @@ -90,10 +90,10 @@ def test_bind_arity end def test_named_bind_variables - assert_equal "1", bind(":a", :a => 1) # ' ruby-mode - assert_equal "1 1", bind(":a :a", :a => 1) # ' ruby-mode + assert_equal "1", bind(":a", a: 1) # ' ruby-mode + assert_equal "1 1", bind(":a :a", a: 1) # ' ruby-mode - assert_nothing_raised { bind("'+00:00'", :foo => "bar") } + assert_nothing_raised { bind("'+00:00'", foo: "bar") } end def test_named_bind_arity @@ -120,14 +120,14 @@ def test_bind_enumerable assert_equal "1,2,3", bind("?", [1, 2, 3]) assert_equal quoted_abc, bind("?", %w(a b c)) - assert_equal "1,2,3", bind(":a", :a => [1, 2, 3]) - assert_equal quoted_abc, bind(":a", :a => %w(a b c)) # ' + assert_equal "1,2,3", bind(":a", a: [1, 2, 3]) + assert_equal quoted_abc, bind(":a", a: %w(a b c)) # ' assert_equal "1,2,3", bind("?", SimpleEnumerable.new([1, 2, 3])) assert_equal quoted_abc, bind("?", SimpleEnumerable.new(%w(a b c))) - assert_equal "1,2,3", bind(":a", :a => SimpleEnumerable.new([1, 2, 3])) - assert_equal quoted_abc, bind(":a", :a => SimpleEnumerable.new(%w(a b c))) # ' + assert_equal "1,2,3", bind(":a", a: SimpleEnumerable.new([1, 2, 3])) + assert_equal quoted_abc, bind(":a", a: SimpleEnumerable.new(%w(a b c))) # ' end def test_bind_empty_enumerable @@ -160,7 +160,7 @@ def test_bind_record end def test_named_bind_with_postgresql_type_casts - l = Proc.new { bind(":a::integer '2009-01-01'::date", :a => "10") } + l = Proc.new { bind(":a::integer '2009-01-01'::date", a: "10") } assert_nothing_raised(&l) assert_equal "#{ActiveRecord::Base.connection.quote('10')}::integer '2009-01-01'::date", l.call end diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index cbc79109f7..2ad3da94e4 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -20,7 +20,7 @@ def perform_schema_dump def test_dump_schema_information_outputs_lexically_ordered_versions versions = %w{ 20100101010101 20100201010101 20100301010101 } versions.reverse_each do |v| - ActiveRecord::SchemaMigration.create!(:version => v) + ActiveRecord::SchemaMigration.create!(version: v) end schema_info = ActiveRecord::Base.connection.dump_schema_information @@ -37,7 +37,7 @@ def test_dump_schema_information_outputs_lexically_ordered_versions versions = %w{ 20100101010101 20100201010101 20100301010101 } versions.reverse_each do |v| - ActiveRecord::SchemaMigration.create!(:version => v) + ActiveRecord::SchemaMigration.create!(version: v) end schema_info = ActiveRecord::Base.connection.dump_schema_information diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb index dc938f779c..effecfd294 100644 --- a/activerecord/test/cases/scoping/default_scoping_test.rb +++ b/activerecord/test/cases/scoping/default_scoping_test.rb @@ -11,7 +11,7 @@ class DefaultScopingTest < ActiveRecord::TestCase fixtures :developers, :posts, :comments def test_default_scope - expected = Developer.all.merge!(:order => "salary DESC").to_a.collect(&:salary) + expected = Developer.all.merge!(order: "salary DESC").to_a.collect(&:salary) received = DeveloperOrderedBySalary.all.collect(&:salary) assert_equal expected, received end @@ -132,7 +132,7 @@ def test_unscope_with_where_attributes assert_equal expected, received expected_2 = Developer.order("salary DESC").collect(&:name) - received_2 = DeveloperOrderedBySalary.select("id").where("name" => "Jamis").unscope({:where => :name}, :select).collect(&:name) + received_2 = DeveloperOrderedBySalary.select("id").where("name" => "Jamis").unscope({where: :name}, :select).collect(&:name) assert_equal expected_2, received_2 expected_3 = Developer.order("salary DESC").collect(&:name) @@ -310,28 +310,28 @@ def test_order_in_default_scope_should_not_prevail end def test_create_attribute_overwrites_default_scoping - assert_equal "David", PoorDeveloperCalledJamis.create!(:name => "David").name - assert_equal 200000, PoorDeveloperCalledJamis.create!(:name => "David", :salary => 200000).salary + assert_equal "David", PoorDeveloperCalledJamis.create!(name: "David").name + assert_equal 200000, PoorDeveloperCalledJamis.create!(name: "David", salary: 200000).salary end def test_create_attribute_overwrites_default_values - assert_equal nil, PoorDeveloperCalledJamis.create!(:salary => nil).salary - assert_equal 50000, PoorDeveloperCalledJamis.create!(:name => "David").salary + assert_equal nil, PoorDeveloperCalledJamis.create!(salary: nil).salary + assert_equal 50000, PoorDeveloperCalledJamis.create!(name: "David").salary end def test_default_scope_attribute - jamis = PoorDeveloperCalledJamis.new(:name => "David") + jamis = PoorDeveloperCalledJamis.new(name: "David") assert_equal 50000, jamis.salary end def test_where_attribute - aaron = PoorDeveloperCalledJamis.where(:salary => 20).new(:name => "Aaron") + aaron = PoorDeveloperCalledJamis.where(salary: 20).new(name: "Aaron") assert_equal 20, aaron.salary assert_equal "Aaron", aaron.name end def test_where_attribute_merge - aaron = PoorDeveloperCalledJamis.where(:name => "foo").new(:name => "Aaron") + aaron = PoorDeveloperCalledJamis.where(name: "foo").new(name: "Aaron") assert_equal "Aaron", aaron.name end @@ -342,26 +342,26 @@ def test_scope_composed_by_limit_and_then_offset_is_equal_to_scope_composed_by_o end def test_create_with_merge - aaron = PoorDeveloperCalledJamis.create_with(:name => "foo", :salary => 20).merge( - PoorDeveloperCalledJamis.create_with(:name => "Aaron")).new + aaron = PoorDeveloperCalledJamis.create_with(name: "foo", salary: 20).merge( + PoorDeveloperCalledJamis.create_with(name: "Aaron")).new assert_equal 20, aaron.salary assert_equal "Aaron", aaron.name - aaron = PoorDeveloperCalledJamis.create_with(:name => "foo", :salary => 20). - create_with(:name => "Aaron").new + aaron = PoorDeveloperCalledJamis.create_with(name: "foo", salary: 20). + create_with(name: "Aaron").new assert_equal 20, aaron.salary assert_equal "Aaron", aaron.name end def test_create_with_reset - jamis = PoorDeveloperCalledJamis.create_with(:name => "Aaron").create_with(nil).new + jamis = PoorDeveloperCalledJamis.create_with(name: "Aaron").create_with(nil).new assert_equal "Jamis", jamis.name end # FIXME: I don't know if this is *desired* behavior, but it is *today's* # behavior. def test_create_with_empty_hash_will_not_reset - jamis = PoorDeveloperCalledJamis.create_with(:name => "Aaron").create_with({}).new + jamis = PoorDeveloperCalledJamis.create_with(name: "Aaron").create_with({}).new assert_equal "Aaron", jamis.name end @@ -410,9 +410,9 @@ def test_default_scope_find_last def test_default_scope_include_with_count d = DeveloperWithIncludes.create! - d.audit_logs.create! :message => "foo" + d.audit_logs.create! message: "foo" - assert_equal 1, DeveloperWithIncludes.where(:audit_logs => { :message => "foo" }).count + assert_equal 1, DeveloperWithIncludes.where(audit_logs: { message: "foo" }).count end def test_default_scope_with_references_works_through_collection_association diff --git a/activerecord/test/cases/scoping/named_scoping_test.rb b/activerecord/test/cases/scoping/named_scoping_test.rb index 1327bf3253..690544ed26 100644 --- a/activerecord/test/cases/scoping/named_scoping_test.rb +++ b/activerecord/test/cases/scoping/named_scoping_test.rb @@ -69,10 +69,10 @@ def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy end def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified - assert !Topic.all.merge!(:where => {:approved => true}).to_a.empty? + assert !Topic.all.merge!(where: {approved: true}).to_a.empty? - assert_equal Topic.all.merge!(:where => {:approved => true}).to_a, Topic.approved - assert_equal Topic.where(:approved => true).count, Topic.approved.count + assert_equal Topic.all.merge!(where: {approved: true}).to_a, Topic.approved + assert_equal Topic.where(approved: true).count, Topic.approved.count end def test_scopes_with_string_name_can_be_composed @@ -82,8 +82,8 @@ def test_scopes_with_string_name_can_be_composed end def test_scopes_are_composable - assert_equal((approved = Topic.all.merge!(:where => {:approved => true}).to_a), Topic.approved) - assert_equal((replied = Topic.all.merge!(:where => "replies_count > 0").to_a), Topic.replied) + assert_equal((approved = Topic.all.merge!(where: {approved: true}).to_a), Topic.approved) + assert_equal((replied = Topic.all.merge!(where: "replies_count > 0").to_a), Topic.replied) assert !(approved == replied) assert !(approved & replied).empty? @@ -238,9 +238,9 @@ def test_many_should_not_fire_query_if_scope_loaded end def test_many_should_return_false_if_none_or_one - topics = Topic.base.where(:id => 0) + topics = Topic.base.where(id: 0) assert !topics.many? - topics = Topic.base.where(:id => 1) + topics = Topic.base.where(id: 1) assert !topics.many? end @@ -357,7 +357,7 @@ def test_spaces_in_scope_names klass = Class.new(ActiveRecord::Base) do self.table_name = "topics" scope :"title containing space", -> { where("title LIKE '% %'") } - scope :approved, -> { where(:approved => true) } + scope :approved, -> { where(approved: true) } end assert_equal klass.send(:"title containing space"), klass.where("title LIKE '% %'") assert_equal klass.approved.send(:"title containing space"), klass.approved.where("title LIKE '% %'") @@ -431,11 +431,11 @@ def test_scopes_batch_finders assert_equal 4, Topic.approved.count assert_queries(5) do - Topic.approved.find_each(:batch_size => 1) {|t| assert t.approved? } + Topic.approved.find_each(batch_size: 1) {|t| assert t.approved? } end assert_queries(3) do - Topic.approved.find_in_batches(:batch_size => 2) do |group| + Topic.approved.find_in_batches(batch_size: 2) do |group| group.each {|t| assert t.approved? } end end @@ -517,7 +517,7 @@ def test_scopes_with_arguments_are_cached_on_associations def test_scopes_to_get_newest post = posts(:welcome) old_last_comment = post.comments.newest - new_comment = post.comments.create(:body => "My new comment") + new_comment = post.comments.create(body: "My new comment") assert_equal new_comment, post.comments.newest assert_not_equal old_last_comment, post.comments.newest end @@ -543,7 +543,7 @@ def test_eager_default_scope_relations_are_remove klass.table_name = "posts" assert_raises(ArgumentError) do - klass.send(:default_scope, klass.where(:id => posts(:welcome).id)) + klass.send(:default_scope, klass.where(id: posts(:welcome).id)) end end diff --git a/activerecord/test/cases/scoping/relation_scoping_test.rb b/activerecord/test/cases/scoping/relation_scoping_test.rb index 253c4195df..0428e1640e 100644 --- a/activerecord/test/cases/scoping/relation_scoping_test.rb +++ b/activerecord/test/cases/scoping/relation_scoping_test.rb @@ -150,8 +150,8 @@ def test_scoped_find_joins end def test_scoped_create_with_where - new_comment = VerySpecialComment.where(:post_id => 1).scoping do - VerySpecialComment.create :body => "Wonderful world" + new_comment = VerySpecialComment.where(post_id: 1).scoping do + VerySpecialComment.create body: "Wonderful world" end assert_equal 1, new_comment.post_id @@ -159,8 +159,8 @@ def test_scoped_create_with_where end def test_scoped_create_with_create_with - new_comment = VerySpecialComment.create_with(:post_id => 1).scoping do - VerySpecialComment.create :body => "Wonderful world" + new_comment = VerySpecialComment.create_with(post_id: 1).scoping do + VerySpecialComment.create body: "Wonderful world" end assert_equal 1, new_comment.post_id @@ -168,8 +168,8 @@ def test_scoped_create_with_create_with end def test_scoped_create_with_create_with_has_higher_priority - new_comment = VerySpecialComment.where(:post_id => 2).create_with(:post_id => 1).scoping do - VerySpecialComment.create :body => "Wonderful world" + new_comment = VerySpecialComment.where(post_id: 2).create_with(post_id: 1).scoping do + VerySpecialComment.create body: "Wonderful world" end assert_equal 1, new_comment.post_id @@ -193,7 +193,7 @@ def test_default_scope_filters_on_joins end def test_update_all_default_scope_filters_on_joins - DeveloperFilteredOnJoins.update_all(:salary => 65000) + DeveloperFilteredOnJoins.update_all(salary: 65000) assert_equal 65000, Developer.find(developers(:david).id).salary # has not changed jamis @@ -260,9 +260,9 @@ def test_merge_inner_scope_has_priority end def test_replace_options - Developer.where(:name => "David").scoping do + Developer.where(name: "David").scoping do Developer.unscoped do - assert_equal "Jamis", Developer.where(:name => "Jamis").first[:name] + assert_equal "Jamis", Developer.where(name: "Jamis").first[:name] end assert_equal "David", Developer.first[:name] @@ -290,9 +290,9 @@ def test_three_level_nested_exclusive_scoped_find end def test_nested_scoped_create - comment = Comment.create_with(:post_id => 1).scoping do - Comment.create_with(:post_id => 2).scoping do - Comment.create :body => "Hey guys, nested scopes are broken. Please fix!" + comment = Comment.create_with(post_id: 1).scoping do + Comment.create_with(post_id: 2).scoping do + Comment.create body: "Hey guys, nested scopes are broken. Please fix!" end end @@ -300,10 +300,10 @@ def test_nested_scoped_create end def test_nested_exclusive_scope_for_create - comment = Comment.create_with(:body => "Hey guys, nested scopes are broken. Please fix!").scoping do - Comment.unscoped.create_with(:post_id => 1).scoping do + comment = Comment.create_with(body: "Hey guys, nested scopes are broken. Please fix!").scoping do + Comment.unscoped.create_with(post_id: 1).scoping do assert Comment.new.body.blank? - Comment.create :body => "Hey guys" + Comment.create body: "Hey guys" end end @@ -352,7 +352,7 @@ def test_should_default_scope_on_associations_is_overridden_by_association_condi end def test_should_maintain_default_scope_on_eager_loaded_associations - michael = Person.where(:id => people(:michael).id).includes(:bad_references).first + michael = Person.where(id: people(:michael).id).includes(:bad_references).first magician = BadReference.find(1) assert_equal [magician], michael.bad_references end diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb index b4fdc1f30a..ec33ad38f2 100644 --- a/activerecord/test/cases/serialization_test.rb +++ b/activerecord/test/cases/serialization_test.rb @@ -12,14 +12,14 @@ class SerializationTest < ActiveRecord::TestCase def setup @contact_attributes = { - :name => "aaron stack", - :age => 25, - :avatar => "binarydata", - :created_at => Time.utc(2006, 8, 1), - :awesome => false, - :preferences => { :gem => "ruby" }, - :alternative_id => nil, - :id => nil + name: "aaron stack", + age: 25, + avatar: "binarydata", + created_at: Time.utc(2006, 8, 1), + awesome: false, + preferences: { gem: "ruby" }, + alternative_id: nil, + id: nil } end @@ -38,7 +38,7 @@ def test_serialize_should_be_reversible def test_serialize_should_allow_attribute_only_filtering FORMATS.each do |format| - @serialized = Contact.new(@contact_attributes).send("to_#{format}", :only => [ :age, :name ]) + @serialized = Contact.new(@contact_attributes).send("to_#{format}", only: [ :age, :name ]) contact = Contact.new.send("from_#{format}", @serialized) assert_equal @contact_attributes[:name], contact.name, "For #{format}" assert_nil contact.avatar, "For #{format}" @@ -47,7 +47,7 @@ def test_serialize_should_allow_attribute_only_filtering def test_serialize_should_allow_attribute_except_filtering FORMATS.each do |format| - @serialized = Contact.new(@contact_attributes).send("to_#{format}", :except => [ :age, :name ]) + @serialized = Contact.new(@contact_attributes).send("to_#{format}", except: [ :age, :name ]) contact = Contact.new.send("from_#{format}", @serialized) assert_nil contact.name, "For #{format}" assert_nil contact.age, "For #{format}" diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index f465e8e7e1..ceb0d5441b 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -124,14 +124,14 @@ def test_nil_serialized_attribute_without_class_constraint end def test_nil_not_serialized_without_class_constraint - assert Topic.new(:content => nil).save - assert_equal 1, Topic.where(:content => nil).count + assert Topic.new(content: nil).save + assert_equal 1, Topic.where(content: nil).count end def test_nil_not_serialized_with_class_constraint Topic.serialize :content, Hash - assert Topic.new(:content => nil).save - assert_equal 1, Topic.where(:content => nil).count + assert Topic.new(content: nil).save + assert_equal 1, Topic.where(content: nil).count end def test_serialized_attribute_should_raise_exception_on_assignment_with_wrong_type @@ -143,7 +143,7 @@ def test_serialized_attribute_should_raise_exception_on_assignment_with_wrong_ty def test_should_raise_exception_on_serialized_attribute_with_type_mismatch myobj = MyObject.new("value1", "value2") - topic = Topic.new(:content => myobj) + topic = Topic.new(content: myobj) assert topic.save Topic.serialize(:content, Hash) assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).content } @@ -152,7 +152,7 @@ def test_should_raise_exception_on_serialized_attribute_with_type_mismatch def test_serialized_attribute_with_class_constraint settings = { "color" => "blue" } Topic.serialize(:content, Hash) - topic = Topic.new(:content => settings) + topic = Topic.new(content: settings) assert topic.save assert_equal(settings, Topic.find(topic.id).content) end @@ -175,14 +175,14 @@ def test_serialized_no_default_class_for_object end def test_serialized_boolean_value_true - topic = Topic.new(:content => true) + topic = Topic.new(content: true) assert topic.save topic = topic.reload assert_equal topic.content, true end def test_serialized_boolean_value_false - topic = Topic.new(:content => false) + topic = Topic.new(content: false) assert topic.save topic = topic.reload assert_equal topic.content, false @@ -200,7 +200,7 @@ def self.load(value) end Topic.serialize(:content, some_class) - topic = Topic.new(:content => some_class.new("my value")) + topic = Topic.new(content: some_class.new("my value")) topic.save! topic.reload assert_kind_of some_class, topic.content diff --git a/activerecord/test/cases/statement_cache_test.rb b/activerecord/test/cases/statement_cache_test.rb index e5755d55ed..df75dd3247 100644 --- a/activerecord/test/cases/statement_cache_test.rb +++ b/activerecord/test/cases/statement_cache_test.rb @@ -16,7 +16,7 @@ def test_statement_cache Book.create(name: "my other book") cache = StatementCache.create(Book.connection) do |params| - Book.where(:name => params.bind) + Book.where(name: params.bind) end b = cache.execute([ "my book" ], Book, Book.connection) @@ -65,7 +65,7 @@ def test_statement_cache_with_simple_statement def test_statement_cache_with_complex_statement cache = ActiveRecord::StatementCache.create(Book.connection) do |params| - Liquid.joins(:molecules => :electrons).where("molecules.name" => "dioxane", "electrons.name" => "lepton") + Liquid.joins(molecules: :electrons).where("molecules.name" => "dioxane", "electrons.name" => "lepton") end salty = Liquid.create(name: "salty") diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb index 44275d3280..633a8a0ebc 100644 --- a/activerecord/test/cases/store_test.rb +++ b/activerecord/test/cases/store_test.rb @@ -6,7 +6,7 @@ class StoreTest < ActiveRecord::TestCase fixtures :'admin/users' setup do - @john = Admin::User.create!(:name => "John Doe", :color => "black", :remember_login => true, :height => "tall", :is_a_good_guy => true) + @john = Admin::User.create!(name: "John Doe", color: "black", remember_login: true, height: "tall", is_a_good_guy: true) end test "reading store attributes through accessors" do diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb index 946d337572..0519c70ac7 100644 --- a/activerecord/test/cases/tasks/database_tasks_test.rb +++ b/activerecord/test/cases/tasks/database_tasks_test.rb @@ -213,7 +213,7 @@ class DatabaseTasksDropTest < ActiveRecord::TestCase class DatabaseTasksDropAllTest < ActiveRecord::TestCase def setup - @configurations = {:development => {"database" => "my-db"}} + @configurations = {development: {"database" => "my-db"}} ActiveRecord::Base.stubs(:configurations).returns(@configurations) end @@ -374,7 +374,7 @@ def test_purges_current_environment_database class DatabaseTasksPurgeAllTest < ActiveRecord::TestCase def test_purge_all_local_configurations - configurations = {:development => {"database" => "my-db"}} + configurations = {development: {"database" => "my-db"}} ActiveRecord::Base.stubs(:configurations).returns(configurations) ActiveRecord::Tasks::DatabaseTasks.expects(:purge). diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb index 16ed83b072..be2f2e5939 100644 --- a/activerecord/test/cases/tasks/mysql_rake_test.rb +++ b/activerecord/test/cases/tasks/mysql_rake_test.rb @@ -5,7 +5,7 @@ module ActiveRecord class MysqlDBCreateTest < ActiveRecord::TestCase def setup - @connection = stub(:create_database => true) + @connection = stub(create_database: true) @configuration = { "adapter" => "mysql2", "database" => "my-app-db" @@ -173,7 +173,7 @@ def assert_permissions_granted_for(db_user) class MySQLDBDropTest < ActiveRecord::TestCase def setup - @connection = stub(:drop_database => true) + @connection = stub(drop_database: true) @configuration = { "adapter" => "mysql2", "database" => "my-app-db" @@ -211,7 +211,7 @@ def test_when_database_dropped_successfully_outputs_info_to_stdout class MySQLPurgeTest < ActiveRecord::TestCase def setup - @connection = stub(:recreate_database => true) + @connection = stub(recreate_database: true) @configuration = { "adapter" => "mysql2", "database" => "test-db" @@ -245,7 +245,7 @@ def test_recreates_database_with_the_given_options class MysqlDBCharsetTest < ActiveRecord::TestCase def setup - @connection = stub(:create_database => true) + @connection = stub(create_database: true) @configuration = { "adapter" => "mysql2", "database" => "my-app-db" @@ -263,7 +263,7 @@ def test_db_retrieves_charset class MysqlDBCollationTest < ActiveRecord::TestCase def setup - @connection = stub(:create_database => true) + @connection = stub(create_database: true) @configuration = { "adapter" => "mysql2", "database" => "my-app-db" diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb index 8c3fc8c6a1..fdfe4e979f 100644 --- a/activerecord/test/cases/tasks/postgresql_rake_test.rb +++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb @@ -5,7 +5,7 @@ module ActiveRecord class PostgreSQLDBCreateTest < ActiveRecord::TestCase def setup - @connection = stub(:create_database => true) + @connection = stub(create_database: true) @configuration = { "adapter" => "postgresql", "database" => "my-app-db" @@ -90,7 +90,7 @@ def test_create_when_database_exists_outputs_info_to_stderr class PostgreSQLDBDropTest < ActiveRecord::TestCase def setup - @connection = stub(:drop_database => true) + @connection = stub(drop_database: true) @configuration = { "adapter" => "postgresql", "database" => "my-app-db" @@ -132,7 +132,7 @@ def test_when_database_dropped_successfully_outputs_info_to_stdout class PostgreSQLPurgeTest < ActiveRecord::TestCase def setup - @connection = stub(:create_database => true, :drop_database => true) + @connection = stub(create_database: true, drop_database: true) @configuration = { "adapter" => "postgresql", "database" => "my-app-db" @@ -181,7 +181,7 @@ def test_establishes_connection class PostgreSQLDBCharsetTest < ActiveRecord::TestCase def setup - @connection = stub(:create_database => true) + @connection = stub(create_database: true) @configuration = { "adapter" => "postgresql", "database" => "my-app-db" @@ -199,7 +199,7 @@ def test_db_retrieves_charset class PostgreSQLDBCollationTest < ActiveRecord::TestCase def setup - @connection = stub(:create_database => true) + @connection = stub(create_database: true) @configuration = { "adapter" => "postgresql", "database" => "my-app-db" @@ -217,7 +217,7 @@ def test_db_retrieves_collation class PostgreSQLStructureDumpTest < ActiveRecord::TestCase def setup - @connection = stub(:structure_dump => true) + @connection = stub(structure_dump: true) @configuration = { "adapter" => "postgresql", "database" => "my-app-db" diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb index 2477df2c5b..9aeeef1aee 100644 --- a/activerecord/test/cases/tasks/sqlite_rake_test.rb +++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb @@ -74,7 +74,7 @@ def test_db_create_with_error_prints_message class SqliteDBDropTest < ActiveRecord::TestCase def setup @database = "db_create.sqlite3" - @path = stub(:to_s => "/absolute/path", :absolute? => true) + @path = stub(to_s: "/absolute/path", absolute?: true) @configuration = { "adapter" => "sqlite3", "database" => @database diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index d9b27d0e3e..c77cc1a4a6 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -241,7 +241,7 @@ def self.name; "Owner"; end def test_saving_a_record_with_a_belongs_to_that_specifies_touching_a_specific_attribute_the_parent_should_update_that_attribute klass = Class.new(ActiveRecord::Base) do def self.name; "Pet"; end - belongs_to :owner, :touch => :happy_at + belongs_to :owner, touch: :happy_at end pet = klass.first @@ -257,7 +257,7 @@ def self.name; "Pet"; end def test_touching_a_record_with_a_belongs_to_that_uses_a_counter_cache_should_update_the_parent klass = Class.new(ActiveRecord::Base) do def self.name; "Pet"; end - belongs_to :owner, :counter_cache => :use_count, :touch => true + belongs_to :owner, counter_cache: :use_count, touch: true end pet = klass.first @@ -276,7 +276,7 @@ def self.name; "Pet"; end def test_touching_a_record_touches_parent_record_and_grandparent_record klass = Class.new(ActiveRecord::Base) do def self.name; "Toy"; end - belongs_to :pet, :touch => true + belongs_to :pet, touch: true end toy = klass.first @@ -298,7 +298,7 @@ def self.name; "Toy"; end wheel_klass = Class.new(ActiveRecord::Base) do def self.name; "Wheel"; end - belongs_to :wheelable, :polymorphic => true, :touch => true + belongs_to :wheelable, polymorphic: true, touch: true end toy = klass.first @@ -346,7 +346,7 @@ def self.name; "Car"; end wheel_class = Class.new(ActiveRecord::Base) do def self.name; "Wheel"; end - belongs_to :wheelable, :polymorphic => true, :touch => true + belongs_to :wheelable, polymorphic: true, touch: true end car1 = car_class.find(1) @@ -377,7 +377,7 @@ def self.name; "Toy"; end wheel_class = Class.new(ActiveRecord::Base) do def self.name; "Wheel"; end - belongs_to :wheelable, :polymorphic => true, :touch => true + belongs_to :wheelable, polymorphic: true, touch: true end car = car_class.find(1) diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb index 21e2cfa5c5..5e97077cb8 100644 --- a/activerecord/test/cases/transaction_callbacks_test.rb +++ b/activerecord/test/cases/transaction_callbacks_test.rb @@ -123,7 +123,7 @@ def test_only_call_after_commit_on_destroy_after_transaction_commits_for_destroy end def test_only_call_after_commit_on_create_after_transaction_commits_for_new_record - new_record = TopicWithCallbacks.new(:title => "New topic", :written_on => Date.today) + new_record = TopicWithCallbacks.new(title: "New topic", written_on: Date.today) add_transaction_execution_blocks new_record new_record.save! @@ -131,7 +131,7 @@ def test_only_call_after_commit_on_create_after_transaction_commits_for_new_reco end def test_only_call_after_commit_on_create_after_transaction_commits_for_new_record_if_create_succeeds_creating_through_association - topic = TopicWithCallbacks.create!(:title => "New topic", :written_on => Date.today) + topic = TopicWithCallbacks.create!(title: "New topic", written_on: Date.today) reply = topic.replies.create assert_equal [], reply.history @@ -213,7 +213,7 @@ def test_only_call_after_rollback_on_destroy_after_transaction_rollsback_for_des end def test_only_call_after_rollback_on_create_after_transaction_rollsback_for_new_record - new_record = TopicWithCallbacks.new(:title => "New topic", :written_on => Date.today) + new_record = TopicWithCallbacks.new(title: "New topic", written_on: Date.today) add_transaction_execution_blocks new_record Topic.transaction do @@ -256,7 +256,7 @@ def second.commits(i=0); @commits ||= 0; @commits += i if i; end Topic.transaction do @first.save! - Topic.transaction(:requires_new => true) do + Topic.transaction(requires_new: true) do second.save! raise ActiveRecord::Rollback end @@ -277,11 +277,11 @@ def @first.commits(i=0); @commits ||= 0; @commits += i if i; end Topic.transaction do @first.save - Topic.transaction(:requires_new => true) do + Topic.transaction(requires_new: true) do @first.save! raise ActiveRecord::Rollback end - Topic.transaction(:requires_new => true) do + Topic.transaction(requires_new: true) do @first.save! raise ActiveRecord::Rollback end diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index e775983817..6dcbc9559c 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -260,14 +260,14 @@ def after_create_for_transaction end } - new_topic = topic.new(:title => "A new topic", - :author_name => "Ben", - :author_email_address => "ben@example.com", - :written_on => "2003-07-16t15:28:11.2233+01:00", - :last_read => "2004-04-15", - :bonus_time => "2005-01-30t15:28:00.00+01:00", - :content => "Have a nice day", - :approved => false) + new_topic = topic.new(title: "A new topic", + author_name: "Ben", + author_email_address: "ben@example.com", + written_on: "2003-07-16t15:28:11.2233+01:00", + last_read: "2004-04-15", + bonus_time: "2005-01-30t15:28:00.00+01:00", + content: "Have a nice day", + approved: false) new_record_snapshot = !new_topic.persisted? id_present = new_topic.has_attribute?(Topic.primary_key) @@ -291,7 +291,7 @@ def after_create_for_transaction end } - new_topic = topic.create(:title => "A new topic") + new_topic = topic.create(title: "A new topic") assert !new_topic.persisted?, "The topic should not be persisted" assert_nil new_topic.id, "The topic should not have an ID" end @@ -329,7 +329,7 @@ def test_manually_rolling_back_a_transaction def test_invalid_keys_for_transaction assert_raise ArgumentError do - Topic.transaction :nested => true do + Topic.transaction nested: true do end end end @@ -342,7 +342,7 @@ def test_force_savepoint_in_nested_transaction @second.save! begin - Topic.transaction :requires_new => true do + Topic.transaction requires_new: true do @first.happy = false @first.save! raise @@ -363,7 +363,7 @@ def test_force_savepoint_on_instance @second.save! begin - @second.transaction :requires_new => true do + @second.transaction requires_new: true do @first.happy = false @first.save! raise @@ -403,17 +403,17 @@ def test_many_savepoints @first.save! begin - Topic.transaction :requires_new => true do + Topic.transaction requires_new: true do @first.content = "Two" @first.save! begin - Topic.transaction :requires_new => true do + Topic.transaction requires_new: true do @first.content = "Three" @first.save! begin - Topic.transaction :requires_new => true do + Topic.transaction requires_new: true do @first.content = "Four" @first.save! raise @@ -508,7 +508,7 @@ def test_rollback_when_commit_raises end def test_rollback_when_saving_a_frozen_record - topic = Topic.new(:title => "test") + topic = Topic.new(title: "test") topic.freeze e = assert_raise(RuntimeError) { topic.save } assert_match(/frozen/i, e.message) # Not good enough, but we can't do much @@ -552,9 +552,9 @@ def test_restore_active_record_state_for_all_records_in_a_transaction self.table_name = "topics" end - topic_1 = Topic.new(:title => "test_1") - topic_2 = Topic.new(:title => "test_2") - topic_3 = topic_without_callbacks.new(:title => "test_3") + topic_1 = Topic.new(title: "test_1") + topic_2 = Topic.new(title: "test_2") + topic_3 = topic_without_callbacks.new(title: "test_3") Topic.transaction do assert topic_1.save diff --git a/activerecord/test/cases/type/integer_test.rb b/activerecord/test/cases/type/integer_test.rb index b411a82705..368b6d7199 100644 --- a/activerecord/test/cases/type/integer_test.rb +++ b/activerecord/test/cases/type/integer_test.rb @@ -6,7 +6,7 @@ module Type class IntegerTest < ActiveRecord::TestCase test "casting ActiveRecord models" do type = Type::Integer.new - firm = Firm.create(:name => "Apple") + firm = Firm.create(name: "Apple") assert_nil type.cast(firm) end diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb index 09044e00b2..66d6ecb928 100644 --- a/activerecord/test/cases/validations/association_validation_test.rb +++ b/activerecord/test/cases/validations/association_validation_test.rb @@ -25,7 +25,7 @@ def test_validates_associated_many end def test_validates_associated_one - Reply.validates :topic, :associated => true + Reply.validates :topic, associated: true Topic.validates_presence_of( :content ) r = Reply.new("title" => "A reply", "content" => "with content!") r.topic = Topic.create("title" => "uhohuhoh") @@ -58,7 +58,7 @@ def valid? end def test_validates_associated_with_custom_message_using_quotes - Reply.validates_associated :topic, :message=> "This string contains 'single' and \"double\" quotes" + Reply.validates_associated :topic, message: "This string contains 'single' and \"double\" quotes" Topic.validates_presence_of :content r = Reply.create("title" => "A reply", "content" => "with content!") r.topic = Topic.create("title" => "uhohuhoh") @@ -80,8 +80,8 @@ def test_validates_presence_of_belongs_to_association__parent_is_new_record repair_validations(Interest) do # Note that Interest and Man have the :inverse_of option set Interest.validates_presence_of(:man) - man = Man.new(:name => "John") - interest = man.interests.build(:topic => "Airplanes") + man = Man.new(name: "John") + interest = man.interests.build(topic: "Airplanes") assert interest.valid?, "Expected interest to be valid, but was not. Interest should have a man object associated" end end @@ -89,8 +89,8 @@ def test_validates_presence_of_belongs_to_association__parent_is_new_record def test_validates_presence_of_belongs_to_association__existing_parent repair_validations(Interest) do Interest.validates_presence_of(:man) - man = Man.create!(:name => "John") - interest = man.interests.build(:topic => "Airplanes") + man = Man.create!(name: "John") + interest = man.interests.build(topic: "Airplanes") assert interest.valid?, "Expected interest to be valid, but was not. Interest should have a man object associated" end end diff --git a/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb b/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb index bc80aa16e6..d44b22b285 100644 --- a/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb +++ b/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb @@ -20,20 +20,20 @@ def reset_i18n_load_path # validates_associated: generate_message(attr_name, :invalid, :message => custom_message, :value => value) def test_generate_message_invalid_with_default_message - assert_equal "is invalid", @topic.errors.generate_message(:title, :invalid, :value => "title") + assert_equal "is invalid", @topic.errors.generate_message(:title, :invalid, value: "title") end def test_generate_message_invalid_with_custom_message - assert_equal "custom message title", @topic.errors.generate_message(:title, :invalid, :message => "custom message %{value}", :value => "title") + assert_equal "custom message title", @topic.errors.generate_message(:title, :invalid, message: "custom message %{value}", value: "title") end # validates_uniqueness_of: generate_message(attr_name, :taken, :message => custom_message) def test_generate_message_taken_with_default_message - assert_equal "has already been taken", @topic.errors.generate_message(:title, :taken, :value => "title") + assert_equal "has already been taken", @topic.errors.generate_message(:title, :taken, value: "title") end def test_generate_message_taken_with_custom_message - assert_equal "custom message title", @topic.errors.generate_message(:title, :taken, :message => "custom message %{value}", :value => "title") + assert_equal "custom message title", @topic.errors.generate_message(:title, :taken, message: "custom message %{value}", value: "title") end # ActiveRecord#RecordInvalid exception @@ -47,7 +47,7 @@ def test_generate_message_taken_with_custom_message test "RecordInvalid exception translation falls back to the :errors namespace" do reset_i18n_load_path do - I18n.backend.store_translations "en", :errors => {:messages => {:record_invalid => "fallback message"}} + I18n.backend.store_translations "en", errors: {messages: {record_invalid: "fallback message"}} topic = Topic.new topic.errors.add(:title, :blank) assert_equal "fallback message", ActiveRecord::RecordInvalid.new(topic).message @@ -57,28 +57,28 @@ def test_generate_message_taken_with_custom_message test "translation for 'taken' can be overridden" do reset_i18n_load_path do I18n.backend.store_translations "en", {errors: {attributes: {title: {taken: "Custom taken message" }}}} - assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => "title") + assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title") end end test "translation for 'taken' can be overridden in activerecord scope" do reset_i18n_load_path do I18n.backend.store_translations "en", {activerecord: {errors: {messages: {taken: "Custom taken message" }}}} - assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => "title") + assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title") end end test "translation for 'taken' can be overridden in activerecord model scope" do reset_i18n_load_path do I18n.backend.store_translations "en", {activerecord: {errors: {models: {topic: {taken: "Custom taken message" }}}}} - assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => "title") + assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title") end end test "translation for 'taken' can be overridden in activerecord attributes scope" do reset_i18n_load_path do I18n.backend.store_translations "en", {activerecord: {errors: {models: {topic: {attributes: {title: {taken: "Custom taken message" }}}}}}} - assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => "title") + assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title") end end end diff --git a/activerecord/test/cases/validations/i18n_validation_test.rb b/activerecord/test/cases/validations/i18n_validation_test.rb index 52a00c55e7..61289cd299 100644 --- a/activerecord/test/cases/validations/i18n_validation_test.rb +++ b/activerecord/test/cases/validations/i18n_validation_test.rb @@ -12,7 +12,7 @@ def setup @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend I18n.load_path.clear I18n.backend = I18n::Backend::Simple.new - I18n.backend.store_translations("en", :errors => {:messages => {:custom => nil}}) + I18n.backend.store_translations("en", errors: {messages: {custom: nil}}) end teardown do @@ -21,12 +21,12 @@ def setup end def unique_topic - @unique ||= Topic.create :title => "unique!" + @unique ||= Topic.create title: "unique!" end def replied_topic @replied_topic ||= begin - topic = Topic.create(:title => "topic") + topic = Topic.create(title: "topic") topic.replies << Reply.new topic end @@ -38,10 +38,10 @@ def replied_topic COMMON_CASES = [ # [ case, validation_options, generate_message_options] [ "given no options", {}, {}], - [ "given custom message", {:message => "custom"}, {:message => "custom"}], - [ "given if condition", {:if => lambda { true }}, {}], - [ "given unless condition", {:unless => lambda { false }}, {}], - [ "given option that is not reserved", {:format => "jpg"}, {:format => "jpg" }], + [ "given custom message", {message: "custom"}, {message: "custom"}], + [ "given if condition", {if: lambda { true }}, {}], + [ "given unless condition", {unless: lambda { false }}, {}], + [ "given option that is not reserved", {format: "jpg"}, {format: "jpg" }], [ "given on condition", {on: [:create, :update] }, {}] ] @@ -49,7 +49,7 @@ def replied_topic test "validates_uniqueness_of on generated message #{name}" do Topic.validates_uniqueness_of :title, validation_options @topic.title = unique_topic.title - assert_called_with(@topic.errors, :generate_message, [:title, :taken, generate_message_options.merge(:value => "unique!")]) do + assert_called_with(@topic.errors, :generate_message, [:title, :taken, generate_message_options.merge(value: "unique!")]) do @topic.valid? end end @@ -58,15 +58,15 @@ def replied_topic COMMON_CASES.each do |name, validation_options, generate_message_options| test "validates_associated on generated message #{name}" do Topic.validates_associated :replies, validation_options - assert_called_with(replied_topic.errors, :generate_message, [:replies, :invalid, generate_message_options.merge(:value => replied_topic.replies)]) do + assert_called_with(replied_topic.errors, :generate_message, [:replies, :invalid, generate_message_options.merge(value: replied_topic.replies)]) do replied_topic.save end end end def test_validates_associated_finds_custom_model_key_translation - I18n.backend.store_translations "en", :activerecord => {:errors => {:models => {:topic => {:attributes => {:replies => {:invalid => "custom message"}}}}}} - I18n.backend.store_translations "en", :activerecord => {:errors => {:messages => {:invalid => "global message"}}} + I18n.backend.store_translations "en", activerecord: {errors: {models: {topic: {attributes: {replies: {invalid: "custom message"}}}}}} + I18n.backend.store_translations "en", activerecord: {errors: {messages: {invalid: "global message"}}} Topic.validates_associated :replies replied_topic.valid? @@ -74,7 +74,7 @@ def test_validates_associated_finds_custom_model_key_translation end def test_validates_associated_finds_global_default_translation - I18n.backend.store_translations "en", :activerecord => {:errors => {:messages => {:invalid => "global message"}}} + I18n.backend.store_translations "en", activerecord: {errors: {messages: {invalid: "global message"}}} Topic.validates_associated :replies replied_topic.valid? diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb index 7abe9b6d36..44b4e28777 100644 --- a/activerecord/test/cases/validations/uniqueness_validation_test.rb +++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb @@ -26,7 +26,7 @@ class Thaumaturgist < IneptWizard class ReplyTitle; end class ReplyWithTitleObject < Reply - validates_uniqueness_of :content, :scope => :title + validates_uniqueness_of :content, scope: :title def title; ReplyTitle.new; end end @@ -57,7 +57,7 @@ class TopicWithAfterCreate < Topic after_create :set_author def set_author - update_attributes!(:author_name => "#{title} #{id}") + update_attributes!(author_name: "#{title} #{id}") end end @@ -107,7 +107,7 @@ def test_validates_uniqueness_with_nil_value end def test_validates_uniqueness_with_validates - Topic.validates :title, :uniqueness => true + Topic.validates :title, uniqueness: true Topic.create!("title" => "abc") t2 = Topic.new("title" => "abc") @@ -126,14 +126,14 @@ def test_validate_uniqueness_when_integer_out_of_range_show_order_does_not_matte end def test_validates_uniqueness_with_newline_chars - Topic.validates_uniqueness_of(:title, :case_sensitive => false) + Topic.validates_uniqueness_of(:title, case_sensitive: false) t = Topic.new("title" => "new\nline") assert t.save, "Should save t as unique" end def test_validate_uniqueness_with_scope - Reply.validates_uniqueness_of(:content, :scope => "parent_id") + Reply.validates_uniqueness_of(:content, scope: "parent_id") t = Topic.create("title" => "I'm unique!") @@ -152,7 +152,7 @@ def test_validate_uniqueness_with_scope end def test_validate_uniqueness_with_object_scope - Reply.validates_uniqueness_of(:content, :scope => :topic) + Reply.validates_uniqueness_of(:content, scope: :topic) t = Topic.create("title" => "I'm unique!") @@ -199,7 +199,7 @@ def test_validate_uniqueness_scoped_to_defining_class end def test_validate_uniqueness_with_scope_array - Reply.validates_uniqueness_of(:author_name, :scope => [:author_email_address, :parent_id]) + Reply.validates_uniqueness_of(:author_name, scope: [:author_email_address, :parent_id]) t = Topic.create("title" => "The earth is actually flat!") @@ -223,7 +223,7 @@ def test_validate_uniqueness_with_scope_array end def test_validate_case_insensitive_uniqueness - Topic.validates_uniqueness_of(:title, :parent_id, :case_sensitive => false, :allow_nil => true) + Topic.validates_uniqueness_of(:title, :parent_id, case_sensitive: false, allow_nil: true) t = Topic.new("title" => "I'm unique!", :parent_id => 2) assert t.save, "Should save t as unique" @@ -256,7 +256,7 @@ def test_validate_case_insensitive_uniqueness assert t_utf8.save, "Should save t_utf8 as unique" # If database hasn't UTF-8 character set, this test fails - if Topic.all.merge!(:select => "LOWER(title) AS title").find(t_utf8.id).title == "Ñ Ñ‚Ð¾Ð¶Ðµ уникальный!" + if Topic.all.merge!(select: "LOWER(title) AS title").find(t_utf8.id).title == "Ñ Ñ‚Ð¾Ð¶Ðµ уникальный!" t2_utf8 = Topic.new("title" => "Ñ Ñ‚Ð¾Ð¶Ðµ УÐИКÐЛЬÐЫЙ!") assert !t2_utf8.valid?, "Shouldn't be valid" assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique" @@ -264,7 +264,7 @@ def test_validate_case_insensitive_uniqueness end def test_validate_case_sensitive_uniqueness_with_special_sql_like_chars - Topic.validates_uniqueness_of(:title, :case_sensitive => true) + Topic.validates_uniqueness_of(:title, case_sensitive: true) t = Topic.new("title" => "I'm unique!") assert t.save, "Should save t as unique" @@ -277,7 +277,7 @@ def test_validate_case_sensitive_uniqueness_with_special_sql_like_chars end def test_validate_case_insensitive_uniqueness_with_special_sql_like_chars - Topic.validates_uniqueness_of(:title, :case_sensitive => false) + Topic.validates_uniqueness_of(:title, case_sensitive: false) t = Topic.new("title" => "I'm unique!") assert t.save, "Should save t as unique" @@ -290,7 +290,7 @@ def test_validate_case_insensitive_uniqueness_with_special_sql_like_chars end def test_validate_case_sensitive_uniqueness - Topic.validates_uniqueness_of(:title, :case_sensitive => true, :allow_nil => true) + Topic.validates_uniqueness_of(:title, case_sensitive: true, allow_nil: true) t = Topic.new("title" => "I'm unique!") assert t.save, "Should save t as unique" @@ -314,7 +314,7 @@ def test_validate_case_sensitive_uniqueness end def test_validate_case_sensitive_uniqueness_with_attribute_passed_as_integer - Topic.validates_uniqueness_of(:title, :case_sensitive => true) + Topic.validates_uniqueness_of(:title, case_sensitive: true) Topic.create!("title" => 101) t2 = Topic.new("title" => 101) @@ -323,7 +323,7 @@ def test_validate_case_sensitive_uniqueness_with_attribute_passed_as_integer end def test_validate_uniqueness_with_non_standard_table_names - i1 = WarehouseThing.create(:value => 1000) + i1 = WarehouseThing.create(value: 1000) assert !i1.valid?, "i1 should not be valid" assert i1.errors[:value].any?, "Should not be empty" end @@ -331,7 +331,7 @@ def test_validate_uniqueness_with_non_standard_table_names def test_validates_uniqueness_inside_scoping Topic.validates_uniqueness_of(:title) - Topic.where(:author_name => "David").scoping do + Topic.where(author_name: "David").scoping do t1 = Topic.new("title" => "I'm unique!", "author_name" => "Mary") assert t1.save t2 = Topic.new("title" => "I'm unique!", "author_name" => "David") @@ -387,29 +387,29 @@ def test_validate_uniqueness_with_limit_and_utf8 end def test_validate_straight_inheritance_uniqueness - w1 = IneptWizard.create(:name => "Rincewind", :city => "Ankh-Morpork") + w1 = IneptWizard.create(name: "Rincewind", city: "Ankh-Morpork") assert w1.valid?, "Saving w1" # Should use validation from base class (which is abstract) - w2 = IneptWizard.new(:name => "Rincewind", :city => "Quirm") + w2 = IneptWizard.new(name: "Rincewind", city: "Quirm") assert !w2.valid?, "w2 shouldn't be valid" assert w2.errors[:name].any?, "Should have errors for name" assert_equal ["has already been taken"], w2.errors[:name], "Should have uniqueness message for name" - w3 = Conjurer.new(:name => "Rincewind", :city => "Quirm") + w3 = Conjurer.new(name: "Rincewind", city: "Quirm") assert !w3.valid?, "w3 shouldn't be valid" assert w3.errors[:name].any?, "Should have errors for name" assert_equal ["has already been taken"], w3.errors[:name], "Should have uniqueness message for name" - w4 = Conjurer.create(:name => "The Amazing Bonko", :city => "Quirm") + w4 = Conjurer.create(name: "The Amazing Bonko", city: "Quirm") assert w4.valid?, "Saving w4" - w5 = Thaumaturgist.new(:name => "The Amazing Bonko", :city => "Lancre") + w5 = Thaumaturgist.new(name: "The Amazing Bonko", city: "Lancre") assert !w5.valid?, "w5 shouldn't be valid" assert w5.errors[:name].any?, "Should have errors for name" assert_equal ["has already been taken"], w5.errors[:name], "Should have uniqueness message for name" - w6 = Thaumaturgist.new(:name => "Mustrum Ridcully", :city => "Quirm") + w6 = Thaumaturgist.new(name: "Mustrum Ridcully", city: "Quirm") assert !w6.valid?, "w6 shouldn't be valid" assert w6.errors[:city].any?, "Should have errors for city" assert_equal ["has already been taken"], w6.errors[:city], "Should have uniqueness message for city" @@ -501,10 +501,10 @@ def test_validate_uniqueness_ignores_itself_when_primary_key_changed def test_validate_uniqueness_with_after_create_performing_save TopicWithAfterCreate.validates_uniqueness_of(:title) - topic = TopicWithAfterCreate.create!(:title => "Title1") + topic = TopicWithAfterCreate.create!(title: "Title1") assert topic.author_name.start_with?("Title1") - topic2 = TopicWithAfterCreate.new(:title => "Title1") + topic2 = TopicWithAfterCreate.new(title: "Title1") refute topic2.valid? assert_equal(["has already been taken"], topic2.errors[:title]) end diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index 95652955c2..e019c9a3e1 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -36,7 +36,7 @@ def test_valid_uses_update_context_when_persisted end def test_valid_using_special_context - r = WrongReply.new(:title => "Valid title") + r = WrongReply.new(title: "Valid title") assert !r.valid?(:special_case) assert_equal "Invalid", r.errors[:author_name].join @@ -53,7 +53,7 @@ def test_valid_using_special_context end def test_invalid_using_multiple_contexts - r = WrongReply.new(:title => "Wrong Create") + r = WrongReply.new(title: "Wrong Create") assert r.invalid?([:special_case, :create]) assert_equal "Invalid", r.errors[:author_name].join assert_equal "is Wrong Create", r.errors[:title].join @@ -95,7 +95,7 @@ def test_validate_with_bang_and_context assert_raise(ActiveRecord::RecordInvalid) do WrongReply.new.validate!(:special_case) end - r = WrongReply.new(:title => "Valid title", :author_name => "secret", :content => "Good") + r = WrongReply.new(title: "Valid title", author_name: "secret", content: "Good") assert r.validate!(:special_case) end @@ -124,7 +124,7 @@ def test_exception_on_create_bang_many_with_block def test_save_without_validation reply = WrongReply.new assert !reply.save - assert reply.save(:validate => false) + assert reply.save(validate: false) end def test_validates_acceptance_of_with_non_existent_table diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index ac1dc4a453..6556771a9d 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -9,7 +9,7 @@ class YamlSerializationTest < ActiveRecord::TestCase def test_to_yaml_with_time_with_zone_should_not_raise_exception with_timezone_config aware_attributes: true, zone: "Pacific Time (US & Canada)" do - topic = Topic.new(:written_on => DateTime.now) + topic = Topic.new(written_on: DateTime.now) assert_nothing_raised { topic.to_yaml } end end @@ -22,8 +22,8 @@ def test_roundtrip end def test_roundtrip_serialized_column - topic = Topic.new(:content => {:omg=>:lol}) - assert_equal({:omg=>:lol}, YAML.load(YAML.dump(topic)).content) + topic = Topic.new(content: {omg: :lol}) + assert_equal({omg: :lol}, YAML.load(YAML.dump(topic)).content) end def test_psych_roundtrip diff --git a/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb b/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb index 549647de86..43c79bc20b 100644 --- a/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb +++ b/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb @@ -1,10 +1,10 @@ class GiveMeBigNumbers < ActiveRecord::Migration::Current def self.up create_table :big_numbers do |table| - table.column :bank_balance, :decimal, :precision => 10, :scale => 2 - table.column :big_bank_balance, :decimal, :precision => 15, :scale => 2 - table.column :world_population, :decimal, :precision => 10 - table.column :my_house_population, :decimal, :precision => 2 + table.column :bank_balance, :decimal, precision: 10, scale: 2 + table.column :big_bank_balance, :decimal, precision: 15, scale: 2 + table.column :world_population, :decimal, precision: 10 + table.column :my_house_population, :decimal, precision: 2 table.column :value_of_e, :decimal end end diff --git a/activerecord/test/migrations/magic/1_currencies_have_symbols.rb b/activerecord/test/migrations/magic/1_currencies_have_symbols.rb index 53b263bf55..d4b0e6cd95 100644 --- a/activerecord/test/migrations/magic/1_currencies_have_symbols.rb +++ b/activerecord/test/migrations/magic/1_currencies_have_symbols.rb @@ -2,8 +2,8 @@ class CurrenciesHaveSymbols < ActiveRecord::Migration::Current def self.up - # We use ¤ for default currency symbol - add_column "currencies", "symbol", :string, :default => "¤" + # We use € for default currency symbol + add_column "currencies", "symbol", :string, default: "€" end def self.down diff --git a/activerecord/test/migrations/missing/4_innocent_jointable.rb b/activerecord/test/migrations/missing/4_innocent_jointable.rb index 20fe183777..bd3bf21576 100644 --- a/activerecord/test/migrations/missing/4_innocent_jointable.rb +++ b/activerecord/test/migrations/missing/4_innocent_jointable.rb @@ -1,6 +1,6 @@ class InnocentJointable < ActiveRecord::Migration::Current def self.up - create_table("people_reminders", :id => false) do |t| + create_table("people_reminders", id: false) do |t| t.column :reminder_id, :integer t.column :person_id, :integer end diff --git a/activerecord/test/migrations/valid/3_innocent_jointable.rb b/activerecord/test/migrations/valid/3_innocent_jointable.rb index 20fe183777..bd3bf21576 100644 --- a/activerecord/test/migrations/valid/3_innocent_jointable.rb +++ b/activerecord/test/migrations/valid/3_innocent_jointable.rb @@ -1,6 +1,6 @@ class InnocentJointable < ActiveRecord::Migration::Current def self.up - create_table("people_reminders", :id => false) do |t| + create_table("people_reminders", id: false) do |t| t.column :reminder_id, :integer t.column :person_id, :integer end diff --git a/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb index 20fe183777..bd3bf21576 100644 --- a/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb +++ b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb @@ -1,6 +1,6 @@ class InnocentJointable < ActiveRecord::Migration::Current def self.up - create_table("people_reminders", :id => false) do |t| + create_table("people_reminders", id: false) do |t| t.column :reminder_id, :integer t.column :person_id, :integer end diff --git a/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb b/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb index bf934576c9..be24de6d70 100644 --- a/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb +++ b/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb @@ -1,6 +1,6 @@ class ValidWithTimestampsInnocentJointable < ActiveRecord::Migration::Current def self.up - create_table("people_reminders", :id => false) do |t| + create_table("people_reminders", id: false) do |t| t.column :reminder_id, :integer t.column :person_id, :integer end diff --git a/activerecord/test/models/admin/user.rb b/activerecord/test/models/admin/user.rb index 3cd829a8d5..2e703f6219 100644 --- a/activerecord/test/models/admin/user.rb +++ b/activerecord/test/models/admin/user.rb @@ -15,11 +15,11 @@ def load(s) belongs_to :account store :params, accessors: [ :token ], coder: YAML - store :settings, :accessors => [ :color, :homepage ] + store :settings, accessors: [ :color, :homepage ] store_accessor :settings, :favorite_food - store :preferences, :accessors => [ :remember_login ] - store :json_data, :accessors => [ :height, :weight ], :coder => Coder.new - store :json_data_empty, :accessors => [ :is_a_good_guy ], :coder => Coder.new + store :preferences, accessors: [ :remember_login ] + store :json_data, accessors: [ :height, :weight ], coder: Coder.new + store :json_data_empty, accessors: [ :is_a_good_guy ], coder: Coder.new def phone_number read_store_attribute(:settings, :phone_number).gsub(/(\d{3})(\d{3})(\d{4})/,'(\1) \2-\3') diff --git a/activerecord/test/models/aircraft.rb b/activerecord/test/models/aircraft.rb index c4404a8094..ebd42ff824 100644 --- a/activerecord/test/models/aircraft.rb +++ b/activerecord/test/models/aircraft.rb @@ -1,5 +1,5 @@ class Aircraft < ActiveRecord::Base self.pluralize_table_names = false - has_many :engines, :foreign_key => "car_id" + has_many :engines, foreign_key: "car_id" has_many :wheels, as: :wheelable end diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index a9f3063736..8633504d54 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -2,33 +2,33 @@ class Author < ActiveRecord::Base has_many :posts has_many :serialized_posts has_one :post - has_many :very_special_comments, :through => :posts - has_many :posts_with_comments, -> { includes(:comments) }, :class_name => "Post" - has_many :popular_grouped_posts, -> { includes(:comments).group("type").having("SUM(comments_count) > 1").select("type") }, :class_name => "Post" - has_many :posts_with_comments_sorted_by_comment_id, -> { includes(:comments).order("comments.id") }, :class_name => "Post" - has_many :posts_sorted_by_id_limited, -> { order("posts.id").limit(1) }, :class_name => "Post" - has_many :posts_with_categories, -> { includes(:categories) }, :class_name => "Post" - has_many :posts_with_comments_and_categories, -> { includes(:comments, :categories).order("posts.id") }, :class_name => "Post" - has_many :posts_with_special_categorizations, :class_name => "PostWithSpecialCategorization" - has_one :post_about_thinking, -> { where("posts.title like '%thinking%'") }, :class_name => "Post" - has_one :post_about_thinking_with_last_comment, -> { where("posts.title like '%thinking%'").includes(:last_comment) }, :class_name => "Post" + has_many :very_special_comments, through: :posts + has_many :posts_with_comments, -> { includes(:comments) }, class_name: "Post" + has_many :popular_grouped_posts, -> { includes(:comments).group("type").having("SUM(comments_count) > 1").select("type") }, class_name: "Post" + has_many :posts_with_comments_sorted_by_comment_id, -> { includes(:comments).order("comments.id") }, class_name: "Post" + has_many :posts_sorted_by_id_limited, -> { order("posts.id").limit(1) }, class_name: "Post" + has_many :posts_with_categories, -> { includes(:categories) }, class_name: "Post" + has_many :posts_with_comments_and_categories, -> { includes(:comments, :categories).order("posts.id") }, class_name: "Post" + has_many :posts_with_special_categorizations, class_name: "PostWithSpecialCategorization" + has_one :post_about_thinking, -> { where("posts.title like '%thinking%'") }, class_name: "Post" + has_one :post_about_thinking_with_last_comment, -> { where("posts.title like '%thinking%'").includes(:last_comment) }, class_name: "Post" has_many :comments, through: :posts do def ratings Rating.joins(:comment).merge(self) end end - has_many :comments_containing_the_letter_e, :through => :posts, :source => :comments - has_many :comments_with_order_and_conditions, -> { order("comments.body").where("comments.body like 'Thank%'") }, :through => :posts, :source => :comments - has_many :comments_with_include, -> { includes(:post) }, :through => :posts, :source => :comments + has_many :comments_containing_the_letter_e, through: :posts, source: :comments + has_many :comments_with_order_and_conditions, -> { order("comments.body").where("comments.body like 'Thank%'") }, through: :posts, source: :comments + has_many :comments_with_include, -> { includes(:post) }, through: :posts, source: :comments has_many :first_posts - has_many :comments_on_first_posts, -> { order("posts.id desc, comments.id asc") }, :through => :first_posts, :source => :comments + has_many :comments_on_first_posts, -> { order("posts.id desc, comments.id asc") }, through: :first_posts, source: :comments has_one :first_post - has_one :comment_on_first_post, -> { order("posts.id desc, comments.id asc") }, :through => :first_post, :source => :comments + has_one :comment_on_first_post, -> { order("posts.id desc, comments.id asc") }, through: :first_post, source: :comments - has_many :thinking_posts, -> { where(:title => "So I was thinking") }, :dependent => :delete_all, :class_name => "Post" - has_many :welcome_posts, -> { where(:title => "Welcome to the weblog") }, :class_name => "Post" + has_many :thinking_posts, -> { where(title: "So I was thinking") }, dependent: :delete_all, class_name: "Post" + has_many :welcome_posts, -> { where(title: "Welcome to the weblog") }, class_name: "Post" has_many :welcome_posts_with_one_comment, -> { where(title: "Welcome to the weblog").where("comments_count = ?", 1) }, @@ -37,110 +37,109 @@ def ratings -> { where(title: "Welcome to the weblog").where(Post.arel_table[:comments_count].gt(0)) }, class_name: "Post" - has_many :comments_desc, -> { order("comments.id DESC") }, :through => :posts, :source => :comments - has_many :funky_comments, :through => :posts, :source => :comments - has_many :ordered_uniq_comments, -> { distinct.order("comments.id") }, :through => :posts, :source => :comments - has_many :ordered_uniq_comments_desc, -> { distinct.order("comments.id DESC") }, :through => :posts, :source => :comments - has_many :readonly_comments, -> { readonly }, :through => :posts, :source => :comments + has_many :comments_desc, -> { order("comments.id DESC") }, through: :posts, source: :comments + has_many :funky_comments, through: :posts, source: :comments + has_many :ordered_uniq_comments, -> { distinct.order("comments.id") }, through: :posts, source: :comments + has_many :ordered_uniq_comments_desc, -> { distinct.order("comments.id DESC") }, through: :posts, source: :comments + has_many :readonly_comments, -> { readonly }, through: :posts, source: :comments has_many :special_posts - has_many :special_post_comments, :through => :special_posts, :source => :comments - has_many :special_posts_with_default_scope, :class_name => "SpecialPostWithDefaultScope" + has_many :special_post_comments, through: :special_posts, source: :comments + has_many :special_posts_with_default_scope, class_name: "SpecialPostWithDefaultScope" - has_many :sti_posts, :class_name => "StiPost" - has_many :sti_post_comments, :through => :sti_posts, :source => :comments + has_many :sti_posts, class_name: "StiPost" + has_many :sti_post_comments, through: :sti_posts, source: :comments - has_many :special_nonexistent_posts, -> { where("posts.body = 'nonexistent'") }, :class_name => "SpecialPost" - has_many :special_nonexistent_post_comments, -> { where("comments.post_id" => 0) }, :through => :special_nonexistent_posts, :source => :comments - has_many :nonexistent_comments, :through => :posts + has_many :special_nonexistent_posts, -> { where("posts.body = 'nonexistent'") }, class_name: "SpecialPost" + has_many :special_nonexistent_post_comments, -> { where("comments.post_id" => 0) }, through: :special_nonexistent_posts, source: :comments + has_many :nonexistent_comments, through: :posts - has_many :hello_posts, -> { where "posts.body = 'hello'" }, :class_name => "Post" - has_many :hello_post_comments, :through => :hello_posts, :source => :comments - has_many :posts_with_no_comments, -> { where("comments.id" => nil).includes(:comments) }, :class_name => "Post" + has_many :hello_posts, -> { where "posts.body = 'hello'" }, class_name: "Post" + has_many :hello_post_comments, through: :hello_posts, source: :comments + has_many :posts_with_no_comments, -> { where("comments.id" => nil).includes(:comments) }, class_name: "Post" - has_many :hello_posts_with_hash_conditions, -> { where(:body => "hello") }, :class_name => "Post" - has_many :hello_post_comments_with_hash_conditions, :through => -:hello_posts_with_hash_conditions, :source => :comments + has_many :hello_posts_with_hash_conditions, -> { where(body: "hello") }, class_name: "Post" + has_many :hello_post_comments_with_hash_conditions, through: :hello_posts_with_hash_conditions, source: :comments - has_many :other_posts, :class_name => "Post" - has_many :posts_with_callbacks, :class_name => "Post", :before_add => :log_before_adding, - :after_add => :log_after_adding, - :before_remove => :log_before_removing, - :after_remove => :log_after_removing - has_many :posts_with_proc_callbacks, :class_name => "Post", - :before_add => Proc.new {|o, r| o.post_log << "before_adding#{r.id || ''}"}, - :after_add => Proc.new {|o, r| o.post_log << "after_adding#{r.id || ''}"}, - :before_remove => Proc.new {|o, r| o.post_log << "before_removing#{r.id}"}, - :after_remove => Proc.new {|o, r| o.post_log << "after_removing#{r.id}"} - has_many :posts_with_multiple_callbacks, :class_name => "Post", - :before_add => [:log_before_adding, Proc.new {|o, r| o.post_log << "before_adding_proc#{r.id || ''}"}], - :after_add => [:log_after_adding, Proc.new {|o, r| o.post_log << "after_adding_proc#{r.id || ''}"}] - has_many :unchangeable_posts, :class_name => "Post", :before_add => :raise_exception, :after_add => :log_after_adding + has_many :other_posts, class_name: "Post" + has_many :posts_with_callbacks, class_name: "Post", before_add: :log_before_adding, + after_add: :log_after_adding, + before_remove: :log_before_removing, + after_remove: :log_after_removing + has_many :posts_with_proc_callbacks, class_name: "Post", + before_add: Proc.new {|o, r| o.post_log << "before_adding#{r.id || ''}"}, + after_add: Proc.new {|o, r| o.post_log << "after_adding#{r.id || ''}"}, + before_remove: Proc.new {|o, r| o.post_log << "before_removing#{r.id}"}, + after_remove: Proc.new {|o, r| o.post_log << "after_removing#{r.id}"} + has_many :posts_with_multiple_callbacks, class_name: "Post", + before_add: [:log_before_adding, Proc.new {|o, r| o.post_log << "before_adding_proc#{r.id || ''}"}], + after_add: [:log_after_adding, Proc.new {|o, r| o.post_log << "after_adding_proc#{r.id || ''}"}] + has_many :unchangeable_posts, class_name: "Post", before_add: :raise_exception, after_add: :log_after_adding has_many :categorizations - has_many :categories, :through => :categorizations - has_many :named_categories, :through => :categorizations + has_many :categories, through: :categorizations + has_many :named_categories, through: :categorizations has_many :special_categorizations - has_many :special_categories, :through => :special_categorizations, :source => :category - has_one :special_category, :through => :special_categorizations, :source => :category + has_many :special_categories, through: :special_categorizations, source: :category + has_one :special_category, through: :special_categorizations, source: :category - has_many :categories_like_general, -> { where(:name => "General") }, :through => :categorizations, :source => :category, :class_name => "Category" + has_many :categories_like_general, -> { where(name: "General") }, through: :categorizations, source: :category, class_name: "Category" - has_many :categorized_posts, :through => :categorizations, :source => :post - has_many :unique_categorized_posts, -> { distinct }, :through => :categorizations, :source => :post + has_many :categorized_posts, through: :categorizations, source: :post + has_many :unique_categorized_posts, -> { distinct }, through: :categorizations, source: :post - has_many :nothings, :through => :kateggorisatons, :class_name => "Category" + has_many :nothings, through: :kateggorisatons, class_name: "Category" has_many :author_favorites - has_many :favorite_authors, -> { order("name") }, :through => :author_favorites + has_many :favorite_authors, -> { order("name") }, through: :author_favorites - has_many :taggings, :through => :posts, :source => :taggings - has_many :taggings_2, :through => :posts, :source => :tagging - has_many :tags, :through => :posts - has_many :post_categories, :through => :posts, :source => :categories - has_many :tagging_tags, :through => :taggings, :source => :tag + has_many :taggings, through: :posts, source: :taggings + has_many :taggings_2, through: :posts, source: :tagging + has_many :tags, through: :posts + has_many :post_categories, through: :posts, source: :categories + has_many :tagging_tags, through: :taggings, source: :tag - has_many :similar_posts, -> { distinct }, :through => :tags, :source => :tagged_posts - has_many :distinct_tags, -> { select("DISTINCT tags.*").order("tags.name") }, :through => :posts, :source => :tags + has_many :similar_posts, -> { distinct }, through: :tags, source: :tagged_posts + has_many :distinct_tags, -> { select("DISTINCT tags.*").order("tags.name") }, through: :posts, source: :tags - has_many :tags_with_primary_key, :through => :posts + has_many :tags_with_primary_key, through: :posts has_many :books - has_many :subscriptions, :through => :books - has_many :subscribers, -> { order("subscribers.nick") }, :through => :subscriptions - has_many :distinct_subscribers, -> { select("DISTINCT subscribers.*").order("subscribers.nick") }, :through => :subscriptions, :source => :subscriber + has_many :subscriptions, through: :books + has_many :subscribers, -> { order("subscribers.nick") }, through: :subscriptions + has_many :distinct_subscribers, -> { select("DISTINCT subscribers.*").order("subscribers.nick") }, through: :subscriptions, source: :subscriber - has_one :essay, :primary_key => :name, :as => :writer - has_one :essay_category, :through => :essay, :source => :category - has_one :essay_owner, :through => :essay, :source => :owner + has_one :essay, primary_key: :name, as: :writer + has_one :essay_category, through: :essay, source: :category + has_one :essay_owner, through: :essay, source: :owner - has_one :essay_2, :primary_key => :name, :class_name => "Essay", :foreign_key => :author_id - has_one :essay_category_2, :through => :essay_2, :source => :category + has_one :essay_2, primary_key: :name, class_name: "Essay", foreign_key: :author_id + has_one :essay_category_2, through: :essay_2, source: :category - has_many :essays, :primary_key => :name, :as => :writer - has_many :essay_categories, :through => :essays, :source => :category - has_many :essay_owners, :through => :essays, :source => :owner + has_many :essays, primary_key: :name, as: :writer + has_many :essay_categories, through: :essays, source: :category + has_many :essay_owners, through: :essays, source: :owner - has_many :essays_2, :primary_key => :name, :class_name => "Essay", :foreign_key => :author_id - has_many :essay_categories_2, :through => :essays_2, :source => :category + has_many :essays_2, primary_key: :name, class_name: "Essay", foreign_key: :author_id + has_many :essay_categories_2, through: :essays_2, source: :category - belongs_to :owned_essay, :primary_key => :name, :class_name => "Essay" - has_one :owned_essay_category, :through => :owned_essay, :source => :category + belongs_to :owned_essay, primary_key: :name, class_name: "Essay" + has_one :owned_essay_category, through: :owned_essay, source: :category - belongs_to :author_address, :dependent => :destroy - belongs_to :author_address_extra, :dependent => :delete, :class_name => "AuthorAddress" + belongs_to :author_address, dependent: :destroy + belongs_to :author_address_extra, dependent: :delete, class_name: "AuthorAddress" - has_many :category_post_comments, :through => :categories, :source => :post_comments + has_many :category_post_comments, through: :categories, source: :post_comments - has_many :misc_posts, -> { where(:posts => { :title => ["misc post by bob", "misc post by mary"] }) }, :class_name => "Post" - has_many :misc_post_first_blue_tags, :through => :misc_posts, :source => :first_blue_tags + has_many :misc_posts, -> { where(posts: { title: ["misc post by bob", "misc post by mary"] }) }, class_name: "Post" + has_many :misc_post_first_blue_tags, through: :misc_posts, source: :first_blue_tags - has_many :misc_post_first_blue_tags_2, -> { where(:posts => { :title => ["misc post by bob", "misc post by mary"] }) }, - :through => :posts, :source => :first_blue_tags_2 + has_many :misc_post_first_blue_tags_2, -> { where(posts: { title: ["misc post by bob", "misc post by mary"] }) }, + through: :posts, source: :first_blue_tags_2 - has_many :posts_with_default_include, :class_name => "PostWithDefaultInclude" - has_many :comments_on_posts_with_default_include, :through => :posts_with_default_include, :source => :comments + has_many :posts_with_default_include, class_name: "PostWithDefaultInclude" + has_many :comments_on_posts_with_default_include, through: :posts_with_default_include, source: :comments has_many :posts_with_signature, ->(record) { where("posts.title LIKE ?", "%by #{record.name.downcase}%") }, class_name: "Post" @@ -205,5 +204,5 @@ def self.destroyed_author_address_ids class AuthorFavorite < ActiveRecord::Base belongs_to :author - belongs_to :favorite_author, :class_name => "Author" + belongs_to :favorite_author, class_name: "Author" end diff --git a/activerecord/test/models/bird.rb b/activerecord/test/models/bird.rb index 2a51d903b8..24b839135d 100644 --- a/activerecord/test/models/bird.rb +++ b/activerecord/test/models/bird.rb @@ -5,7 +5,7 @@ class Bird < ActiveRecord::Base accepts_nested_attributes_for :pirate attr_accessor :cancel_save_from_callback - before_save :cancel_save_callback_method, :if => :cancel_save_from_callback + before_save :cancel_save_callback_method, if: :cancel_save_from_callback def cancel_save_callback_method throw(:abort) end diff --git a/activerecord/test/models/book.rb b/activerecord/test/models/book.rb index 5db4f64b74..edd0281127 100644 --- a/activerecord/test/models/book.rb +++ b/activerecord/test/models/book.rb @@ -1,7 +1,7 @@ class Book < ActiveRecord::Base has_many :authors - has_many :citations, :foreign_key => "book1_id" + has_many :citations, foreign_key: "book1_id" has_many :references, -> { distinct }, through: :citations, source: :reference_of has_many :subscriptions diff --git a/activerecord/test/models/bulb.rb b/activerecord/test/models/bulb.rb index 88baa60035..3196207ac9 100644 --- a/activerecord/test/models/bulb.rb +++ b/activerecord/test/models/bulb.rb @@ -1,6 +1,6 @@ class Bulb < ActiveRecord::Base - default_scope { where(:name => "defaulty") } - belongs_to :car, :touch => true + default_scope { where(name: "defaulty") } + belongs_to :car, touch: true scope :awesome, -> { where(frickinawesome: true) } attr_reader :scope_after_initialize, :attributes_after_initialize diff --git a/activerecord/test/models/car.rb b/activerecord/test/models/car.rb index 9f129689ef..92bff7ff96 100644 --- a/activerecord/test/models/car.rb +++ b/activerecord/test/models/car.rb @@ -3,16 +3,16 @@ class Car < ActiveRecord::Base has_many :all_bulbs, -> { unscope where: :name }, class_name: "Bulb" has_many :funky_bulbs, class_name: "FunkyBulb", dependent: :destroy has_many :failed_bulbs, class_name: "FailedBulb", dependent: :destroy - has_many :foo_bulbs, -> { where(:name => "foo") }, :class_name => "Bulb" + has_many :foo_bulbs, -> { where(name: "foo") }, class_name: "Bulb" has_many :awesome_bulbs, -> { awesome }, class_name: "Bulb" has_one :bulb has_many :tyres - has_many :engines, :dependent => :destroy, inverse_of: :my_car - has_many :wheels, :as => :wheelable, :dependent => :destroy + has_many :engines, dependent: :destroy, inverse_of: :my_car + has_many :wheels, as: :wheelable, dependent: :destroy - has_many :price_estimates, :as => :estimate_of + has_many :price_estimates, as: :estimate_of scope :incl_tyres, -> { includes(:tyres) } scope :incl_engines, -> { includes(:engines) } diff --git a/activerecord/test/models/categorization.rb b/activerecord/test/models/categorization.rb index 178aff0541..b99383d0b1 100644 --- a/activerecord/test/models/categorization.rb +++ b/activerecord/test/models/categorization.rb @@ -1,18 +1,18 @@ class Categorization < ActiveRecord::Base belongs_to :post belongs_to :category, counter_cache: true - belongs_to :named_category, :class_name => "Category", :foreign_key => :named_category_name, :primary_key => :name + belongs_to :named_category, class_name: "Category", foreign_key: :named_category_name, primary_key: :name belongs_to :author - has_many :post_taggings, :through => :author, :source => :taggings + has_many :post_taggings, through: :author, source: :taggings - belongs_to :author_using_custom_pk, :class_name => "Author", :foreign_key => :author_id, :primary_key => :author_address_extra_id - has_many :authors_using_custom_pk, :class_name => "Author", :foreign_key => :id, :primary_key => :category_id + belongs_to :author_using_custom_pk, class_name: "Author", foreign_key: :author_id, primary_key: :author_address_extra_id + has_many :authors_using_custom_pk, class_name: "Author", foreign_key: :id, primary_key: :category_id end class SpecialCategorization < ActiveRecord::Base self.table_name = "categorizations" - default_scope { where(:special => true) } + default_scope { where(special: true) } belongs_to :author belongs_to :category diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb index 0c6794ff65..e8654dca01 100644 --- a/activerecord/test/models/category.rb +++ b/activerecord/test/models/category.rb @@ -1,21 +1,21 @@ class Category < ActiveRecord::Base has_and_belongs_to_many :posts - has_and_belongs_to_many :special_posts, :class_name => "Post" - has_and_belongs_to_many :other_posts, :class_name => "Post" - has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, -> { includes(:authors).order("authors.id") }, :class_name => "Post" + has_and_belongs_to_many :special_posts, class_name: "Post" + has_and_belongs_to_many :other_posts, class_name: "Post" + has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, -> { includes(:authors).order("authors.id") }, class_name: "Post" has_and_belongs_to_many :select_testing_posts, -> { select "posts.*, 1 as correctness_marker" }, - :class_name => "Post", - :foreign_key => "category_id", - :association_foreign_key => "post_id" + class_name: "Post", + foreign_key: "category_id", + association_foreign_key: "post_id" has_and_belongs_to_many :post_with_conditions, - -> { where :title => "Yet Another Testing Title" }, - :class_name => "Post" + -> { where title: "Yet Another Testing Title" }, + class_name: "Post" - has_and_belongs_to_many :popular_grouped_posts, -> { group("posts.type").having("sum(comments.post_id) > 2").includes(:comments) }, :class_name => "Post" - has_and_belongs_to_many :posts_grouped_by_title, -> { group("title").select("title") }, :class_name => "Post" + has_and_belongs_to_many :popular_grouped_posts, -> { group("posts.type").having("sum(comments.post_id) > 2").includes(:comments) }, class_name: "Post" + has_and_belongs_to_many :posts_grouped_by_title, -> { group("title").select("title") }, class_name: "Post" def self.what_are_you "a category..." @@ -23,12 +23,12 @@ def self.what_are_you has_many :categorizations has_many :special_categorizations - has_many :post_comments, :through => :posts, :source => :comments + has_many :post_comments, through: :posts, source: :comments - has_many :authors, :through => :categorizations - has_many :authors_with_select, -> { select "authors.*, categorizations.post_id" }, :through => :categorizations, :source => :author + has_many :authors, through: :categorizations + has_many :authors_with_select, -> { select "authors.*, categorizations.post_id" }, through: :categorizations, source: :author - scope :general, -> { where(:name => "General") } + scope :general, -> { where(name: "General") } end class SpecialCategory < Category diff --git a/activerecord/test/models/citation.rb b/activerecord/test/models/citation.rb index 3d87eb795c..7d06387f56 100644 --- a/activerecord/test/models/citation.rb +++ b/activerecord/test/models/citation.rb @@ -1,3 +1,3 @@ class Citation < ActiveRecord::Base - belongs_to :reference_of, :class_name => "Book", :foreign_key => :book2_id + belongs_to :reference_of, class_name: "Book", foreign_key: :book2_id end diff --git a/activerecord/test/models/club.rb b/activerecord/test/models/club.rb index e1b3e706f2..b2986a8c58 100644 --- a/activerecord/test/models/club.rb +++ b/activerecord/test/models/club.rb @@ -1,9 +1,9 @@ class Club < ActiveRecord::Base has_one :membership - has_many :memberships, :inverse_of => false - has_many :members, :through => :memberships + has_many :memberships, inverse_of: false + has_many :members, through: :memberships has_one :sponsor - has_one :sponsored_member, :through => :sponsor, :source => :sponsorable, :source_type => "Member" + has_one :sponsored_member, through: :sponsor, source: :sponsorable, source_type: "Member" belongs_to :category has_many :favourites, -> { where(memberships: { favourite: true }) }, through: :memberships, source: :member diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb index 45463b69f2..7315a1af8e 100644 --- a/activerecord/test/models/comment.rb +++ b/activerecord/test/models/comment.rb @@ -2,22 +2,22 @@ class Comment < ActiveRecord::Base scope :limit_by, lambda {|l| limit(l) } scope :containing_the_letter_e, -> { where("comments.body LIKE '%e%'") } scope :not_again, -> { where("comments.body NOT LIKE '%again%'") } - scope :for_first_post, -> { where(:post_id => 1) } + scope :for_first_post, -> { where(post_id: 1) } scope :for_first_author, -> { joins(:post).where("posts.author_id" => 1) } scope :created, -> { all } - belongs_to :post, :counter_cache => true + belongs_to :post, counter_cache: true belongs_to :author, polymorphic: true belongs_to :resource, polymorphic: true belongs_to :developer has_many :ratings - belongs_to :first_post, :foreign_key => :post_id + belongs_to :first_post, foreign_key: :post_id belongs_to :special_post_with_default_scope, foreign_key: :post_id - has_many :children, :class_name => "Comment", :foreign_key => :parent_id - belongs_to :parent, :class_name => "Comment", :counter_cache => :children_count + has_many :children, class_name: "Comment", foreign_key: :parent_id + belongs_to :parent, class_name: "Comment", counter_cache: :children_count def self.what_are_you "a comment..." diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index 6a01dae18d..921cf10f30 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -7,12 +7,12 @@ class Company < AbstractCompany validates_presence_of :name - has_one :dummy_account, :foreign_key => "firm_id", :class_name => "Account" + has_one :dummy_account, foreign_key: "firm_id", class_name: "Account" has_many :contracts - has_many :developers, :through => :contracts + has_many :developers, through: :contracts scope :of_first_firm, lambda { - joins(:account => :firm). + joins(account: :firm). where("firms.id" => 1) } @@ -35,7 +35,7 @@ class Company < ::Company end class Firm < ::Company - has_many :clients, :class_name => "Namespaced::Client" + has_many :clients, class_name: "Namespaced::Client" end class Client < ::Company @@ -45,45 +45,45 @@ class Client < ::Company class Firm < Company to_param :name - has_many :clients, -> { order "id" }, :dependent => :destroy, :before_remove => :log_before_remove, :after_remove => :log_after_remove - has_many :unsorted_clients, :class_name => "Client" - has_many :unsorted_clients_with_symbol, :class_name => :Client - has_many :clients_sorted_desc, -> { order "id DESC" }, :class_name => "Client" - has_many :clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :inverse_of => :firm - has_many :clients_ordered_by_name, -> { order "name" }, :class_name => "Client" - has_many :unvalidated_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :validate => false - has_many :dependent_clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :dependent => :destroy - has_many :exclusively_dependent_clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all - has_many :limited_clients, -> { limit 1 }, :class_name => "Client" - has_many :clients_with_interpolated_conditions, ->(firm) { where "rating > #{firm.rating}" }, :class_name => "Client" - has_many :clients_like_ms, -> { where("name = 'Microsoft'").order("id") }, :class_name => "Client" - has_many :clients_like_ms_with_hash_conditions, -> { where(:name => "Microsoft").order("id") }, :class_name => "Client" - has_many :plain_clients, :class_name => "Client" - has_many :clients_using_primary_key, :class_name => "Client", - :primary_key => "name", :foreign_key => "firm_name" - has_many :clients_using_primary_key_with_delete_all, :class_name => "Client", - :primary_key => "name", :foreign_key => "firm_name", :dependent => :delete_all - has_many :clients_grouped_by_firm_id, -> { group("firm_id").select("firm_id") }, :class_name => "Client" - has_many :clients_grouped_by_name, -> { group("name").select("name") }, :class_name => "Client" + has_many :clients, -> { order "id" }, dependent: :destroy, before_remove: :log_before_remove, after_remove: :log_after_remove + has_many :unsorted_clients, class_name: "Client" + has_many :unsorted_clients_with_symbol, class_name: :Client + has_many :clients_sorted_desc, -> { order "id DESC" }, class_name: "Client" + has_many :clients_of_firm, -> { order "id" }, foreign_key: "client_of", class_name: "Client", inverse_of: :firm + has_many :clients_ordered_by_name, -> { order "name" }, class_name: "Client" + has_many :unvalidated_clients_of_firm, foreign_key: "client_of", class_name: "Client", validate: false + has_many :dependent_clients_of_firm, -> { order "id" }, foreign_key: "client_of", class_name: "Client", dependent: :destroy + has_many :exclusively_dependent_clients_of_firm, -> { order "id" }, foreign_key: "client_of", class_name: "Client", dependent: :delete_all + has_many :limited_clients, -> { limit 1 }, class_name: "Client" + has_many :clients_with_interpolated_conditions, ->(firm) { where "rating > #{firm.rating}" }, class_name: "Client" + has_many :clients_like_ms, -> { where("name = 'Microsoft'").order("id") }, class_name: "Client" + has_many :clients_like_ms_with_hash_conditions, -> { where(name: "Microsoft").order("id") }, class_name: "Client" + has_many :plain_clients, class_name: "Client" + has_many :clients_using_primary_key, class_name: "Client", + primary_key: "name", foreign_key: "firm_name" + has_many :clients_using_primary_key_with_delete_all, class_name: "Client", + primary_key: "name", foreign_key: "firm_name", dependent: :delete_all + has_many :clients_grouped_by_firm_id, -> { group("firm_id").select("firm_id") }, class_name: "Client" + has_many :clients_grouped_by_name, -> { group("name").select("name") }, class_name: "Client" - has_one :account, :foreign_key => "firm_id", :dependent => :destroy, :validate => true - has_one :unvalidated_account, :foreign_key => "firm_id", :class_name => "Account", :validate => false - has_one :account_with_select, -> { select("id, firm_id") }, :foreign_key => "firm_id", :class_name=>"Account" - has_one :readonly_account, -> { readonly }, :foreign_key => "firm_id", :class_name => "Account" + has_one :account, foreign_key: "firm_id", dependent: :destroy, validate: true + has_one :unvalidated_account, foreign_key: "firm_id", class_name: "Account", validate: false + has_one :account_with_select, -> { select("id, firm_id") }, foreign_key: "firm_id", class_name: "Account" + has_one :readonly_account, -> { readonly }, foreign_key: "firm_id", class_name: "Account" # added order by id as in fixtures there are two accounts for Rails Core # Oracle tests were failing because of that as the second fixture was selected - has_one :account_using_primary_key, -> { order("id") }, :primary_key => "firm_id", :class_name => "Account" - has_one :account_using_foreign_and_primary_keys, :foreign_key => "firm_name", :primary_key => "name", :class_name => "Account" + has_one :account_using_primary_key, -> { order("id") }, primary_key: "firm_id", class_name: "Account" + has_one :account_using_foreign_and_primary_keys, foreign_key: "firm_name", primary_key: "name", class_name: "Account" has_one :account_with_inexistent_foreign_key, class_name: "Account", foreign_key: "inexistent" - has_one :deletable_account, :foreign_key => "firm_id", :class_name => "Account", :dependent => :delete + has_one :deletable_account, foreign_key: "firm_id", class_name: "Account", dependent: :delete - has_one :account_limit_500_with_hash_conditions, -> { where :credit_limit => 500 }, :foreign_key => "firm_id", :class_name => "Account" + has_one :account_limit_500_with_hash_conditions, -> { where credit_limit: 500 }, foreign_key: "firm_id", class_name: "Account" - has_one :unautosaved_account, :foreign_key => "firm_id", :class_name => "Account", :autosave => false + has_one :unautosaved_account, foreign_key: "firm_id", class_name: "Account", autosave: false has_many :accounts - has_many :unautosaved_accounts, :foreign_key => "firm_id", :class_name => "Account", :autosave => false + has_many :unautosaved_accounts, foreign_key: "firm_id", class_name: "Account", autosave: false - has_many :association_with_references, -> { references(:foo) }, :class_name => "Client" + has_many :association_with_references, -> { references(:foo) }, class_name: "Client" has_one :lead_developer, class_name: "Developer" has_many :projects @@ -103,32 +103,32 @@ def log_after_remove(record) end class DependentFirm < Company - has_one :account, :foreign_key => "firm_id", :dependent => :nullify - has_many :companies, :foreign_key => "client_of", :dependent => :nullify - has_one :company, :foreign_key => "client_of", :dependent => :nullify + has_one :account, foreign_key: "firm_id", dependent: :nullify + has_many :companies, foreign_key: "client_of", dependent: :nullify + has_one :company, foreign_key: "client_of", dependent: :nullify end class RestrictedWithExceptionFirm < Company - has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict_with_exception - has_many :companies, -> { order("id") }, :foreign_key => "client_of", :dependent => :restrict_with_exception + has_one :account, -> { order("id") }, foreign_key: "firm_id", dependent: :restrict_with_exception + has_many :companies, -> { order("id") }, foreign_key: "client_of", dependent: :restrict_with_exception end class RestrictedWithErrorFirm < Company - has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict_with_error - has_many :companies, -> { order("id") }, :foreign_key => "client_of", :dependent => :restrict_with_error + has_one :account, -> { order("id") }, foreign_key: "firm_id", dependent: :restrict_with_error + has_many :companies, -> { order("id") }, foreign_key: "client_of", dependent: :restrict_with_error end class Client < Company - belongs_to :firm, :foreign_key => "client_of" - belongs_to :firm_with_basic_id, :class_name => "Firm", :foreign_key => "firm_id" - belongs_to :firm_with_select, -> { select("id") }, :class_name => "Firm", :foreign_key => "firm_id" - belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of" - belongs_to :firm_with_condition, -> { where "1 = ?", 1 }, :class_name => "Firm", :foreign_key => "client_of" - belongs_to :firm_with_primary_key, :class_name => "Firm", :primary_key => "name", :foreign_key => "firm_name" - belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name - belongs_to :readonly_firm, -> { readonly }, :class_name => "Firm", :foreign_key => "firm_id" - belongs_to :bob_firm, -> { where :name => "Bob" }, :class_name => "Firm", :foreign_key => "client_of" - has_many :accounts, :through => :firm, :source => :accounts + belongs_to :firm, foreign_key: "client_of" + belongs_to :firm_with_basic_id, class_name: "Firm", foreign_key: "firm_id" + belongs_to :firm_with_select, -> { select("id") }, class_name: "Firm", foreign_key: "firm_id" + belongs_to :firm_with_other_name, class_name: "Firm", foreign_key: "client_of" + belongs_to :firm_with_condition, -> { where "1 = ?", 1 }, class_name: "Firm", foreign_key: "client_of" + belongs_to :firm_with_primary_key, class_name: "Firm", primary_key: "name", foreign_key: "firm_name" + belongs_to :firm_with_primary_key_symbols, class_name: "Firm", primary_key: :name, foreign_key: :firm_name + belongs_to :readonly_firm, -> { readonly }, class_name: "Firm", foreign_key: "firm_id" + belongs_to :bob_firm, -> { where name: "Bob" }, class_name: "Firm", foreign_key: "client_of" + has_many :accounts, through: :firm, source: :accounts belongs_to :account validate do @@ -181,9 +181,9 @@ def private_method end class ExclusivelyDependentFirm < Company - has_one :account, :foreign_key => "firm_id", :dependent => :delete - has_many :dependent_sanitized_conditional_clients_of_firm, -> { order("id").where("name = 'BigShot Inc.'") }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all - has_many :dependent_conditional_clients_of_firm, -> { order("id").where("name = ?", "BigShot Inc.") }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all + has_one :account, foreign_key: "firm_id", dependent: :delete + has_many :dependent_sanitized_conditional_clients_of_firm, -> { order("id").where("name = 'BigShot Inc.'") }, foreign_key: "client_of", class_name: "Client", dependent: :delete_all + has_many :dependent_conditional_clients_of_firm, -> { order("id").where("name = ?", "BigShot Inc.") }, foreign_key: "client_of", class_name: "Client", dependent: :delete_all end class SpecialClient < Client @@ -193,8 +193,8 @@ class VerySpecialClient < SpecialClient end class Account < ActiveRecord::Base - belongs_to :firm, :class_name => "Company" - belongs_to :unautosaved_firm, :foreign_key => "firm_id", :class_name => "Firm", :autosave => false + belongs_to :firm, class_name: "Company" + belongs_to :unautosaved_firm, foreign_key: "firm_id", class_name: "Firm", autosave: false alias_attribute :available_credit, :credit_limit diff --git a/activerecord/test/models/company_in_module.rb b/activerecord/test/models/company_in_module.rb index b444f9c49c..e035a80ab8 100644 --- a/activerecord/test/models/company_in_module.rb +++ b/activerecord/test/models/company_in_module.rb @@ -6,23 +6,23 @@ class Company < ActiveRecord::Base end class Firm < Company - has_many :clients, -> { order("id") }, :dependent => :destroy - has_many :clients_sorted_desc, -> { order("id DESC") }, :class_name => "Client" - has_many :clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client" - has_many :clients_like_ms, -> { where("name = 'Microsoft'").order("id") }, :class_name => "Client" - has_one :account, :class_name => "MyApplication::Billing::Account", :dependent => :destroy + has_many :clients, -> { order("id") }, dependent: :destroy + has_many :clients_sorted_desc, -> { order("id DESC") }, class_name: "Client" + has_many :clients_of_firm, -> { order "id" }, foreign_key: "client_of", class_name: "Client" + has_many :clients_like_ms, -> { where("name = 'Microsoft'").order("id") }, class_name: "Client" + has_one :account, class_name: "MyApplication::Billing::Account", dependent: :destroy end class Client < Company - belongs_to :firm, :foreign_key => "client_of" - belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of" + belongs_to :firm, foreign_key: "client_of" + belongs_to :firm_with_other_name, class_name: "Firm", foreign_key: "client_of" class Contact < ActiveRecord::Base; end end class Developer < ActiveRecord::Base has_and_belongs_to_many :projects - validates_length_of :name, :within => (3..20) + validates_length_of :name, within: (3..20) end class Project < ActiveRecord::Base @@ -78,12 +78,12 @@ class Firm < ActiveRecord::Base end class Account < ActiveRecord::Base - with_options(:foreign_key => :firm_id) do |i| - i.belongs_to :firm, :class_name => "MyApplication::Business::Firm" - i.belongs_to :qualified_billing_firm, :class_name => "MyApplication::Billing::Firm" - i.belongs_to :unqualified_billing_firm, :class_name => "Firm" - i.belongs_to :nested_qualified_billing_firm, :class_name => "MyApplication::Billing::Nested::Firm" - i.belongs_to :nested_unqualified_billing_firm, :class_name => "Nested::Firm" + with_options(foreign_key: :firm_id) do |i| + i.belongs_to :firm, class_name: "MyApplication::Business::Firm" + i.belongs_to :qualified_billing_firm, class_name: "MyApplication::Billing::Firm" + i.belongs_to :unqualified_billing_firm, class_name: "Firm" + i.belongs_to :nested_qualified_billing_firm, class_name: "MyApplication::Billing::Nested::Firm" + i.belongs_to :nested_unqualified_billing_firm, class_name: "Nested::Firm" end validate :check_empty_credit_limit diff --git a/activerecord/test/models/computer.rb b/activerecord/test/models/computer.rb index 0295ff9736..1c9856e1af 100644 --- a/activerecord/test/models/computer.rb +++ b/activerecord/test/models/computer.rb @@ -1,3 +1,3 @@ class Computer < ActiveRecord::Base - belongs_to :developer, :foreign_key=>"developer" + belongs_to :developer, foreign_key: "developer" end diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb index 15e3832204..47bbbbfd8b 100644 --- a/activerecord/test/models/contact.rb +++ b/activerecord/test/models/contact.rb @@ -1,7 +1,7 @@ module ContactFakeColumns def self.extended(base) base.class_eval do - establish_connection(:adapter => "fake") + establish_connection(adapter: "fake") connection.data_sources = [table_name] connection.primary_keys = { @@ -19,7 +19,7 @@ def self.extended(base) serialize :preferences - belongs_to :alternative, :class_name => "Contact" + belongs_to :alternative, class_name: "Contact" end end diff --git a/activerecord/test/models/contract.rb b/activerecord/test/models/contract.rb index e16758498f..32bd581377 100644 --- a/activerecord/test/models/contract.rb +++ b/activerecord/test/models/contract.rb @@ -1,7 +1,7 @@ class Contract < ActiveRecord::Base belongs_to :company belongs_to :developer - belongs_to :firm, :foreign_key => "company_id" + belongs_to :firm, foreign_key: "company_id" before_save :hi after_save :bye diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb index d464759430..71afd0866e 100644 --- a/activerecord/test/models/customer.rb +++ b/activerecord/test/models/customer.rb @@ -1,13 +1,13 @@ class Customer < ActiveRecord::Base cattr_accessor :gps_conversion_was_run - composed_of :address, :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ], :allow_nil => true - composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new(&:to_money) - composed_of :gps_location, :allow_nil => true - composed_of :non_blank_gps_location, :class_name => "GpsLocation", :allow_nil => true, :mapping => %w(gps_location gps_location), - :converter => lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)} - composed_of :fullname, :mapping => %w(name to_s), :constructor => Proc.new { |name| Fullname.parse(name) }, :converter => :parse - composed_of :fullname_no_converter, :mapping => %w(name to_s), class_name: "Fullname" + composed_of :address, mapping: [ %w(address_street street), %w(address_city city), %w(address_country country) ], allow_nil: true + composed_of :balance, class_name: "Money", mapping: %w(balance amount), converter: Proc.new(&:to_money) + composed_of :gps_location, allow_nil: true + composed_of :non_blank_gps_location, class_name: "GpsLocation", allow_nil: true, mapping: %w(gps_location gps_location), + converter: lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)} + composed_of :fullname, mapping: %w(name to_s), constructor: Proc.new { |name| Fullname.parse(name) }, converter: :parse + composed_of :fullname_no_converter, mapping: %w(name to_s), class_name: "Fullname" end class Address diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb index 41cbe35cb4..6dc3c6d632 100644 --- a/activerecord/test/models/developer.rb +++ b/activerecord/test/models/developer.rb @@ -23,35 +23,35 @@ def find_most_recent has_and_belongs_to_many :projects_extended_by_name, -> { extending(DeveloperProjectsAssociationExtension) }, - :class_name => "Project", - :join_table => "developers_projects", - :association_foreign_key => "project_id" + class_name: "Project", + join_table: "developers_projects", + association_foreign_key: "project_id" has_and_belongs_to_many :projects_extended_by_name_twice, -> { extending(DeveloperProjectsAssociationExtension, DeveloperProjectsAssociationExtension2) }, - :class_name => "Project", - :join_table => "developers_projects", - :association_foreign_key => "project_id" + class_name: "Project", + join_table: "developers_projects", + association_foreign_key: "project_id" has_and_belongs_to_many :projects_extended_by_name_and_block, -> { extending(DeveloperProjectsAssociationExtension) }, - :class_name => "Project", - :join_table => "developers_projects", - :association_foreign_key => "project_id" do + class_name: "Project", + join_table: "developers_projects", + association_foreign_key: "project_id" do def find_least_recent order("id ASC").first end end - has_and_belongs_to_many :special_projects, :join_table => "developers_projects", :association_foreign_key => "project_id" + has_and_belongs_to_many :special_projects, join_table: "developers_projects", association_foreign_key: "project_id" has_and_belongs_to_many :sym_special_projects, - :join_table => :developers_projects, - :association_foreign_key => "project_id", - :class_name => "SpecialProject" + join_table: :developers_projects, + association_foreign_key: "project_id", + class_name: "SpecialProject" has_many :audit_logs has_many :contracts - has_many :firms, :through => :contracts, :source => :firm + has_many :firms, through: :contracts, source: :firm has_many :comments, ->(developer) { where(body: "I'm #{developer.name}") } has_many :ratings, through: :comments has_one :ship, dependent: :nullify @@ -59,20 +59,20 @@ def find_least_recent belongs_to :firm has_many :contracted_projects, class_name: "Project" - scope :jamises, -> { where(:name => "Jamis") } + scope :jamises, -> { where(name: "Jamis") } - validates_inclusion_of :salary, :in => 50000..200000 - validates_length_of :name, :within => 3..20 + validates_inclusion_of :salary, in: 50000..200000 + validates_length_of :name, within: 3..20 before_create do |developer| - developer.audit_logs.build :message => "Computer created" + developer.audit_logs.build message: "Computer created" end attr_accessor :last_name define_attribute_method "last_name" def log=(message) - audit_logs.build :message => message + audit_logs.build message: message end after_find :track_instance_count @@ -87,13 +87,13 @@ def track_instance_count end class AuditLog < ActiveRecord::Base - belongs_to :developer, :validate => true - belongs_to :unvalidated_developer, :class_name => "Developer" + belongs_to :developer, validate: true + belongs_to :unvalidated_developer, class_name: "Developer" end class DeveloperWithBeforeDestroyRaise < ActiveRecord::Base self.table_name = "developers" - has_and_belongs_to_many :projects, :join_table => "developers_projects", :foreign_key => "developer_id" + has_and_belongs_to_many :projects, join_table: "developers_projects", foreign_key: "developer_id" before_destroy :raise_if_projects_empty! def raise_if_projects_empty! @@ -108,16 +108,16 @@ class DeveloperWithSelect < ActiveRecord::Base class DeveloperWithIncludes < ActiveRecord::Base self.table_name = "developers" - has_many :audit_logs, :foreign_key => :developer_id + has_many :audit_logs, foreign_key: :developer_id default_scope { includes(:audit_logs) } end class DeveloperFilteredOnJoins < ActiveRecord::Base self.table_name = "developers" - has_and_belongs_to_many :projects, -> { order("projects.id") }, :foreign_key => "developer_id", :join_table => "developers_projects" + has_and_belongs_to_many :projects, -> { order("projects.id") }, foreign_key: "developer_id", join_table: "developers_projects" def self.default_scope - joins(:projects).where(:projects => { :name => "Active Controller" }) + joins(:projects).where(projects: { name: "Active Controller" }) end end @@ -135,30 +135,30 @@ class DeveloperCalledDavid < ActiveRecord::Base class LazyLambdaDeveloperCalledDavid < ActiveRecord::Base self.table_name = "developers" - default_scope lambda { where(:name => "David") } + default_scope lambda { where(name: "David") } end class LazyBlockDeveloperCalledDavid < ActiveRecord::Base self.table_name = "developers" - default_scope { where(:name => "David") } + default_scope { where(name: "David") } end class CallableDeveloperCalledDavid < ActiveRecord::Base self.table_name = "developers" - default_scope OpenStruct.new(:call => where(:name => "David")) + default_scope OpenStruct.new(call: where(name: "David")) end class ClassMethodDeveloperCalledDavid < ActiveRecord::Base self.table_name = "developers" def self.default_scope - where(:name => "David") + where(name: "David") end end class ClassMethodReferencingScopeDeveloperCalledDavid < ActiveRecord::Base self.table_name = "developers" - scope :david, -> { where(:name => "David") } + scope :david, -> { where(name: "David") } def self.default_scope david @@ -167,14 +167,14 @@ def self.default_scope class LazyBlockReferencingScopeDeveloperCalledDavid < ActiveRecord::Base self.table_name = "developers" - scope :david, -> { where(:name => "David") } + scope :david, -> { where(name: "David") } default_scope { david } end class DeveloperCalledJamis < ActiveRecord::Base self.table_name = "developers" - default_scope { where(:name => "Jamis") } + default_scope { where(name: "Jamis") } scope :poor, -> { where("salary < 150000") } scope :david, -> { where name: "David" } scope :david2, -> { unscoped.where name: "David" } @@ -183,26 +183,26 @@ class DeveloperCalledJamis < ActiveRecord::Base class PoorDeveloperCalledJamis < ActiveRecord::Base self.table_name = "developers" - default_scope -> { where(:name => "Jamis", :salary => 50000) } + default_scope -> { where(name: "Jamis", salary: 50000) } end class InheritedPoorDeveloperCalledJamis < DeveloperCalledJamis self.table_name = "developers" - default_scope -> { where(:salary => 50000) } + default_scope -> { where(salary: 50000) } end class MultiplePoorDeveloperCalledJamis < ActiveRecord::Base self.table_name = "developers" - default_scope -> { where(:name => "Jamis") } - default_scope -> { where(:salary => 50000) } + default_scope -> { where(name: "Jamis") } + default_scope -> { where(salary: 50000) } end module SalaryDefaultScope extend ActiveSupport::Concern - included { default_scope { where(:salary => 50000) } } + included { default_scope { where(salary: 50000) } } end class ModuleIncludedPoorDeveloperCalledJamis < DeveloperCalledJamis @@ -213,14 +213,14 @@ class ModuleIncludedPoorDeveloperCalledJamis < DeveloperCalledJamis class EagerDeveloperWithDefaultScope < ActiveRecord::Base self.table_name = "developers" - has_and_belongs_to_many :projects, -> { order("projects.id") }, :foreign_key => "developer_id", :join_table => "developers_projects" + has_and_belongs_to_many :projects, -> { order("projects.id") }, foreign_key: "developer_id", join_table: "developers_projects" default_scope { includes(:projects) } end class EagerDeveloperWithClassMethodDefaultScope < ActiveRecord::Base self.table_name = "developers" - has_and_belongs_to_many :projects, -> { order("projects.id") }, :foreign_key => "developer_id", :join_table => "developers_projects" + has_and_belongs_to_many :projects, -> { order("projects.id") }, foreign_key: "developer_id", join_table: "developers_projects" def self.default_scope includes(:projects) @@ -229,23 +229,23 @@ def self.default_scope class EagerDeveloperWithLambdaDefaultScope < ActiveRecord::Base self.table_name = "developers" - has_and_belongs_to_many :projects, -> { order("projects.id") }, :foreign_key => "developer_id", :join_table => "developers_projects" + has_and_belongs_to_many :projects, -> { order("projects.id") }, foreign_key: "developer_id", join_table: "developers_projects" default_scope lambda { includes(:projects) } end class EagerDeveloperWithBlockDefaultScope < ActiveRecord::Base self.table_name = "developers" - has_and_belongs_to_many :projects, -> { order("projects.id") }, :foreign_key => "developer_id", :join_table => "developers_projects" + has_and_belongs_to_many :projects, -> { order("projects.id") }, foreign_key: "developer_id", join_table: "developers_projects" default_scope { includes(:projects) } end class EagerDeveloperWithCallableDefaultScope < ActiveRecord::Base self.table_name = "developers" - has_and_belongs_to_many :projects, -> { order("projects.id") }, :foreign_key => "developer_id", :join_table => "developers_projects" + has_and_belongs_to_many :projects, -> { order("projects.id") }, foreign_key: "developer_id", join_table: "developers_projects" - default_scope OpenStruct.new(:call => includes(:projects)) + default_scope OpenStruct.new(call: includes(:projects)) end class ThreadsafeDeveloper < ActiveRecord::Base diff --git a/activerecord/test/models/edge.rb b/activerecord/test/models/edge.rb index 1de4756b28..e61d25c9bc 100644 --- a/activerecord/test/models/edge.rb +++ b/activerecord/test/models/edge.rb @@ -1,5 +1,5 @@ # This class models an edge in a directed graph. class Edge < ActiveRecord::Base - belongs_to :source, :class_name => "Vertex", :foreign_key => "source_id" - belongs_to :sink, :class_name => "Vertex", :foreign_key => "sink_id" + belongs_to :source, class_name: "Vertex", foreign_key: "source_id" + belongs_to :sink, class_name: "Vertex", foreign_key: "sink_id" end diff --git a/activerecord/test/models/engine.rb b/activerecord/test/models/engine.rb index c30502e3ea..50c6717037 100644 --- a/activerecord/test/models/engine.rb +++ b/activerecord/test/models/engine.rb @@ -1,4 +1,4 @@ class Engine < ActiveRecord::Base - belongs_to :my_car, :class_name => "Car", :foreign_key => "car_id", :counter_cache => :engines_count + belongs_to :my_car, class_name: "Car", foreign_key: "car_id", counter_cache: :engines_count end diff --git a/activerecord/test/models/essay.rb b/activerecord/test/models/essay.rb index ec4b982b5b..13267fbc21 100644 --- a/activerecord/test/models/essay.rb +++ b/activerecord/test/models/essay.rb @@ -1,5 +1,5 @@ class Essay < ActiveRecord::Base - belongs_to :writer, :primary_key => :name, :polymorphic => true - belongs_to :category, :primary_key => :name - has_one :owner, :primary_key => :name + belongs_to :writer, primary_key: :name, polymorphic: true + belongs_to :category, primary_key: :name + has_one :owner, primary_key: :name end diff --git a/activerecord/test/models/face.rb b/activerecord/test/models/face.rb index 5f33372b16..5913bfa969 100644 --- a/activerecord/test/models/face.rb +++ b/activerecord/test/models/face.rb @@ -1,9 +1,9 @@ class Face < ActiveRecord::Base - belongs_to :man, :inverse_of => :face - belongs_to :polymorphic_man, :polymorphic => true, :inverse_of => :polymorphic_face + belongs_to :man, inverse_of: :face + belongs_to :polymorphic_man, polymorphic: true, inverse_of: :polymorphic_face # Oracle identifier length is limited to 30 bytes or less, `polymorphic` renamed `poly` - belongs_to :poly_man_without_inverse, :polymorphic => true + belongs_to :poly_man_without_inverse, polymorphic: true # These is a "broken" inverse_of for the purposes of testing - belongs_to :horrible_man, :class_name => "Man", :inverse_of => :horrible_face - belongs_to :horrible_polymorphic_man, :polymorphic => true, :inverse_of => :horrible_polymorphic_face + belongs_to :horrible_man, class_name: "Man", inverse_of: :horrible_face + belongs_to :horrible_polymorphic_man, polymorphic: true, inverse_of: :horrible_polymorphic_face end diff --git a/activerecord/test/models/hotel.rb b/activerecord/test/models/hotel.rb index 203e384c76..7bc717c891 100644 --- a/activerecord/test/models/hotel.rb +++ b/activerecord/test/models/hotel.rb @@ -5,7 +5,7 @@ class Hotel < ActiveRecord::Base has_many :drink_designers, source_type: "DrinkDesigner", source: :employable, through: :chefs has_many :chef_lists, as: :employable_list - has_many :mocktail_designers, through: :chef_lists, source: :employable, :source_type => "MocktailDesigner" + has_many :mocktail_designers, through: :chef_lists, source: :employable, source_type: "MocktailDesigner" has_many :recipes, through: :chefs end diff --git a/activerecord/test/models/interest.rb b/activerecord/test/models/interest.rb index d5d9226204..ec79416ee7 100644 --- a/activerecord/test/models/interest.rb +++ b/activerecord/test/models/interest.rb @@ -1,5 +1,5 @@ class Interest < ActiveRecord::Base - belongs_to :man, :inverse_of => :interests - belongs_to :polymorphic_man, :polymorphic => true, :inverse_of => :polymorphic_interests - belongs_to :zine, :inverse_of => :interests + belongs_to :man, inverse_of: :interests + belongs_to :polymorphic_man, polymorphic: true, inverse_of: :polymorphic_interests + belongs_to :zine, inverse_of: :interests end diff --git a/activerecord/test/models/invoice.rb b/activerecord/test/models/invoice.rb index fc6ef0230e..44ee717187 100644 --- a/activerecord/test/models/invoice.rb +++ b/activerecord/test/models/invoice.rb @@ -1,4 +1,4 @@ class Invoice < ActiveRecord::Base - has_many :line_items, :autosave => true + has_many :line_items, autosave: true before_save {|record| record.balance = record.line_items.map(&:amount).sum } end diff --git a/activerecord/test/models/item.rb b/activerecord/test/models/item.rb index c2571dd7fb..336fb1769a 100644 --- a/activerecord/test/models/item.rb +++ b/activerecord/test/models/item.rb @@ -1,6 +1,6 @@ class AbstractItem < ActiveRecord::Base self.abstract_class = true - has_one :tagging, :as => :taggable + has_one :tagging, as: :taggable end class Item < AbstractItem diff --git a/activerecord/test/models/job.rb b/activerecord/test/models/job.rb index 267f73bd6f..bbaef2792c 100644 --- a/activerecord/test/models/job.rb +++ b/activerecord/test/models/job.rb @@ -1,7 +1,7 @@ class Job < ActiveRecord::Base has_many :references - has_many :people, :through => :references - belongs_to :ideal_reference, :class_name => "Reference" + has_many :people, through: :references + belongs_to :ideal_reference, class_name: "Reference" - has_many :agents, :through => :people + has_many :agents, through: :people end diff --git a/activerecord/test/models/line_item.rb b/activerecord/test/models/line_item.rb index 0dd921a300..93f7cceb13 100644 --- a/activerecord/test/models/line_item.rb +++ b/activerecord/test/models/line_item.rb @@ -1,3 +1,3 @@ class LineItem < ActiveRecord::Base - belongs_to :invoice, :touch => true + belongs_to :invoice, touch: true end diff --git a/activerecord/test/models/man.rb b/activerecord/test/models/man.rb index 797c46dcbe..d2436a735c 100644 --- a/activerecord/test/models/man.rb +++ b/activerecord/test/models/man.rb @@ -1,11 +1,11 @@ class Man < ActiveRecord::Base - has_one :face, :inverse_of => :man - has_one :polymorphic_face, :class_name => "Face", :as => :polymorphic_man, :inverse_of => :polymorphic_man - has_one :polymorphic_face_without_inverse, :class_name => "Face", :as => :poly_man_without_inverse - has_many :interests, :inverse_of => :man - has_many :polymorphic_interests, :class_name => "Interest", :as => :polymorphic_man, :inverse_of => :polymorphic_man + has_one :face, inverse_of: :man + has_one :polymorphic_face, class_name: "Face", as: :polymorphic_man, inverse_of: :polymorphic_man + has_one :polymorphic_face_without_inverse, class_name: "Face", as: :poly_man_without_inverse + has_many :interests, inverse_of: :man + has_many :polymorphic_interests, class_name: "Interest", as: :polymorphic_man, inverse_of: :polymorphic_man # These are "broken" inverse_of associations for the purposes of testing - has_one :dirty_face, :class_name => "Face", :inverse_of => :dirty_man - has_many :secret_interests, :class_name => "Interest", :inverse_of => :secret_man + has_one :dirty_face, class_name: "Face", inverse_of: :dirty_man + has_many :secret_interests, class_name: "Interest", inverse_of: :secret_man has_one :mixed_case_monkey end diff --git a/activerecord/test/models/matey.rb b/activerecord/test/models/matey.rb index 1badaede0a..80ee5f47c5 100644 --- a/activerecord/test/models/matey.rb +++ b/activerecord/test/models/matey.rb @@ -1,4 +1,4 @@ class Matey < ActiveRecord::Base belongs_to :pirate - belongs_to :target, :class_name => "Pirate" + belongs_to :target, class_name: "Pirate" end diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb index dd90d3e92b..93dfc8253f 100644 --- a/activerecord/test/models/member.rb +++ b/activerecord/test/models/member.rb @@ -2,34 +2,34 @@ class Member < ActiveRecord::Base has_one :current_membership has_one :selected_membership has_one :membership - has_one :club, :through => :current_membership - has_one :selected_club, :through => :selected_membership, :source => :club - has_one :favourite_club, -> { where "memberships.favourite = ?", true }, :through => :membership, :source => :club - has_one :hairy_club, -> { where :clubs => {:name => "Moustache and Eyebrow Fancier Club"} }, :through => :membership, :source => :club - has_one :sponsor, :as => :sponsorable - has_one :sponsor_club, :through => :sponsor - has_one :member_detail, :inverse_of => false - has_one :organization, :through => :member_detail + has_one :club, through: :current_membership + has_one :selected_club, through: :selected_membership, source: :club + has_one :favourite_club, -> { where "memberships.favourite = ?", true }, through: :membership, source: :club + has_one :hairy_club, -> { where clubs: {name: "Moustache and Eyebrow Fancier Club"} }, through: :membership, source: :club + has_one :sponsor, as: :sponsorable + has_one :sponsor_club, through: :sponsor + has_one :member_detail, inverse_of: false + has_one :organization, through: :member_detail belongs_to :member_type - has_many :nested_member_types, :through => :member_detail, :source => :member_type - has_one :nested_member_type, :through => :member_detail, :source => :member_type + has_many :nested_member_types, through: :member_detail, source: :member_type + has_one :nested_member_type, through: :member_detail, source: :member_type - has_many :nested_sponsors, :through => :sponsor_club, :source => :sponsor - has_one :nested_sponsor, :through => :sponsor_club, :source => :sponsor + has_many :nested_sponsors, through: :sponsor_club, source: :sponsor + has_one :nested_sponsor, through: :sponsor_club, source: :sponsor - has_many :organization_member_details, :through => :member_detail - has_many :organization_member_details_2, :through => :organization, :source => :member_details + has_many :organization_member_details, through: :member_detail + has_many :organization_member_details_2, through: :organization, source: :member_details - has_one :club_category, :through => :club, :source => :category + has_one :club_category, through: :club, source: :category - has_many :current_memberships, -> { where :favourite => true } - has_many :clubs, :through => :current_memberships + has_many :current_memberships, -> { where favourite: true } + has_many :clubs, through: :current_memberships has_many :tenant_memberships has_many :tenant_clubs, through: :tenant_memberships, class_name: "Club", source: :club - has_one :club_through_many, :through => :current_memberships, :source => :club + has_one :club_through_many, through: :current_memberships, source: :club belongs_to :admittable, polymorphic: true has_one :premium_club, through: :admittable @@ -37,5 +37,5 @@ class Member < ActiveRecord::Base class SelfMember < ActiveRecord::Base self.table_name = "members" - has_and_belongs_to_many :friends, :class_name => "SelfMember", :join_table => "member_friends" + has_and_belongs_to_many :friends, class_name: "SelfMember", join_table: "member_friends" end diff --git a/activerecord/test/models/minivan.rb b/activerecord/test/models/minivan.rb index 4fe79720ad..3c12406425 100644 --- a/activerecord/test/models/minivan.rb +++ b/activerecord/test/models/minivan.rb @@ -2,7 +2,7 @@ class Minivan < ActiveRecord::Base self.primary_key = :minivan_id belongs_to :speedometer - has_one :dashboard, :through => :speedometer + has_one :dashboard, through: :speedometer attr_readonly :color diff --git a/activerecord/test/models/order.rb b/activerecord/test/models/order.rb index 4ec7198c88..699be53959 100644 --- a/activerecord/test/models/order.rb +++ b/activerecord/test/models/order.rb @@ -1,4 +1,4 @@ class Order < ActiveRecord::Base - belongs_to :billing, :class_name => "Customer", :foreign_key => "billing_customer_id" - belongs_to :shipping, :class_name => "Customer", :foreign_key => "shipping_customer_id" + belongs_to :billing, class_name: "Customer", foreign_key: "billing_customer_id" + belongs_to :shipping, class_name: "Customer", foreign_key: "shipping_customer_id" end diff --git a/activerecord/test/models/organization.rb b/activerecord/test/models/organization.rb index 1858351dd1..462830dadc 100644 --- a/activerecord/test/models/organization.rb +++ b/activerecord/test/models/organization.rb @@ -1,14 +1,14 @@ class Organization < ActiveRecord::Base has_many :member_details - has_many :members, :through => :member_details + has_many :members, through: :member_details - has_many :authors, :primary_key => :name - has_many :author_essay_categories, :through => :authors, :source => :essay_categories + has_many :authors, primary_key: :name + has_many :author_essay_categories, through: :authors, source: :essay_categories - has_one :author, :primary_key => :name - has_one :author_owned_essay_category, :through => :author, :source => :owned_essay_category + has_one :author, primary_key: :name + has_one :author_owned_essay_category, through: :author, source: :owned_essay_category - has_many :posts, :through => :author, :source => :posts + has_many :posts, through: :author, source: :posts scope :clubs, -> { from("clubs") } end diff --git a/activerecord/test/models/parrot.rb b/activerecord/test/models/parrot.rb index 9ee9670da9..5b693664d4 100644 --- a/activerecord/test/models/parrot.rb +++ b/activerecord/test/models/parrot.rb @@ -3,13 +3,13 @@ class Parrot < ActiveRecord::Base has_and_belongs_to_many :pirates has_and_belongs_to_many :treasures - has_many :loots, :as => :looter + has_many :loots, as: :looter alias_attribute :title, :name validates_presence_of :name attr_accessor :cancel_save_from_callback - before_save :cancel_save_callback_method, :if => :cancel_save_from_callback + before_save :cancel_save_callback_method, if: :cancel_save_from_callback def cancel_save_callback_method throw(:abort) end @@ -19,5 +19,5 @@ class LiveParrot < Parrot end class DeadParrot < Parrot - belongs_to :killer, :class_name => "Pirate", foreign_key: :killer_id + belongs_to :killer, class_name: "Pirate", foreign_key: :killer_id end diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index a33b4dca6b..f57d8bdbdf 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -3,10 +3,10 @@ class Person < ActiveRecord::Base has_many :secure_readers has_one :reader - has_many :posts, :through => :readers - has_many :secure_posts, :through => :secure_readers + has_many :posts, through: :readers + has_many :secure_posts, through: :secure_readers has_many :posts_with_no_comments, -> { includes(:comments).where("comments.id is null").references(:comments) }, - :through => :readers, :source => :post + through: :readers, source: :post has_many :friendships, foreign_key: "friend_id" # friends_too exists to test a bug, and probably shouldn't be used elsewhere @@ -15,49 +15,49 @@ class Person < ActiveRecord::Base has_many :references has_many :bad_references - has_many :fixed_bad_references, -> { where :favourite => true }, :class_name => "BadReference" - has_one :favourite_reference, -> { where "favourite=?", true }, :class_name => "Reference" - has_many :posts_with_comments_sorted_by_comment_id, -> { includes(:comments).order("comments.id") }, :through => :readers, :source => :post + has_many :fixed_bad_references, -> { where favourite: true }, class_name: "BadReference" + has_one :favourite_reference, -> { where "favourite=?", true }, class_name: "Reference" + has_many :posts_with_comments_sorted_by_comment_id, -> { includes(:comments).order("comments.id") }, through: :readers, source: :post has_many :first_posts, -> { where(id: [1, 2]) }, through: :readers - has_many :jobs, :through => :references - has_many :jobs_with_dependent_destroy, :source => :job, :through => :references, :dependent => :destroy - has_many :jobs_with_dependent_delete_all, :source => :job, :through => :references, :dependent => :delete_all - has_many :jobs_with_dependent_nullify, :source => :job, :through => :references, :dependent => :nullify + has_many :jobs, through: :references + has_many :jobs_with_dependent_destroy, source: :job, through: :references, dependent: :destroy + has_many :jobs_with_dependent_delete_all, source: :job, through: :references, dependent: :delete_all + has_many :jobs_with_dependent_nullify, source: :job, through: :references, dependent: :nullify - belongs_to :primary_contact, :class_name => "Person" - has_many :agents, :class_name => "Person", :foreign_key => "primary_contact_id" - has_many :agents_of_agents, :through => :agents, :source => :agents - belongs_to :number1_fan, :class_name => "Person" + belongs_to :primary_contact, class_name: "Person" + has_many :agents, class_name: "Person", foreign_key: "primary_contact_id" + has_many :agents_of_agents, through: :agents, source: :agents + belongs_to :number1_fan, class_name: "Person" - has_many :personal_legacy_things, :dependent => :destroy + has_many :personal_legacy_things, dependent: :destroy - has_many :agents_posts, :through => :agents, :source => :posts - has_many :agents_posts_authors, :through => :agents_posts, :source => :author + has_many :agents_posts, through: :agents, source: :posts + has_many :agents_posts_authors, through: :agents_posts, source: :author has_many :essays, primary_key: "first_name", foreign_key: "writer_id" - scope :males, -> { where(:gender => "M") } + scope :males, -> { where(gender: "M") } end class PersonWithDependentDestroyJobs < ActiveRecord::Base self.table_name = "people" - has_many :references, :foreign_key => :person_id - has_many :jobs, :source => :job, :through => :references, :dependent => :destroy + has_many :references, foreign_key: :person_id + has_many :jobs, source: :job, through: :references, dependent: :destroy end class PersonWithDependentDeleteAllJobs < ActiveRecord::Base self.table_name = "people" - has_many :references, :foreign_key => :person_id - has_many :jobs, :source => :job, :through => :references, :dependent => :delete_all + has_many :references, foreign_key: :person_id + has_many :jobs, source: :job, through: :references, dependent: :delete_all end class PersonWithDependentNullifyJobs < ActiveRecord::Base self.table_name = "people" - has_many :references, :foreign_key => :person_id - has_many :jobs, :source => :job, :through => :references, :dependent => :nullify + has_many :references, foreign_key: :person_id + has_many :jobs, source: :job, through: :references, dependent: :nullify end @@ -65,9 +65,9 @@ class LoosePerson < ActiveRecord::Base self.table_name = "people" self.abstract_class = true - has_one :best_friend, :class_name => "LoosePerson", :foreign_key => :best_friend_id - belongs_to :best_friend_of, :class_name => "LoosePerson", :foreign_key => :best_friend_of_id - has_many :best_friends, :class_name => "LoosePerson", :foreign_key => :best_friend_id + has_one :best_friend, class_name: "LoosePerson", foreign_key: :best_friend_id + belongs_to :best_friend_of, class_name: "LoosePerson", foreign_key: :best_friend_of_id + has_many :best_friends, class_name: "LoosePerson", foreign_key: :best_friend_id accepts_nested_attributes_for :best_friend, :best_friend_of, :best_friends end @@ -77,9 +77,9 @@ class LooseDescendant < LoosePerson; end class TightPerson < ActiveRecord::Base self.table_name = "people" - has_one :best_friend, :class_name => "TightPerson", :foreign_key => :best_friend_id - belongs_to :best_friend_of, :class_name => "TightPerson", :foreign_key => :best_friend_of_id - has_many :best_friends, :class_name => "TightPerson", :foreign_key => :best_friend_id + has_one :best_friend, class_name: "TightPerson", foreign_key: :best_friend_id + belongs_to :best_friend_of, class_name: "TightPerson", foreign_key: :best_friend_of_id + has_many :best_friends, class_name: "TightPerson", foreign_key: :best_friend_id accepts_nested_attributes_for :best_friend, :best_friend_of, :best_friends end @@ -89,7 +89,7 @@ class TightDescendant < TightPerson; end class RichPerson < ActiveRecord::Base self.table_name = "people" - has_and_belongs_to_many :treasures, :join_table => "peoples_treasures" + has_and_belongs_to_many :treasures, join_table: "peoples_treasures" before_validation :run_before_create, on: :create before_validation :run_before_validation @@ -108,15 +108,15 @@ def run_before_validation class NestedPerson < ActiveRecord::Base self.table_name = "people" - has_one :best_friend, :class_name => "NestedPerson", :foreign_key => :best_friend_id - accepts_nested_attributes_for :best_friend, :update_only => true + has_one :best_friend, class_name: "NestedPerson", foreign_key: :best_friend_id + accepts_nested_attributes_for :best_friend, update_only: true def comments=(new_comments) raise RuntimeError end def best_friend_first_name=(new_name) - assign_attributes({ :best_friend_attributes => { :first_name => new_name } }) + assign_attributes({ best_friend_attributes: { first_name: new_name } }) end end diff --git a/activerecord/test/models/personal_legacy_thing.rb b/activerecord/test/models/personal_legacy_thing.rb index a7ee3a0bca..adde7a504a 100644 --- a/activerecord/test/models/personal_legacy_thing.rb +++ b/activerecord/test/models/personal_legacy_thing.rb @@ -1,4 +1,4 @@ class PersonalLegacyThing < ActiveRecord::Base self.locking_column = :version - belongs_to :person, :counter_cache => true + belongs_to :person, counter_cache: true end diff --git a/activerecord/test/models/pet.rb b/activerecord/test/models/pet.rb index 06170837b6..51a3e42815 100644 --- a/activerecord/test/models/pet.rb +++ b/activerecord/test/models/pet.rb @@ -2,7 +2,7 @@ class Pet < ActiveRecord::Base attr_accessor :current_user self.primary_key = :pet_id - belongs_to :owner, :touch => true + belongs_to :owner, touch: true has_many :toys has_many :pet_treasures has_many :treasures, through: :pet_treasures diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb index 7cb602f445..80a941874b 100644 --- a/activerecord/test/models/pirate.rb +++ b/activerecord/test/models/pirate.rb @@ -1,47 +1,47 @@ class Pirate < ActiveRecord::Base - belongs_to :parrot, :validate => true - belongs_to :non_validated_parrot, :class_name => "Parrot" - has_and_belongs_to_many :parrots, -> { order("parrots.id ASC") }, :validate => true - has_and_belongs_to_many :non_validated_parrots, :class_name => "Parrot" - has_and_belongs_to_many :parrots_with_method_callbacks, :class_name => "Parrot", - :before_add => :log_before_add, - :after_add => :log_after_add, - :before_remove => :log_before_remove, - :after_remove => :log_after_remove - has_and_belongs_to_many :parrots_with_proc_callbacks, :class_name => "Parrot", - :before_add => proc {|p,pa| p.ship_log << "before_adding_proc_parrot_#{pa.id || ''}"}, - :after_add => proc {|p,pa| p.ship_log << "after_adding_proc_parrot_#{pa.id || ''}"}, - :before_remove => proc {|p,pa| p.ship_log << "before_removing_proc_parrot_#{pa.id}"}, - :after_remove => proc {|p,pa| p.ship_log << "after_removing_proc_parrot_#{pa.id}"} + belongs_to :parrot, validate: true + belongs_to :non_validated_parrot, class_name: "Parrot" + has_and_belongs_to_many :parrots, -> { order("parrots.id ASC") }, validate: true + has_and_belongs_to_many :non_validated_parrots, class_name: "Parrot" + has_and_belongs_to_many :parrots_with_method_callbacks, class_name: "Parrot", + before_add: :log_before_add, + after_add: :log_after_add, + before_remove: :log_before_remove, + after_remove: :log_after_remove + has_and_belongs_to_many :parrots_with_proc_callbacks, class_name: "Parrot", + before_add: proc {|p,pa| p.ship_log << "before_adding_proc_parrot_#{pa.id || ''}"}, + after_add: proc {|p,pa| p.ship_log << "after_adding_proc_parrot_#{pa.id || ''}"}, + before_remove: proc {|p,pa| p.ship_log << "before_removing_proc_parrot_#{pa.id}"}, + after_remove: proc {|p,pa| p.ship_log << "after_removing_proc_parrot_#{pa.id}"} has_and_belongs_to_many :autosaved_parrots, class_name: "Parrot", autosave: true - has_many :treasures, :as => :looter - has_many :treasure_estimates, :through => :treasures, :source => :price_estimates + has_many :treasures, as: :looter + has_many :treasure_estimates, through: :treasures, source: :price_estimates has_one :ship - has_one :update_only_ship, :class_name => "Ship" - has_one :non_validated_ship, :class_name => "Ship" + has_one :update_only_ship, class_name: "Ship" + has_one :non_validated_ship, class_name: "Ship" has_many :birds, -> { order("birds.id ASC") } - has_many :birds_with_method_callbacks, :class_name => "Bird", - :before_add => :log_before_add, - :after_add => :log_after_add, - :before_remove => :log_before_remove, - :after_remove => :log_after_remove - has_many :birds_with_proc_callbacks, :class_name => "Bird", - :before_add => proc {|p,b| p.ship_log << "before_adding_proc_bird_#{b.id || ''}"}, - :after_add => proc {|p,b| p.ship_log << "after_adding_proc_bird_#{b.id || ''}"}, - :before_remove => proc {|p,b| p.ship_log << "before_removing_proc_bird_#{b.id}"}, - :after_remove => proc {|p,b| p.ship_log << "after_removing_proc_bird_#{b.id}"} - has_many :birds_with_reject_all_blank, :class_name => "Bird" + has_many :birds_with_method_callbacks, class_name: "Bird", + before_add: :log_before_add, + after_add: :log_after_add, + before_remove: :log_before_remove, + after_remove: :log_after_remove + has_many :birds_with_proc_callbacks, class_name: "Bird", + before_add: proc {|p,b| p.ship_log << "before_adding_proc_bird_#{b.id || ''}"}, + after_add: proc {|p,b| p.ship_log << "after_adding_proc_bird_#{b.id || ''}"}, + before_remove: proc {|p,b| p.ship_log << "before_removing_proc_bird_#{b.id}"}, + after_remove: proc {|p,b| p.ship_log << "after_removing_proc_bird_#{b.id}"} + has_many :birds_with_reject_all_blank, class_name: "Bird" - has_one :foo_bulb, -> { where :name => "foo" }, :foreign_key => :car_id, :class_name => "Bulb" + has_one :foo_bulb, -> { where name: "foo" }, foreign_key: :car_id, class_name: "Bulb" - accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc(&:empty?) - accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?) - accepts_nested_attributes_for :update_only_ship, :update_only => true + accepts_nested_attributes_for :parrots, :birds, allow_destroy: true, reject_if: proc(&:empty?) + accepts_nested_attributes_for :ship, allow_destroy: true, reject_if: proc(&:empty?) + accepts_nested_attributes_for :update_only_ship, update_only: true accepts_nested_attributes_for :parrots_with_method_callbacks, :parrots_with_proc_callbacks, - :birds_with_method_callbacks, :birds_with_proc_callbacks, :allow_destroy => true - accepts_nested_attributes_for :birds_with_reject_all_blank, :reject_if => :all_blank + :birds_with_method_callbacks, :birds_with_proc_callbacks, allow_destroy: true + accepts_nested_attributes_for :birds_with_reject_all_blank, reject_if: :all_blank validates_presence_of :catchphrase @@ -54,7 +54,7 @@ def reject_empty_ships_on_create(attributes) end attr_accessor :cancel_save_from_callback, :parrots_limit - before_save :cancel_save_callback_method, :if => :cancel_save_from_callback + before_save :cancel_save_callback_method, if: :cancel_save_from_callback def cancel_save_callback_method throw(:abort) end @@ -82,7 +82,7 @@ def log(record, callback) end class DestructivePirate < Pirate - has_one :dependent_ship, :class_name => "Ship", :foreign_key => :pirate_id, :dependent => :destroy + has_one :dependent_ship, class_name: "Ship", foreign_key: :pirate_id, dependent: :destroy end class FamousPirate < ActiveRecord::Base diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 395ba37e0b..8bfd79d907 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -25,18 +25,18 @@ def greeting belongs_to :author - belongs_to :author_with_posts, -> { includes(:posts) }, :class_name => "Author", :foreign_key => :author_id - belongs_to :author_with_address, -> { includes(:author_address) }, :class_name => "Author", :foreign_key => :author_id + belongs_to :author_with_posts, -> { includes(:posts) }, class_name: "Author", foreign_key: :author_id + belongs_to :author_with_address, -> { includes(:author_address) }, class_name: "Author", foreign_key: :author_id def first_comment super.body end - has_one :first_comment, -> { order("id ASC") }, :class_name => "Comment" - has_one :last_comment, -> { order("id desc") }, :class_name => "Comment" + has_one :first_comment, -> { order("id ASC") }, class_name: "Comment" + has_one :last_comment, -> { order("id desc") }, class_name: "Comment" - scope :with_special_comments, -> { joins(:comments).where(:comments => {:type => "SpecialComment"}) } - scope :with_very_special_comments, -> { joins(:comments).where(:comments => {:type => "VerySpecialComment"}) } - scope :with_post, ->(post_id) { joins(:comments).where(:comments => { :post_id => post_id }) } + scope :with_special_comments, -> { joins(:comments).where(comments: {type: "SpecialComment"}) } + scope :with_very_special_comments, -> { joins(:comments).where(comments: {type: "VerySpecialComment"}) } + scope :with_post, ->(post_id) { joins(:comments).where(comments: { post_id: post_id }) } scope :with_comments, -> { preload(:comments) } scope :with_tags, -> { preload(:taggings) } @@ -68,29 +68,29 @@ def greeting has_many :comments_with_extend_2, extend: [NamedExtension, NamedExtension2], class_name: "Comment", foreign_key: "post_id" - has_many :author_favorites, :through => :author - has_many :author_categorizations, :through => :author, :source => :categorizations - has_many :author_addresses, :through => :author + has_many :author_favorites, through: :author + has_many :author_categorizations, through: :author, source: :categorizations + has_many :author_addresses, through: :author has_many :author_address_extra_with_address, through: :author_with_address, source: :author_address_extra has_one :very_special_comment - has_one :very_special_comment_with_post, -> { includes(:post) }, :class_name => "VerySpecialComment" + has_one :very_special_comment_with_post, -> { includes(:post) }, class_name: "VerySpecialComment" has_one :very_special_comment_with_post_with_joins, -> { joins(:post).order("posts.id") }, class_name: "VerySpecialComment" has_many :special_comments - has_many :nonexistent_comments, -> { where "comments.id < 0" }, :class_name => "Comment" + has_many :nonexistent_comments, -> { where "comments.id < 0" }, class_name: "Comment" - has_many :special_comments_ratings, :through => :special_comments, :source => :ratings - has_many :special_comments_ratings_taggings, :through => :special_comments_ratings, :source => :taggings + has_many :special_comments_ratings, through: :special_comments, source: :ratings + has_many :special_comments_ratings_taggings, through: :special_comments_ratings, source: :taggings - has_many :category_posts, :class_name => "CategoryPost" + has_many :category_posts, class_name: "CategoryPost" has_many :scategories, through: :category_posts, source: :category has_and_belongs_to_many :categories - has_and_belongs_to_many :special_categories, :join_table => "categories_posts", :association_foreign_key => "category_id" + has_and_belongs_to_many :special_categories, join_table: "categories_posts", association_foreign_key: "category_id" - has_many :taggings, :as => :taggable, :counter_cache => :tags_count - has_many :tags, :through => :taggings do + has_many :taggings, as: :taggable, counter_cache: :tags_count + has_many :tags, through: :taggings do def add_joins_and_select select("tags.*, authors.id as author_id") .joins("left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id") @@ -98,62 +98,62 @@ def add_joins_and_select end end - has_many :taggings_with_delete_all, :class_name => "Tagging", :as => :taggable, :dependent => :delete_all, counter_cache: :taggings_with_delete_all_count - has_many :taggings_with_destroy, :class_name => "Tagging", :as => :taggable, :dependent => :destroy, counter_cache: :taggings_with_destroy_count + has_many :taggings_with_delete_all, class_name: "Tagging", as: :taggable, dependent: :delete_all, counter_cache: :taggings_with_delete_all_count + has_many :taggings_with_destroy, class_name: "Tagging", as: :taggable, dependent: :destroy, counter_cache: :taggings_with_destroy_count - has_many :tags_with_destroy, :through => :taggings, :source => :tag, :dependent => :destroy, counter_cache: :tags_with_destroy_count - has_many :tags_with_nullify, :through => :taggings, :source => :tag, :dependent => :nullify, counter_cache: :tags_with_nullify_count + has_many :tags_with_destroy, through: :taggings, source: :tag, dependent: :destroy, counter_cache: :tags_with_destroy_count + has_many :tags_with_nullify, through: :taggings, source: :tag, dependent: :nullify, counter_cache: :tags_with_nullify_count - has_many :misc_tags, -> { where :tags => { :name => "Misc" } }, :through => :taggings, :source => :tag - has_many :funky_tags, :through => :taggings, :source => :tag - has_many :super_tags, :through => :taggings - has_many :tags_with_primary_key, :through => :taggings, :source => :tag_with_primary_key - has_one :tagging, :as => :taggable + has_many :misc_tags, -> { where tags: { name: "Misc" } }, through: :taggings, source: :tag + has_many :funky_tags, through: :taggings, source: :tag + has_many :super_tags, through: :taggings + has_many :tags_with_primary_key, through: :taggings, source: :tag_with_primary_key + has_one :tagging, as: :taggable - has_many :first_taggings, -> { where :taggings => { :comment => "first" } }, :as => :taggable, :class_name => "Tagging" - has_many :first_blue_tags, -> { where :tags => { :name => "Blue" } }, :through => :first_taggings, :source => :tag + has_many :first_taggings, -> { where taggings: { comment: "first" } }, as: :taggable, class_name: "Tagging" + has_many :first_blue_tags, -> { where tags: { name: "Blue" } }, through: :first_taggings, source: :tag - has_many :first_blue_tags_2, -> { where :taggings => { :comment => "first" } }, :through => :taggings, :source => :blue_tag + has_many :first_blue_tags_2, -> { where taggings: { comment: "first" } }, through: :taggings, source: :blue_tag - has_many :invalid_taggings, -> { where "taggings.id < 0" }, :as => :taggable, :class_name => "Tagging" - has_many :invalid_tags, :through => :invalid_taggings, :source => :tag + has_many :invalid_taggings, -> { where "taggings.id < 0" }, as: :taggable, class_name: "Tagging" + has_many :invalid_tags, through: :invalid_taggings, source: :tag - has_many :categorizations, :foreign_key => :category_id - has_many :authors, :through => :categorizations + has_many :categorizations, foreign_key: :category_id + has_many :authors, through: :categorizations - has_many :categorizations_using_author_id, :primary_key => :author_id, :foreign_key => :post_id, :class_name => "Categorization" - has_many :authors_using_author_id, :through => :categorizations_using_author_id, :source => :author + has_many :categorizations_using_author_id, primary_key: :author_id, foreign_key: :post_id, class_name: "Categorization" + has_many :authors_using_author_id, through: :categorizations_using_author_id, source: :author - has_many :taggings_using_author_id, :primary_key => :author_id, :as => :taggable, :class_name => "Tagging" - has_many :tags_using_author_id, :through => :taggings_using_author_id, :source => :tag + has_many :taggings_using_author_id, primary_key: :author_id, as: :taggable, class_name: "Tagging" + has_many :tags_using_author_id, through: :taggings_using_author_id, source: :tag - has_many :images, :as => :imageable, :foreign_key => :imageable_identifier, :foreign_type => :imageable_class - has_one :main_image, :as => :imageable, :foreign_key => :imageable_identifier, :foreign_type => :imageable_class, :class_name => "Image" + has_many :images, as: :imageable, foreign_key: :imageable_identifier, foreign_type: :imageable_class + has_one :main_image, as: :imageable, foreign_key: :imageable_identifier, foreign_type: :imageable_class, class_name: "Image" - has_many :standard_categorizations, :class_name => "Categorization", :foreign_key => :post_id - has_many :author_using_custom_pk, :through => :standard_categorizations - has_many :authors_using_custom_pk, :through => :standard_categorizations - has_many :named_categories, :through => :standard_categorizations + has_many :standard_categorizations, class_name: "Categorization", foreign_key: :post_id + has_many :author_using_custom_pk, through: :standard_categorizations + has_many :authors_using_custom_pk, through: :standard_categorizations + has_many :named_categories, through: :standard_categorizations has_many :readers has_many :secure_readers - has_many :readers_with_person, -> { includes(:person) }, :class_name => "Reader" - has_many :people, :through => :readers - has_many :single_people, :through => :readers - has_many :people_with_callbacks, :source=>:person, :through => :readers, - :before_add => lambda {|owner, reader| log(:added, :before, reader.first_name) }, - :after_add => lambda {|owner, reader| log(:added, :after, reader.first_name) }, - :before_remove => lambda {|owner, reader| log(:removed, :before, reader.first_name) }, - :after_remove => lambda {|owner, reader| log(:removed, :after, reader.first_name) } - has_many :skimmers, -> { where :skimmer => true }, :class_name => "Reader" - has_many :impatient_people, :through => :skimmers, :source => :person + has_many :readers_with_person, -> { includes(:person) }, class_name: "Reader" + has_many :people, through: :readers + has_many :single_people, through: :readers + has_many :people_with_callbacks, source: :person, through: :readers, + before_add: lambda {|owner, reader| log(:added, :before, reader.first_name) }, + after_add: lambda {|owner, reader| log(:added, :after, reader.first_name) }, + before_remove: lambda {|owner, reader| log(:removed, :before, reader.first_name) }, + after_remove: lambda {|owner, reader| log(:removed, :after, reader.first_name) } + has_many :skimmers, -> { where skimmer: true }, class_name: "Reader" + has_many :impatient_people, through: :skimmers, source: :person has_many :lazy_readers - has_many :lazy_readers_skimmers_or_not, -> { where(skimmer: [ true, false ]) }, :class_name => "LazyReader" + has_many :lazy_readers_skimmers_or_not, -> { where(skimmer: [ true, false ]) }, class_name: "LazyReader" - has_many :lazy_people, :through => :lazy_readers, :source => :person - has_many :lazy_readers_unscope_skimmers, -> { skimmers_or_not }, :class_name => "LazyReader" - has_many :lazy_people_unscope_skimmers, :through => :lazy_readers_unscope_skimmers, :source => :person + has_many :lazy_people, through: :lazy_readers, source: :person + has_many :lazy_readers_unscope_skimmers, -> { skimmers_or_not }, class_name: "LazyReader" + has_many :lazy_people_unscope_skimmers, through: :lazy_readers_unscope_skimmers, source: :person def self.top(limit) ranked_by_comments.limit_by(limit) @@ -177,7 +177,7 @@ class SpecialPost < Post; end class StiPost < Post self.abstract_class = true - has_one :special_comment, :class_name => "SpecialComment" + has_one :special_comment, class_name: "SpecialComment" end class SubStiPost < StiPost @@ -187,22 +187,22 @@ class SubStiPost < StiPost class FirstPost < ActiveRecord::Base self.inheritance_column = :disabled self.table_name = "posts" - default_scope { where(:id => 1) } + default_scope { where(id: 1) } - has_many :comments, :foreign_key => :post_id - has_one :comment, :foreign_key => :post_id + has_many :comments, foreign_key: :post_id + has_one :comment, foreign_key: :post_id end class PostWithDefaultInclude < ActiveRecord::Base self.inheritance_column = :disabled self.table_name = "posts" default_scope { includes(:comments) } - has_many :comments, :foreign_key => :post_id + has_many :comments, foreign_key: :post_id end class PostWithSpecialCategorization < Post - has_many :categorizations, :foreign_key => :post_id - default_scope { where(:type => "PostWithSpecialCategorization").joins(:categorizations).where(:categorizations => { :special => true }) } + has_many :categorizations, foreign_key: :post_id + default_scope { where(type: "PostWithSpecialCategorization").joins(:categorizations).where(categorizations: { special: true }) } end class PostWithDefaultScope < ActiveRecord::Base @@ -230,7 +230,7 @@ class PostWithIncludesDefaultScope < ActiveRecord::Base class SpecialPostWithDefaultScope < ActiveRecord::Base self.inheritance_column = :disabled self.table_name = "posts" - default_scope { where(:id => [1, 5,6]) } + default_scope { where(id: [1, 5,6]) } end class PostThatLoadsCommentsInAnAfterSaveHook < ActiveRecord::Base diff --git a/activerecord/test/models/price_estimate.rb b/activerecord/test/models/price_estimate.rb index d09e2a88a3..ce086e40a3 100644 --- a/activerecord/test/models/price_estimate.rb +++ b/activerecord/test/models/price_estimate.rb @@ -1,4 +1,4 @@ class PriceEstimate < ActiveRecord::Base - belongs_to :estimate_of, :polymorphic => true + belongs_to :estimate_of, polymorphic: true belongs_to :thing, polymorphic: true end diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb index 1b3b807ee2..4d6b269731 100644 --- a/activerecord/test/models/project.rb +++ b/activerecord/test/models/project.rb @@ -1,17 +1,17 @@ class Project < ActiveRecord::Base belongs_to :mentor has_and_belongs_to_many :developers, -> { distinct.order "developers.name desc, developers.id desc" } - has_and_belongs_to_many :readonly_developers, -> { readonly }, :class_name => "Developer" - has_and_belongs_to_many :non_unique_developers, -> { order "developers.name desc, developers.id desc" }, :class_name => "Developer" - has_and_belongs_to_many :limited_developers, -> { limit 1 }, :class_name => "Developer" - has_and_belongs_to_many :developers_named_david, -> { where("name = 'David'").distinct }, :class_name => "Developer" - has_and_belongs_to_many :developers_named_david_with_hash_conditions, -> { where(:name => "David").distinct }, :class_name => "Developer" - has_and_belongs_to_many :salaried_developers, -> { where "salary > 0" }, :class_name => "Developer" - has_and_belongs_to_many :developers_with_callbacks, :class_name => "Developer", :before_add => Proc.new {|o, r| o.developers_log << "before_adding#{r.id || ''}"}, - :after_add => Proc.new {|o, r| o.developers_log << "after_adding#{r.id || ''}"}, - :before_remove => Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"}, - :after_remove => Proc.new {|o, r| o.developers_log << "after_removing#{r.id}"} - has_and_belongs_to_many :well_payed_salary_groups, -> { group("developers.salary").having("SUM(salary) > 10000").select("SUM(salary) as salary") }, :class_name => "Developer" + has_and_belongs_to_many :readonly_developers, -> { readonly }, class_name: "Developer" + has_and_belongs_to_many :non_unique_developers, -> { order "developers.name desc, developers.id desc" }, class_name: "Developer" + has_and_belongs_to_many :limited_developers, -> { limit 1 }, class_name: "Developer" + has_and_belongs_to_many :developers_named_david, -> { where("name = 'David'").distinct }, class_name: "Developer" + has_and_belongs_to_many :developers_named_david_with_hash_conditions, -> { where(name: "David").distinct }, class_name: "Developer" + has_and_belongs_to_many :salaried_developers, -> { where "salary > 0" }, class_name: "Developer" + has_and_belongs_to_many :developers_with_callbacks, class_name: "Developer", before_add: Proc.new {|o, r| o.developers_log << "before_adding#{r.id || ''}"}, + after_add: Proc.new {|o, r| o.developers_log << "after_adding#{r.id || ''}"}, + before_remove: Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"}, + after_remove: Proc.new {|o, r| o.developers_log << "after_removing#{r.id}"} + has_and_belongs_to_many :well_payed_salary_groups, -> { group("developers.salary").having("SUM(salary) > 10000").select("SUM(salary) as salary") }, class_name: "Developer" belongs_to :firm has_one :lead_developer, through: :firm, inverse_of: :contracted_projects diff --git a/activerecord/test/models/rating.rb b/activerecord/test/models/rating.rb index 25a52c4ad7..7420821db0 100644 --- a/activerecord/test/models/rating.rb +++ b/activerecord/test/models/rating.rb @@ -1,4 +1,4 @@ class Rating < ActiveRecord::Base belongs_to :comment - has_many :taggings, :as => :taggable + has_many :taggings, as: :taggable end diff --git a/activerecord/test/models/reader.rb b/activerecord/test/models/reader.rb index 8c7235ba9a..7c5a159fe0 100644 --- a/activerecord/test/models/reader.rb +++ b/activerecord/test/models/reader.rb @@ -1,22 +1,22 @@ class Reader < ActiveRecord::Base belongs_to :post - belongs_to :person, :inverse_of => :readers - belongs_to :single_person, :class_name => "Person", :foreign_key => :person_id, :inverse_of => :reader + belongs_to :person, inverse_of: :readers + belongs_to :single_person, class_name: "Person", foreign_key: :person_id, inverse_of: :reader belongs_to :first_post, -> { where(id: [2, 3]) } end class SecureReader < ActiveRecord::Base self.table_name = "readers" - belongs_to :secure_post, :class_name => "Post", :foreign_key => "post_id" - belongs_to :secure_person, :inverse_of => :secure_readers, :class_name => "Person", :foreign_key => "person_id" + belongs_to :secure_post, class_name: "Post", foreign_key: "post_id" + belongs_to :secure_person, inverse_of: :secure_readers, class_name: "Person", foreign_key: "person_id" end class LazyReader < ActiveRecord::Base self.table_name = "readers" default_scope -> { where(skimmer: true) } - scope :skimmers_or_not, -> { unscope(:where => :skimmer) } + scope :skimmers_or_not, -> { unscope(where: :skimmer) } belongs_to :post belongs_to :person diff --git a/activerecord/test/models/reference.rb b/activerecord/test/models/reference.rb index 1cf6669dce..e2bb980fed 100644 --- a/activerecord/test/models/reference.rb +++ b/activerecord/test/models/reference.rb @@ -2,7 +2,7 @@ class Reference < ActiveRecord::Base belongs_to :person belongs_to :job - has_many :agents_posts_authors, :through => :person + has_many :agents_posts_authors, through: :person class << self; attr_accessor :make_comments; end self.make_comments = false @@ -18,5 +18,5 @@ def make_comments class BadReference < ActiveRecord::Base self.table_name = "references" - default_scope { where(:favourite => false) } + default_scope { where(favourite: false) } end diff --git a/activerecord/test/models/reply.rb b/activerecord/test/models/reply.rb index 34b60bdef1..a2d169292a 100644 --- a/activerecord/test/models/reply.rb +++ b/activerecord/test/models/reply.rb @@ -1,14 +1,14 @@ require "models/topic" class Reply < Topic - belongs_to :topic, :foreign_key => "parent_id", :counter_cache => true - belongs_to :topic_with_primary_key, :class_name => "Topic", :primary_key => "title", :foreign_key => "parent_title", :counter_cache => "replies_count" - has_many :replies, :class_name => "SillyReply", :dependent => :destroy, :foreign_key => "parent_id" + belongs_to :topic, foreign_key: "parent_id", counter_cache: true + belongs_to :topic_with_primary_key, class_name: "Topic", primary_key: "title", foreign_key: "parent_title", counter_cache: "replies_count" + has_many :replies, class_name: "SillyReply", dependent: :destroy, foreign_key: "parent_id" end class UniqueReply < Reply - belongs_to :topic, :foreign_key => "parent_id", :counter_cache => true - validates_uniqueness_of :content, :scope => "parent_id" + belongs_to :topic, foreign_key: "parent_id", counter_cache: true + validates_uniqueness_of :content, scope: "parent_id" end class SillyUniqueReply < UniqueReply @@ -16,12 +16,12 @@ class SillyUniqueReply < UniqueReply class WrongReply < Reply validate :errors_on_empty_content - validate :title_is_wrong_create, :on => :create + validate :title_is_wrong_create, on: :create validate :check_empty_title - validate :check_content_mismatch, :on => :create - validate :check_wrong_update, :on => :update - validate :check_author_name_is_secret, :on => :special_case + validate :check_content_mismatch, on: :create + validate :check_wrong_update, on: :update + validate :check_author_name_is_secret, on: :special_case def check_empty_title errors[:title] << "Empty" unless attribute_present?("title") @@ -51,11 +51,11 @@ def check_author_name_is_secret end class SillyReply < Reply - belongs_to :reply, :foreign_key => "parent_id", :counter_cache => :replies_count + belongs_to :reply, foreign_key: "parent_id", counter_cache: :replies_count end module Web class Reply < Web::Topic - belongs_to :topic, :foreign_key => "parent_id", :counter_cache => true, :class_name => "Web::Topic" + belongs_to :topic, foreign_key: "parent_id", counter_cache: true, class_name: "Web::Topic" end end diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb index eae360a9eb..77a7b22315 100644 --- a/activerecord/test/models/ship.rb +++ b/activerecord/test/models/ship.rb @@ -2,19 +2,19 @@ class Ship < ActiveRecord::Base self.record_timestamps = false belongs_to :pirate - belongs_to :update_only_pirate, :class_name => "Pirate" + belongs_to :update_only_pirate, class_name: "Pirate" belongs_to :developer, dependent: :destroy - has_many :parts, :class_name => "ShipPart" + has_many :parts, class_name: "ShipPart" has_many :treasures - accepts_nested_attributes_for :parts, :allow_destroy => true - accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc(&:empty?) - accepts_nested_attributes_for :update_only_pirate, :update_only => true + accepts_nested_attributes_for :parts, allow_destroy: true + accepts_nested_attributes_for :pirate, allow_destroy: true, reject_if: proc(&:empty?) + accepts_nested_attributes_for :update_only_pirate, update_only: true validates_presence_of :name attr_accessor :cancel_save_from_callback - before_save :cancel_save_callback_method, :if => :cancel_save_from_callback + before_save :cancel_save_callback_method, if: :cancel_save_from_callback def cancel_save_callback_method throw(:abort) end diff --git a/activerecord/test/models/ship_part.rb b/activerecord/test/models/ship_part.rb index 05c65f8a4a..1a633b8d77 100644 --- a/activerecord/test/models/ship_part.rb +++ b/activerecord/test/models/ship_part.rb @@ -1,7 +1,7 @@ class ShipPart < ActiveRecord::Base belongs_to :ship - has_many :trinkets, :class_name => "Treasure", :as => :looter - accepts_nested_attributes_for :trinkets, :allow_destroy => true + has_many :trinkets, class_name: "Treasure", as: :looter + accepts_nested_attributes_for :trinkets, allow_destroy: true accepts_nested_attributes_for :ship validates_presence_of :name diff --git a/activerecord/test/models/shop.rb b/activerecord/test/models/shop.rb index 607a0a5b41..f9d23d13b0 100644 --- a/activerecord/test/models/shop.rb +++ b/activerecord/test/models/shop.rb @@ -1,10 +1,10 @@ module Shop class Collection < ActiveRecord::Base - has_many :products, :dependent => :nullify + has_many :products, dependent: :nullify end class Product < ActiveRecord::Base - has_many :variants, :dependent => :delete_all + has_many :variants, dependent: :delete_all belongs_to :type class Type < ActiveRecord::Base diff --git a/activerecord/test/models/sponsor.rb b/activerecord/test/models/sponsor.rb index 5f7e47b583..175933ccf1 100644 --- a/activerecord/test/models/sponsor.rb +++ b/activerecord/test/models/sponsor.rb @@ -1,7 +1,7 @@ class Sponsor < ActiveRecord::Base - belongs_to :sponsor_club, :class_name => "Club", :foreign_key => "club_id" - belongs_to :sponsorable, :polymorphic => true - belongs_to :thing, :polymorphic => true, :foreign_type => :sponsorable_type, :foreign_key => :sponsorable_id - belongs_to :sponsorable_with_conditions, -> { where :name => "Ernie"}, :polymorphic => true, - :foreign_type => "sponsorable_type", :foreign_key => "sponsorable_id" + belongs_to :sponsor_club, class_name: "Club", foreign_key: "club_id" + belongs_to :sponsorable, polymorphic: true + belongs_to :thing, polymorphic: true, foreign_type: :sponsorable_type, foreign_key: :sponsorable_id + belongs_to :sponsorable_with_conditions, -> { where name: "Ernie"}, polymorphic: true, + foreign_type: "sponsorable_type", foreign_key: "sponsorable_id" end diff --git a/activerecord/test/models/subscriber.rb b/activerecord/test/models/subscriber.rb index 269da472cf..a820329003 100644 --- a/activerecord/test/models/subscriber.rb +++ b/activerecord/test/models/subscriber.rb @@ -1,7 +1,7 @@ class Subscriber < ActiveRecord::Base self.primary_key = "nick" has_many :subscriptions - has_many :books, :through => :subscriptions + has_many :books, through: :subscriptions end class SpecialSubscriber < Subscriber diff --git a/activerecord/test/models/subscription.rb b/activerecord/test/models/subscription.rb index bcac4738a3..1cedf6deae 100644 --- a/activerecord/test/models/subscription.rb +++ b/activerecord/test/models/subscription.rb @@ -1,4 +1,4 @@ class Subscription < ActiveRecord::Base - belongs_to :subscriber, :counter_cache => :books_count + belongs_to :subscriber, counter_cache: :books_count belongs_to :book end diff --git a/activerecord/test/models/tag.rb b/activerecord/test/models/tag.rb index a49affaf3f..c907aea10f 100644 --- a/activerecord/test/models/tag.rb +++ b/activerecord/test/models/tag.rb @@ -1,9 +1,9 @@ class Tag < ActiveRecord::Base has_many :taggings - has_many :taggables, :through => :taggings + has_many :taggables, through: :taggings has_one :tagging - has_many :tagged_posts, :through => :taggings, :source => "taggable", :source_type => "Post" + has_many :tagged_posts, through: :taggings, source: "taggable", source_type: "Post" end class OrderedTag < Tag diff --git a/activerecord/test/models/tagging.rb b/activerecord/test/models/tagging.rb index 3ab9f50739..f739b4a197 100644 --- a/activerecord/test/models/tagging.rb +++ b/activerecord/test/models/tagging.rb @@ -4,10 +4,10 @@ module Taggable class Tagging < ActiveRecord::Base belongs_to :tag, -> { includes(:tagging) } - belongs_to :super_tag, :class_name => "Tag", :foreign_key => "super_tag_id" - belongs_to :invalid_tag, :class_name => "Tag", :foreign_key => "tag_id" - belongs_to :blue_tag, -> { where :tags => { :name => "Blue" } }, :class_name => "Tag", :foreign_key => :tag_id - belongs_to :tag_with_primary_key, :class_name => "Tag", :foreign_key => :tag_id, :primary_key => :custom_primary_key - belongs_to :taggable, :polymorphic => true, :counter_cache => :tags_count - has_many :things, :through => :taggable + belongs_to :super_tag, class_name: "Tag", foreign_key: "super_tag_id" + belongs_to :invalid_tag, class_name: "Tag", foreign_key: "tag_id" + belongs_to :blue_tag, -> { where tags: { name: "Blue" } }, class_name: "Tag", foreign_key: :tag_id + belongs_to :tag_with_primary_key, class_name: "Tag", foreign_key: :tag_id, primary_key: :custom_primary_key + belongs_to :taggable, polymorphic: true, counter_cache: :tags_count + has_many :things, through: :taggable end diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb index 4e35e458ca..00f89a5364 100644 --- a/activerecord/test/models/topic.rb +++ b/activerecord/test/models/topic.rb @@ -5,15 +5,15 @@ class Topic < ActiveRecord::Base where "written_on < ?", time end } - scope :approved, -> { where(:approved => true) } - scope :rejected, -> { where(:approved => false) } + scope :approved, -> { where(approved: true) } + scope :rejected, -> { where(approved: false) } scope :scope_with_lambda, lambda { all } - scope :by_lifo, -> { where(:author_name => "lifo") } + scope :by_lifo, -> { where(author_name: "lifo") } scope :replied, -> { where "replies_count > 0" } - scope "approved_as_string", -> { where(:approved => true) } + scope "approved_as_string", -> { where(approved: true) } scope :anonymous_extension, -> { all } do def one 1 @@ -22,7 +22,7 @@ def one scope :with_object, Class.new(Struct.new(:klass)) { def call - klass.where(:approved => true) + klass.where(approved: true) end }.new(self) @@ -35,8 +35,8 @@ def two has_many :replies, dependent: :destroy, foreign_key: "parent_id", autosave: true has_many :approved_replies, -> { approved }, class_name: "Reply", foreign_key: "parent_id", counter_cache: "replies_count" - has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id" - has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id" + has_many :unique_replies, dependent: :destroy, foreign_key: "parent_id" + has_many :silly_unique_replies, dependent: :destroy, foreign_key: "parent_id" serialize :content @@ -113,6 +113,6 @@ def blank? module Web class Topic < ActiveRecord::Base - has_many :replies, :dependent => :destroy, :foreign_key => "parent_id", :class_name => "Web::Reply" + has_many :replies, dependent: :destroy, foreign_key: "parent_id", class_name: "Web::Reply" end end diff --git a/activerecord/test/models/treasure.rb b/activerecord/test/models/treasure.rb index 04c3ef662c..fb2a5d44e2 100644 --- a/activerecord/test/models/treasure.rb +++ b/activerecord/test/models/treasure.rb @@ -1,10 +1,10 @@ class Treasure < ActiveRecord::Base has_and_belongs_to_many :parrots - belongs_to :looter, :polymorphic => true + belongs_to :looter, polymorphic: true # No counter_cache option given belongs_to :ship - has_many :price_estimates, :as => :estimate_of + has_many :price_estimates, as: :estimate_of has_and_belongs_to_many :rich_people, join_table: "peoples_treasures", validate: false accepts_nested_attributes_for :looter diff --git a/activerecord/test/models/vegetables.rb b/activerecord/test/models/vegetables.rb index 5f6a17dbb3..ef310d2359 100644 --- a/activerecord/test/models/vegetables.rb +++ b/activerecord/test/models/vegetables.rb @@ -20,5 +20,5 @@ class KingCole < GreenCabbage end class RedCabbage < Cabbage - belongs_to :seller, :class_name => "Company" + belongs_to :seller, class_name: "Company" end diff --git a/activerecord/test/models/vertex.rb b/activerecord/test/models/vertex.rb index cd0ac92236..3d19433b6f 100644 --- a/activerecord/test/models/vertex.rb +++ b/activerecord/test/models/vertex.rb @@ -1,9 +1,9 @@ # This class models a vertex in a directed graph. class Vertex < ActiveRecord::Base - has_many :sink_edges, :class_name => "Edge", :foreign_key => "source_id" - has_many :sinks, :through => :sink_edges + has_many :sink_edges, class_name: "Edge", foreign_key: "source_id" + has_many :sinks, through: :sink_edges has_and_belongs_to_many :sources, - :class_name => "Vertex", :join_table => "edges", - :foreign_key => "sink_id", :association_foreign_key => "source_id" + class_name: "Vertex", join_table: "edges", + foreign_key: "sink_id", association_foreign_key: "source_id" end diff --git a/activerecord/test/models/wheel.rb b/activerecord/test/models/wheel.rb index 26868bce5e..cba2b3e518 100644 --- a/activerecord/test/models/wheel.rb +++ b/activerecord/test/models/wheel.rb @@ -1,3 +1,3 @@ class Wheel < ActiveRecord::Base - belongs_to :wheelable, :polymorphic => true, :counter_cache => true + belongs_to :wheelable, polymorphic: true, counter_cache: true end diff --git a/activerecord/test/models/without_table.rb b/activerecord/test/models/without_table.rb index 50c824e4ac..7c0fc286e1 100644 --- a/activerecord/test/models/without_table.rb +++ b/activerecord/test/models/without_table.rb @@ -1,3 +1,3 @@ class WithoutTable < ActiveRecord::Base - default_scope -> { where(:published => true) } + default_scope -> { where(published: true) } end diff --git a/activerecord/test/models/zine.rb b/activerecord/test/models/zine.rb index c2d0fdaf25..3f2b348b46 100644 --- a/activerecord/test/models/zine.rb +++ b/activerecord/test/models/zine.rb @@ -1,3 +1,3 @@ class Zine < ActiveRecord::Base - has_many :interests, :inverse_of => :zine + has_many :interests, inverse_of: :zine end