diff options
author | Xavier Noria <fxn@hashref.com> | 2016-08-06 18:24:04 +0200 |
---|---|---|
committer | Xavier Noria <fxn@hashref.com> | 2016-08-06 18:26:45 +0200 |
commit | 4df2b779ddfcb27761c71e00e2b241bfa06a0950 (patch) | |
tree | 7a83cce62195f7b20afea6d6a8873b953d25cb84 /activerecord | |
parent | a731125f12c5834de7eae3455fad63ea4d348034 (diff) | |
download | rails-4df2b779ddfcb27761c71e00e2b241bfa06a0950.tar.gz rails-4df2b779ddfcb27761c71e00e2b241bfa06a0950.tar.bz2 rails-4df2b779ddfcb27761c71e00e2b241bfa06a0950.zip |
applies new string literal convention in activerecord/lib
The current code base is not uniform. After some discussion,
we have chosen to go with double quotes by default.
Diffstat (limited to 'activerecord')
118 files changed, 840 insertions, 840 deletions
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index baa497dc98..fb7b8df01d 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -21,13 +21,13 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ -require 'active_support' -require 'active_support/rails' -require 'active_model' -require 'arel' +require "active_support" +require "active_support/rails" +require "active_model" +require "arel" -require 'active_record/version' -require 'active_record/attribute_set' +require "active_record/version" +require "active_record/attribute_set" module ActiveRecord extend ActiveSupport::Autoload @@ -46,7 +46,7 @@ module ActiveRecord autoload :Integration autoload :LegacyYamlAdapter autoload :Migration - autoload :Migrator, 'active_record/migration' + autoload :Migrator, "active_record/migration" autoload :ModelSchema autoload :NestedAttributes autoload :NoTouching @@ -56,7 +56,7 @@ module ActiveRecord autoload :Querying autoload :CollectionCacheKey autoload :ReadonlyAttributes - autoload :RecordInvalid, 'active_record/validations' + autoload :RecordInvalid, "active_record/validations" autoload :Reflection autoload :RuntimeRegistry autoload :Sanitization @@ -76,9 +76,9 @@ module ActiveRecord autoload :SecureToken eager_autoload do - autoload :ActiveRecordError, 'active_record/errors' - autoload :ConnectionNotEstablished, 'active_record/errors' - autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter' + autoload :ActiveRecordError, "active_record/errors" + autoload :ConnectionNotEstablished, "active_record/errors" + autoload :ConnectionAdapters, "active_record/connection_adapters/abstract_adapter" autoload :Aggregations autoload :Associations @@ -90,7 +90,7 @@ module ActiveRecord autoload :AssociationRelation autoload :NullRelation - autoload_under 'relation' do + autoload_under "relation" do autoload :QueryMethods autoload :FinderMethods autoload :Calculations @@ -104,8 +104,8 @@ module ActiveRecord end module Coders - autoload :YAMLColumn, 'active_record/coders/yaml_column' - autoload :JSON, 'active_record/coders/json' + autoload :YAMLColumn, "active_record/coders/yaml_column" + autoload :JSON, "active_record/coders/json" end module AttributeMethods @@ -153,13 +153,13 @@ module ActiveRecord extend ActiveSupport::Autoload autoload :DatabaseTasks - autoload :SQLiteDatabaseTasks, 'active_record/tasks/sqlite_database_tasks' - autoload :MySQLDatabaseTasks, 'active_record/tasks/mysql_database_tasks' + autoload :SQLiteDatabaseTasks, "active_record/tasks/sqlite_database_tasks" + autoload :MySQLDatabaseTasks, "active_record/tasks/mysql_database_tasks" autoload :PostgreSQLDatabaseTasks, - 'active_record/tasks/postgresql_database_tasks' + "active_record/tasks/postgresql_database_tasks" end - autoload :TestFixtures, 'active_record/fixtures' + autoload :TestFixtures, "active_record/fixtures" def self.eager_load! super @@ -176,5 +176,5 @@ ActiveSupport.on_load(:active_record) do end ActiveSupport.on_load(:i18n) do - I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml' + I18n.load_path << File.dirname(__FILE__) + "/active_record/locale/en.yml" end diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index c91b5d3fe3..61a26cf914 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1,7 +1,7 @@ -require 'active_support/core_ext/enumerable' -require 'active_support/core_ext/string/conversions' -require 'active_support/core_ext/module/remove_method' -require 'active_record/errors' +require "active_support/core_ext/enumerable" +require "active_support/core_ext/string/conversions" +require "active_support/core_ext/module/remove_method" +require "active_record/errors" module ActiveRecord class AssociationNotFoundError < ConfigurationError #:nodoc: @@ -207,14 +207,14 @@ module ActiveRecord autoload :ThroughAssociation module Builder #:nodoc: - autoload :Association, 'active_record/associations/builder/association' - autoload :SingularAssociation, 'active_record/associations/builder/singular_association' - autoload :CollectionAssociation, 'active_record/associations/builder/collection_association' + autoload :Association, "active_record/associations/builder/association" + autoload :SingularAssociation, "active_record/associations/builder/singular_association" + autoload :CollectionAssociation, "active_record/associations/builder/collection_association" - autoload :BelongsTo, 'active_record/associations/builder/belongs_to' - autoload :HasOne, 'active_record/associations/builder/has_one' - autoload :HasMany, 'active_record/associations/builder/has_many' - autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many' + autoload :BelongsTo, "active_record/associations/builder/belongs_to" + autoload :HasOne, "active_record/associations/builder/has_one" + autoload :HasMany, "active_record/associations/builder/has_many" + autoload :HasAndBelongsToMany, "active_record/associations/builder/has_and_belongs_to_many" end eager_autoload do diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb index 021bc32237..3963008a76 100644 --- a/activerecord/lib/active_record/associations/alias_tracker.rb +++ b/activerecord/lib/active_record/associations/alias_tracker.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/string/conversions' +require "active_support/core_ext/string/conversions" module ActiveRecord module Associations diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index 62e867a353..74803d0ad5 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/array/wrap' +require "active_support/core_ext/array/wrap" module ActiveRecord module Associations diff --git a/activerecord/lib/active_record/associations/builder/collection_association.rb b/activerecord/lib/active_record/associations/builder/collection_association.rb index f25bd7ca9f..6857929d61 100644 --- a/activerecord/lib/active_record/associations/builder/collection_association.rb +++ b/activerecord/lib/active_record/associations/builder/collection_association.rb @@ -1,6 +1,6 @@ # This class is inherited by the has_many and has_many_and_belongs_to_many association classes -require 'active_record/associations' +require "active_record/associations" module ActiveRecord::Associations::Builder # :nodoc: class CollectionAssociation < Association #:nodoc: diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index dd5fd607a2..33c8d4b8d6 100644 --- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb @@ -94,7 +94,7 @@ module ActiveRecord::Associations::Builder # :nodoc: def middle_reflection(join_model) middle_name = [lhs_model.name.downcase.pluralize, - association_name].join('_'.freeze).gsub('::'.freeze, '_'.freeze).to_sym + association_name].join("_".freeze).gsub("::".freeze, "_".freeze).to_sym middle_options = middle_options join_model HasMany.create_reflection(lhs_model, 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 ddd0b59cc1..67510f18d4 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -146,7 +146,7 @@ module ActiveRecord stmt.from scope.klass.arel_table stmt.wheres = arel.constraints - count = scope.klass.connection.delete(stmt, 'SQL', scope.bound_attributes) + count = scope.klass.connection.delete(stmt, "SQL", scope.bound_attributes) end when :nullify count = scope.update_all(source_reflection.foreign_key => nil) diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index 491152bbcb..0f9ad77405 100644 --- a/activerecord/lib/active_record/associations/join_dependency.rb +++ b/activerecord/lib/active_record/associations/join_dependency.rb @@ -1,8 +1,8 @@ module ActiveRecord module Associations class JoinDependency # :nodoc: - autoload :JoinBase, 'active_record/associations/join_dependency/join_base' - autoload :JoinAssociation, 'active_record/associations/join_dependency/join_association' + autoload :JoinBase, "active_record/associations/join_dependency/join_base" + autoload :JoinAssociation, "active_record/associations/join_dependency/join_association" class Aliases # :nodoc: def initialize(tables) @@ -154,7 +154,7 @@ module ActiveRecord class_name: join_root.base_klass.name } - message_bus.instrument('instantiation.active_record', payload) do + message_bus.instrument("instantiation.active_record", payload) do result_set.each { |row_hash| parent_key = primary_key ? row_hash[primary_key] : row_hash parent = parents[parent_key] ||= join_root.instantiate(row_hash, column_aliases) diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb index bdf77009eb..a5705951f3 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb @@ -1,4 +1,4 @@ -require 'active_record/associations/join_dependency/join_part' +require "active_record/associations/join_dependency/join_part" module ActiveRecord module Associations diff --git a/activerecord/lib/active_record/associations/join_dependency/join_base.rb b/activerecord/lib/active_record/associations/join_dependency/join_base.rb index 3a26c25737..fca20514d1 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_base.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_base.rb @@ -1,4 +1,4 @@ -require 'active_record/associations/join_dependency/join_part' +require "active_record/associations/join_dependency/join_part" module ActiveRecord module Associations diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb index e64af84e1a..320d9dc952 100644 --- a/activerecord/lib/active_record/associations/preloader.rb +++ b/activerecord/lib/active_record/associations/preloader.rb @@ -42,16 +42,16 @@ module ActiveRecord extend ActiveSupport::Autoload eager_autoload do - autoload :Association, 'active_record/associations/preloader/association' - autoload :SingularAssociation, 'active_record/associations/preloader/singular_association' - autoload :CollectionAssociation, 'active_record/associations/preloader/collection_association' - autoload :ThroughAssociation, 'active_record/associations/preloader/through_association' - - autoload :HasMany, 'active_record/associations/preloader/has_many' - autoload :HasManyThrough, 'active_record/associations/preloader/has_many_through' - autoload :HasOne, 'active_record/associations/preloader/has_one' - autoload :HasOneThrough, 'active_record/associations/preloader/has_one_through' - autoload :BelongsTo, 'active_record/associations/preloader/belongs_to' + autoload :Association, "active_record/associations/preloader/association" + autoload :SingularAssociation, "active_record/associations/preloader/singular_association" + autoload :CollectionAssociation, "active_record/associations/preloader/collection_association" + autoload :ThroughAssociation, "active_record/associations/preloader/through_association" + + autoload :HasMany, "active_record/associations/preloader/has_many" + autoload :HasManyThrough, "active_record/associations/preloader/has_many_through" + autoload :HasOne, "active_record/associations/preloader/has_one" + autoload :HasOneThrough, "active_record/associations/preloader/has_one_through" + autoload :BelongsTo, "active_record/associations/preloader/belongs_to" end NULL_RELATION = Struct.new(:values, :where_clause, :joins_values).new({}, Relation::WhereClause.empty, []) diff --git a/activerecord/lib/active_record/attribute/user_provided_default.rb b/activerecord/lib/active_record/attribute/user_provided_default.rb index 4580813364..32b9c289bb 100644 --- a/activerecord/lib/active_record/attribute/user_provided_default.rb +++ b/activerecord/lib/active_record/attribute/user_provided_default.rb @@ -1,4 +1,4 @@ -require 'active_record/attribute' +require "active_record/attribute" module ActiveRecord class Attribute # :nodoc: diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb index b96d8e9352..1cccb0852e 100644 --- a/activerecord/lib/active_record/attribute_assignment.rb +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -1,4 +1,4 @@ -require 'active_model/forbidden_attributes_protection' +require "active_model/forbidden_attributes_protection" module ActiveRecord module AttributeAssignment diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index eadd73aab0..12699bb30b 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -1,7 +1,7 @@ -require 'active_support/core_ext/enumerable' -require 'active_support/core_ext/string/filters' -require 'mutex_m' -require 'concurrent/map' +require "active_support/core_ext/enumerable" +require "active_support/core_ext/string/filters" +require "mutex_m" +require "concurrent/map" module ActiveRecord # = Active Record Attribute Methods @@ -148,7 +148,7 @@ module ActiveRecord # Person.attribute_method?(:age=) # => true # Person.attribute_method?(:nothing) # => false def attribute_method?(attribute) - super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, ''))) + super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, ""))) end # Returns an array of column names as strings if it's not an abstract class and diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 0bcfa5f00d..50d7e1df7a 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -1,5 +1,5 @@ -require 'active_support/core_ext/module/attribute_accessors' -require 'active_record/attribute_mutation_tracker' +require "active_support/core_ext/module/attribute_accessors" +require "active_record/attribute_mutation_tracker" module ActiveRecord module AttributeMethods diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index d28edfb003..162a564a49 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -1,4 +1,4 @@ -require 'set' +require "set" module ActiveRecord module AttributeMethods @@ -48,14 +48,14 @@ module ActiveRecord protected def attribute_method?(attr_name) - attr_name == 'id' || super + attr_name == "id" || super end module ClassMethods def define_method_attribute(attr_name) super - if attr_name == primary_key && attr_name != 'id' + if attr_name == primary_key && attr_name != "id" generated_attribute_methods.send(:alias_method, :id, primary_key) end end @@ -98,7 +98,7 @@ module ActiveRecord pk = connection.schema_cache.primary_keys(table_name) suppress_composite_primary_key(pk) else - 'id' + "id" end end end diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index ab2ecaa7c5..a7310130fe 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -25,7 +25,7 @@ module ActiveRecord # Making it frozen means that it doesn't get duped when used to # key the @attributes in read_attribute. def define_method_attribute(name) - safe_name = name.unpack('h*'.freeze).first + safe_name = name.unpack("h*".freeze).first temp_method = "__temp__#{safe_name}" ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name @@ -49,7 +49,7 @@ module ActiveRecord # to a date object, like Date.new(2004, 12, 12)). def read_attribute(attr_name, &block) name = attr_name.to_s - name = self.class.primary_key if name == 'id'.freeze + name = self.class.primary_key if name == "id".freeze _read_attribute(name, &block) end diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb index cbb4f0cff8..d7b5f8b262 100644 --- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb +++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/string/strip' +require "active_support/core_ext/string/strip" module ActiveRecord module AttributeMethods diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb index 70c2d2f25d..e7f62197c3 100644 --- a/activerecord/lib/active_record/attribute_methods/write.rb +++ b/activerecord/lib/active_record/attribute_methods/write.rb @@ -11,7 +11,7 @@ module ActiveRecord protected def define_method_attribute=(name) - safe_name = name.unpack('h*'.freeze).first + safe_name = name.unpack("h*".freeze).first ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 @@ -44,7 +44,7 @@ module ActiveRecord def write_attribute_with_type_cast(attr_name, value, should_type_cast) attr_name = attr_name.to_s - attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key + attr_name = self.class.primary_key if attr_name == "id" && self.class.primary_key if should_type_cast @attributes.write_from_user(attr_name, value) diff --git a/activerecord/lib/active_record/attribute_set.rb b/activerecord/lib/active_record/attribute_set.rb index f868f23845..fd569d869a 100644 --- a/activerecord/lib/active_record/attribute_set.rb +++ b/activerecord/lib/active_record/attribute_set.rb @@ -1,5 +1,5 @@ -require 'active_record/attribute_set/builder' -require 'active_record/attribute_set/yaml_encoder' +require "active_record/attribute_set/builder" +require "active_record/attribute_set/yaml_encoder" module ActiveRecord class AttributeSet # :nodoc: diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index 4ffd39d82d..b4d98ca3c0 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -1,4 +1,4 @@ -require 'active_record/attribute' +require "active_record/attribute" module ActiveRecord class AttributeSet # :nodoc: diff --git a/activerecord/lib/active_record/attribute_set/yaml_encoder.rb b/activerecord/lib/active_record/attribute_set/yaml_encoder.rb index f9d527a5a3..52ffe719f4 100644 --- a/activerecord/lib/active_record/attribute_set/yaml_encoder.rb +++ b/activerecord/lib/active_record/attribute_set/yaml_encoder.rb @@ -8,7 +8,7 @@ module ActiveRecord end def encode(attribute_set, coder) - coder['concise_attributes'] = attribute_set.each_value.map do |attr| + coder["concise_attributes"] = attribute_set.each_value.map do |attr| if attr.type.equal?(default_types[attr.name]) attr.with_type(nil) else @@ -18,10 +18,10 @@ module ActiveRecord end def decode(coder) - if coder['attributes'] - coder['attributes'] + if coder["attributes"] + coder["attributes"] else - attributes_hash = Hash[coder['concise_attributes'].map do |attr| + attributes_hash = Hash[coder["concise_attributes"].map do |attr| if attr.type.nil? attr = attr.with_type(default_types[attr.name]) end diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index ed0302e763..880d9a2b84 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -1,4 +1,4 @@ -require 'active_record/attribute/user_provided_default' +require "active_record/attribute/user_provided_default" module ActiveRecord # See ActiveRecord::Attributes::ClassMethods for documentation diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 6a1a27ce41..01d7886406 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1,25 +1,25 @@ -require 'yaml' -require 'active_support/benchmarkable' -require 'active_support/dependencies' -require 'active_support/descendants_tracker' -require 'active_support/time' -require 'active_support/core_ext/module/attribute_accessors' -require 'active_support/core_ext/array/extract_options' -require 'active_support/core_ext/hash/deep_merge' -require 'active_support/core_ext/hash/slice' -require 'active_support/core_ext/hash/transform_values' -require 'active_support/core_ext/string/behavior' -require 'active_support/core_ext/kernel/singleton_class' -require 'active_support/core_ext/module/introspection' -require 'active_support/core_ext/object/duplicable' -require 'active_support/core_ext/class/subclasses' -require 'active_record/attribute_decorators' -require 'active_record/errors' -require 'active_record/log_subscriber' -require 'active_record/explain_subscriber' -require 'active_record/relation/delegation' -require 'active_record/attributes' -require 'active_record/type_caster' +require "yaml" +require "active_support/benchmarkable" +require "active_support/dependencies" +require "active_support/descendants_tracker" +require "active_support/time" +require "active_support/core_ext/module/attribute_accessors" +require "active_support/core_ext/array/extract_options" +require "active_support/core_ext/hash/deep_merge" +require "active_support/core_ext/hash/slice" +require "active_support/core_ext/hash/transform_values" +require "active_support/core_ext/string/behavior" +require "active_support/core_ext/kernel/singleton_class" +require "active_support/core_ext/module/introspection" +require "active_support/core_ext/object/duplicable" +require "active_support/core_ext/class/subclasses" +require "active_record/attribute_decorators" +require "active_record/errors" +require "active_record/log_subscriber" +require "active_record/explain_subscriber" +require "active_record/relation/delegation" +require "active_record/attributes" +require "active_record/type_caster" module ActiveRecord #:nodoc: # = Active Record diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb index 5ac1e0c001..8b98d9ccd7 100644 --- a/activerecord/lib/active_record/coders/yaml_column.rb +++ b/activerecord/lib/active_record/coders/yaml_column.rb @@ -1,5 +1,5 @@ -require 'yaml' -require 'active_support/core_ext/regexp' +require "yaml" +require "active_support/core_ext/regexp" module ActiveRecord module Coders # :nodoc: 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 526adc9efe..198a169df2 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -1,6 +1,6 @@ -require 'thread' -require 'concurrent/map' -require 'monitor' +require "thread" +require "concurrent/map" +require "monitor" module ActiveRecord # Raised when a connection could not be obtained within the connection @@ -197,7 +197,7 @@ module ActiveRecord elapsed = Time.now - t0 if elapsed >= timeout - msg = 'could not obtain a connection from the pool within %0.3f seconds (waited %0.3f seconds); all pooled connections were in use' % + msg = "could not obtain a connection from the pool within %0.3f seconds (waited %0.3f seconds); all pooled connections were in use" % [timeout, elapsed] raise ConnectionTimeoutError, msg end @@ -858,7 +858,7 @@ module ActiveRecord payload[:config] = spec.config end - message_bus.instrument('!connection.active_record', payload) do + message_bus.instrument("!connection.active_record", payload) do owner_to_pool[spec.name] = ConnectionAdapters::ConnectionPool.new(spec) end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index c2d02a6cc2..452e78a40b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -82,7 +82,7 @@ module ActiveRecord # Executes +sql+ statement in the context of this connection using # +binds+ as the bind substitutes. +name+ is logged along with # the executed +sql+ statement. - def exec_query(sql, name = 'SQL', binds = [], prepare: false) + def exec_query(sql, name = "SQL", binds = [], prepare: false) raise NotImplementedError end @@ -324,7 +324,7 @@ module ActiveRecord end end - execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert' + execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", "Fixture Insert" end def empty_insert_statement_value @@ -343,8 +343,8 @@ module ActiveRecord def sanitize_limit(limit) if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral) limit - elsif limit.to_s.include?(',') - Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',') + elsif limit.to_s.include?(",") + Arel.sql limit.to_s.split(",").map{ |i| Integer(i) }.join(",") else Integer(limit) end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb index eda6af08e3..20d009bbf8 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/big_decimal/conversions' +require "active_support/core_ext/big_decimal/conversions" module ActiveRecord module ConnectionAdapters # :nodoc: @@ -116,7 +116,7 @@ module ActiveRecord end def unquoted_true - 't'.freeze + "t".freeze end def quoted_false @@ -124,7 +124,7 @@ module ActiveRecord end def unquoted_false - 'f'.freeze + "f".freeze end # Quote date/time values for use in SQL input. Includes microseconds @@ -147,7 +147,7 @@ module ActiveRecord end def quoted_time(value) # :nodoc: - quoted_date(value).sub(/\A2000-01-01 /, '') + quoted_date(value).sub(/\A2000-01-01 /, "") end private @@ -168,7 +168,7 @@ module ActiveRecord when false then quoted_false when nil then "NULL" # BigDecimals need to be put in a non-normalized form and quoted. - when BigDecimal then value.to_s('F') + when BigDecimal then value.to_s("F") when Numeric, ActiveSupport::Duration then value.to_s when Type::Time::Value then "'#{quoted_time(value)}'" when Date, Time then "'#{quoted_date(value)}'" @@ -185,7 +185,7 @@ module ActiveRecord when true then unquoted_true when false then unquoted_false # BigDecimals need to be put in a non-normalized form and quoted. - when BigDecimal then value.to_s('F') + when BigDecimal then value.to_s("F") when Type::Time::Value then quoted_time(value) when Date, Time then quoted_date(value) when *types_which_need_no_typecasting diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb index 6add697eeb..322684672f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/string/strip' +require "active_support/core_ext/string/strip" module ActiveRecord module ConnectionAdapters @@ -23,9 +23,9 @@ module ActiveRecord def visit_AlterTable(o) sql = "ALTER TABLE #{quote_table_name(o.name)} " - sql << o.adds.map { |col| accept col }.join(' ') - sql << o.foreign_key_adds.map { |fk| visit_AddForeignKey fk }.join(' ') - sql << o.foreign_key_drops.map { |fk| visit_DropForeignKey fk }.join(' ') + sql << o.adds.map { |col| accept col }.join(" ") + sql << o.foreign_key_adds.map { |fk| visit_AddForeignKey fk }.join(" ") + sql << o.foreign_key_drops.map { |fk| visit_DropForeignKey fk }.join(" ") end def visit_ColumnDefinition(o) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 8dbafc5a4b..c1fc99ce1f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -388,7 +388,7 @@ module ActiveRecord end def aliased_types(name, fallback) - 'timestamp' == name ? :datetime : fallback + "timestamp" == name ? :datetime : fallback end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb index 677a4c6bd0..321e08c5ca 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb @@ -40,7 +40,7 @@ module ActiveRecord default = schema_default(column) if column.has_default? spec[:default] = default unless default.nil? - spec[:null] = 'false' unless column.null + spec[:null] = "false" unless column.null if collation = schema_collation(column) spec[:collation] = collation 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 19c265db6e..77e97a6d1b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -1,6 +1,6 @@ -require 'active_record/migration/join_table' -require 'active_support/core_ext/string/access' -require 'digest' +require "active_record/migration/join_table" +require "active_support/core_ext/string/access" +require "digest" module ActiveRecord module ConnectionAdapters # :nodoc: @@ -25,7 +25,7 @@ module ActiveRecord # Truncates a table alias according to the limits of the current adapter. def table_alias_for(table_name) - table_name[0...table_alias_length].tr('.', '_') + table_name[0...table_alias_length].tr(".", "_") end # Returns the relation names useable to back Active Record models. @@ -985,7 +985,7 @@ module ActiveRecord end def dump_schema_information #:nodoc: - versions = ActiveRecord::SchemaMigration.order('version').pluck(:version) + versions = ActiveRecord::SchemaMigration.order("version").pluck(:version) insert_versions_sql(versions) end @@ -1026,7 +1026,7 @@ module ActiveRecord migrated = select_values("SELECT version FROM #{sm_table}").map(&:to_i) paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" } versions = Dir[*paths].map do |filename| - filename.split('/').last.split('_').first.to_i + filename.split("/").last.split("_").first.to_i end unless migrated.include?(version) @@ -1178,7 +1178,7 @@ module ActiveRecord def quoted_columns_for_index(column_names, options = {}) return [column_names] if column_names.is_a?(String) - option_strings = Hash[column_names.map {|name| [name, '']}] + option_strings = Hash[column_names.map {|name| [name, ""]}] # add index sort order if supported if supports_index_sort_order? @@ -1205,7 +1205,7 @@ module ActiveRecord end if column_names.any? - checks << lambda { |i| i.columns.join('_and_') == column_names.join('_and_') } + checks << lambda { |i| i.columns.join("_and_") == column_names.join("_and_") } end raise ArgumentError "No name or columns specified" if checks.none? @@ -1255,7 +1255,7 @@ module ActiveRecord def index_name_options(column_names) # :nodoc: if column_names.is_a?(String) - column_names = column_names.scan(/\w+/).join('_') + column_names = column_names.scan(/\w+/).join("_") end { column: column_names } diff --git a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb index ca795cb1ad..d6b03e1eb1 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb @@ -195,7 +195,7 @@ module ActiveRecord raise ensure unless error - if Thread.current.status == 'aborting' + if Thread.current.status == "aborting" rollback_transaction if transaction else begin diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 0b8bacff4e..7ba3b5f43b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -1,11 +1,11 @@ -require 'active_record/type' -require 'active_record/connection_adapters/determine_if_preparable_visitor' -require 'active_record/connection_adapters/schema_cache' -require 'active_record/connection_adapters/sql_type_metadata' -require 'active_record/connection_adapters/abstract/schema_dumper' -require 'active_record/connection_adapters/abstract/schema_creation' -require 'arel/collectors/bind' -require 'arel/collectors/sql_string' +require "active_record/type" +require "active_record/connection_adapters/determine_if_preparable_visitor" +require "active_record/connection_adapters/schema_cache" +require "active_record/connection_adapters/sql_type_metadata" +require "active_record/connection_adapters/abstract/schema_dumper" +require "active_record/connection_adapters/abstract/schema_creation" +require "arel/collectors/bind" +require "arel/collectors/sql_string" module ActiveRecord module ConnectionAdapters # :nodoc: @@ -14,7 +14,7 @@ module ActiveRecord autoload :Column autoload :ConnectionSpecification - autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do + autoload_at "active_record/connection_adapters/abstract/schema_definitions" do autoload :IndexDefinition autoload :ColumnDefinition autoload :ChangeColumnDefinition @@ -25,11 +25,11 @@ module ActiveRecord autoload :ReferenceDefinition end - autoload_at 'active_record/connection_adapters/abstract/connection_pool' do + autoload_at "active_record/connection_adapters/abstract/connection_pool" do autoload :ConnectionHandler end - autoload_under 'abstract' do + autoload_under "abstract" do autoload :SchemaStatements autoload :DatabaseStatements autoload :DatabaseLimits @@ -39,7 +39,7 @@ module ActiveRecord autoload :Savepoints end - autoload_at 'active_record/connection_adapters/abstract/transaction' do + autoload_at "active_record/connection_adapters/abstract/transaction" do autoload :TransactionManager autoload :NullTransaction autoload :RealTransaction @@ -61,7 +61,7 @@ module ActiveRecord # Most of the methods in the adapter are useful during migrations. Most # notably, the instance methods provided by SchemaStatements are very useful. class AbstractAdapter - ADAPTER_NAME = 'Abstract'.freeze + ADAPTER_NAME = "Abstract".freeze include Quoting, DatabaseStatements, SchemaStatements include DatabaseLimits include QueryCache @@ -120,11 +120,11 @@ module ActiveRecord include Comparable def initialize(version_string) - @version = version_string.split('.').map(&:to_i) + @version = version_string.split(".").map(&:to_i) end def <=>(version_string) - @version <=> version_string.split('.').map(&:to_i) + @version <=> version_string.split(".").map(&:to_i) end end @@ -164,9 +164,9 @@ module ActiveRecord # this method must only be called while holding connection pool's mutex def lease if in_use? - msg = 'Cannot lease connection, ' + msg = "Cannot lease connection, " if @owner == Thread.current - msg << 'it is already leased by the current thread.' + msg << "it is already leased by the current thread." else msg << "it is already in use by a different thread: #{@owner}. " << "Current thread: #{Thread.current}." @@ -193,7 +193,7 @@ module ActiveRecord @owner = nil else - raise ActiveRecordError, 'Cannot expire connection, it is not currently leased.' + raise ActiveRecordError, "Cannot expire connection, it is not currently leased." end end @@ -206,7 +206,7 @@ module ActiveRecord @owner = Thread.current end else - raise ActiveRecordError, 'Cannot steal connection, it is not currently leased.' + raise ActiveRecordError, "Cannot steal connection, it is not currently leased." end end @@ -508,12 +508,12 @@ module ActiveRecord register_class_with_limit m, %r(float)i, Type::Float register_class_with_limit m, %r(int)i, Type::Integer - m.alias_type %r(blob)i, 'binary' - m.alias_type %r(clob)i, 'text' - m.alias_type %r(timestamp)i, 'datetime' - m.alias_type %r(numeric)i, 'decimal' - m.alias_type %r(number)i, 'decimal' - m.alias_type %r(double)i, 'float' + m.alias_type %r(blob)i, "binary" + m.alias_type %r(clob)i, "text" + m.alias_type %r(timestamp)i, "datetime" + m.alias_type %r(numeric)i, "decimal" + m.alias_type %r(number)i, "decimal" + m.alias_type %r(double)i, "float" m.register_type(%r(decimal)i) do |sql_type| scale = extract_scale(sql_type) 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 5e9705e02f..ee86e6e128 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -1,15 +1,15 @@ -require 'active_record/connection_adapters/abstract_adapter' -require 'active_record/connection_adapters/statement_pool' -require 'active_record/connection_adapters/mysql/column' -require 'active_record/connection_adapters/mysql/explain_pretty_printer' -require 'active_record/connection_adapters/mysql/quoting' -require 'active_record/connection_adapters/mysql/schema_creation' -require 'active_record/connection_adapters/mysql/schema_definitions' -require 'active_record/connection_adapters/mysql/schema_dumper' -require 'active_record/connection_adapters/mysql/type_metadata' - -require 'active_support/core_ext/string/strip' -require 'active_support/core_ext/regexp' +require "active_record/connection_adapters/abstract_adapter" +require "active_record/connection_adapters/statement_pool" +require "active_record/connection_adapters/mysql/column" +require "active_record/connection_adapters/mysql/explain_pretty_printer" +require "active_record/connection_adapters/mysql/quoting" +require "active_record/connection_adapters/mysql/schema_creation" +require "active_record/connection_adapters/mysql/schema_definitions" +require "active_record/connection_adapters/mysql/schema_dumper" +require "active_record/connection_adapters/mysql/type_metadata" + +require "active_support/core_ext/string/strip" +require "active_support/core_ext/regexp" module ActiveRecord module ConnectionAdapters @@ -68,16 +68,16 @@ module ActiveRecord @statements = StatementPool.new(self.class.type_cast_config_to_integer(config[:statement_limit])) - if version < '5.0.0' + if version < "5.0.0" raise "Your version of MySQL (#{full_version.match(/^\d+\.\d+\.\d+/)[0]}) is too old. Active Record supports MySQL >= 5.0." end end - CHARSETS_OF_4BYTES_MAXLEN = ['utf8mb4', 'utf16', 'utf16le', 'utf32'] + CHARSETS_OF_4BYTES_MAXLEN = ["utf8mb4", "utf16", "utf16le", "utf32"] def internal_string_options_for_primary_key # :nodoc: super.tap { |options| - options[:collation] = collation.sub(/\A[^_]+/, 'utf8') if CHARSETS_OF_4BYTES_MAXLEN.include?(charset) + options[:collation] = collation.sub(/\A[^_]+/, "utf8") if CHARSETS_OF_4BYTES_MAXLEN.include?(charset) } end @@ -136,9 +136,9 @@ module ActiveRecord def supports_datetime_with_precision? if mariadb? - version >= '5.3.0' + version >= "5.3.0" else - version >= '5.6.4' + version >= "5.6.4" end end @@ -159,7 +159,7 @@ module ActiveRecord end def index_algorithms - { default: 'ALGORITHM = DEFAULT', copy: 'ALGORITHM = COPY', inplace: 'ALGORITHM = INPLACE' } + { default: "ALGORITHM = DEFAULT", copy: "ALGORITHM = COPY", inplace: "ALGORITHM = INPLACE" } end # HELPER METHODS =========================================== @@ -208,7 +208,7 @@ module ActiveRecord def explain(arel, binds = []) sql = "EXPLAIN #{to_sql(arel, binds)}" start = Time.now - result = exec_query(sql, 'EXPLAIN', binds) + result = exec_query(sql, "EXPLAIN", binds) elapsed = Time.now - start MySQL::ExplainPrettyPrinter.new.pp(result, elapsed) @@ -294,17 +294,17 @@ module ActiveRecord end def current_database - select_value 'SELECT DATABASE() as db' + select_value "SELECT DATABASE() as db" end # Returns the database character set. def charset - show_variable 'character_set_database' + show_variable "character_set_database" end # Returns the database collation strategy. def collation - show_variable 'collation_database' + show_variable "collation_database" end def tables(name = nil) # :nodoc: @@ -327,7 +327,7 @@ module ActiveRecord sql = "SELECT table_name FROM information_schema.tables " sql << "WHERE table_schema = #{quote(@config[:database])}" - select_values(sql, 'SCHEMA') + select_values(sql, "SCHEMA") end def truncate(table_name, name = nil) @@ -353,11 +353,11 @@ module ActiveRecord sql = "SELECT table_name FROM information_schema.tables " sql << "WHERE table_schema = #{quote(schema)} AND table_name = #{quote(name)}" - select_values(sql, 'SCHEMA').any? + select_values(sql, "SCHEMA").any? end def views # :nodoc: - select_values("SHOW FULL TABLES WHERE table_type = 'VIEW'", 'SCHEMA') + select_values("SHOW FULL TABLES WHERE table_type = 'VIEW'", "SCHEMA") end def view_exists?(view_name) # :nodoc: @@ -368,17 +368,17 @@ module ActiveRecord sql = "SELECT table_name FROM information_schema.tables WHERE table_type = 'VIEW'" sql << " AND table_schema = #{quote(schema)} AND table_name = #{quote(name)}" - select_values(sql, 'SCHEMA').any? + select_values(sql, "SCHEMA").any? end # Returns an array of indexes for the given table. def indexes(table_name, name = nil) #:nodoc: indexes = [] current_index = nil - execute_and_free("SHOW KEYS FROM #{quote_table_name(table_name)}", 'SCHEMA') do |result| + execute_and_free("SHOW KEYS FROM #{quote_table_name(table_name)}", "SCHEMA") do |result| each_hash(result) do |row| if current_index != row[:Key_name] - next if row[:Key_name] == 'PRIMARY' # skip the primary key + next if row[:Key_name] == "PRIMARY" # skip the primary key current_index = row[:Key_name] mysql_index_type = row[:Index_type].downcase.to_sym @@ -412,7 +412,7 @@ module ActiveRecord def table_comment(table_name) # :nodoc: schema, name = extract_schema_qualified_name(table_name) - select_value(<<-SQL.strip_heredoc, 'SCHEMA') + select_value(<<-SQL.strip_heredoc, "SCHEMA") SELECT table_comment FROM information_schema.tables WHERE table_schema = #{quote(schema)} @@ -421,7 +421,7 @@ module ActiveRecord end def create_table(table_name, **options) #:nodoc: - super(table_name, options: 'ENGINE=InnoDB', **options) + super(table_name, options: "ENGINE=InnoDB", **options) end def bulk_change_table(table_name, operations) #:nodoc: @@ -518,7 +518,7 @@ module ActiveRecord schema, name = extract_schema_qualified_name(table_name) - fk_info = select_all(<<-SQL.strip_heredoc, 'SCHEMA') + fk_info = select_all(<<-SQL.strip_heredoc, "SCHEMA") SELECT fk.referenced_table_name AS 'to_table', fk.referenced_column_name AS 'primary_key', fk.column_name AS 'column', @@ -535,15 +535,15 @@ module ActiveRecord fk_info.map do |row| options = { - column: row['column'], - name: row['name'], - primary_key: row['primary_key'] + column: row["column"], + name: row["name"], + primary_key: row["primary_key"] } - options[:on_update] = extract_foreign_key_action(row['on_update']) - options[:on_delete] = extract_foreign_key_action(row['on_delete']) + options[:on_update] = extract_foreign_key_action(row["on_update"]) + options[:on_delete] = extract_foreign_key_action(row["on_delete"]) - ForeignKeyDefinition.new(table_name, row['to_table'], options) + ForeignKeyDefinition.new(table_name, row["to_table"], options) end end @@ -553,7 +553,7 @@ module ActiveRecord create_table_info = create_table_info(table_name) # strip create_definitions and partition_options - raw_table_options = create_table_info.sub(/\A.*\n\) /m, '').sub(/\n\/\*!.*\*\/\n\z/m, '').strip + raw_table_options = create_table_info.sub(/\A.*\n\) /m, "").sub(/\n\/\*!.*\*\/\n\z/m, "").strip # strip AUTO_INCREMENT raw_table_options.sub!(/(ENGINE=\w+)(?: AUTO_INCREMENT=\d+)/, '\1') @@ -561,7 +561,7 @@ module ActiveRecord table_options[:options] = raw_table_options # strip COMMENT - if raw_table_options.sub!(/ COMMENT='.+'/, '') + if raw_table_options.sub!(/ COMMENT='.+'/, "") table_options[:comment] = table_comment(table_name) end @@ -571,13 +571,13 @@ module ActiveRecord # Maps logical Rails types to MySQL-specific data types. def type_to_sql(type, limit = nil, precision = nil, scale = nil, unsigned = nil) sql = case type.to_s - when 'integer' + when "integer" integer_to_sql(limit) - when 'text' + when "text" text_to_sql(limit) - when 'blob' + when "blob" binary_to_sql(limit) - when 'binary' + when "binary" if (0..0xfff) === limit "varbinary(#{limit})" else @@ -587,13 +587,13 @@ module ActiveRecord super(type, limit, precision, scale) end - sql << ' unsigned' if unsigned && type != :primary_key + sql << " unsigned" if unsigned && type != :primary_key sql end # SHOW VARIABLES LIKE 'name' def show_variable(name) - select_value("SELECT @@#{name}", 'SCHEMA') + select_value("SELECT @@#{name}", "SCHEMA") rescue ActiveRecord::StatementInvalid nil end @@ -603,7 +603,7 @@ module ActiveRecord schema, name = extract_schema_qualified_name(table_name) - select_values(<<-SQL.strip_heredoc, 'SCHEMA') + select_values(<<-SQL.strip_heredoc, "SCHEMA") SELECT column_name FROM information_schema.key_column_usage WHERE constraint_name = 'PRIMARY' @@ -635,10 +635,10 @@ module ActiveRecord # Convert Arel node to string s = s.to_sql unless s.is_a?(String) # Remove any ASC/DESC modifiers - s.gsub(/\s+(?:ASC|DESC)\b/i, '') + s.gsub(/\s+(?:ASC|DESC)\b/i, "") }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" } - [super, *order_columns].join(', ') + [super, *order_columns].join(", ") end def strict_mode? @@ -675,18 +675,18 @@ module ActiveRecord register_integer_type m, %r(^tinyint)i, limit: 1 m.register_type %r(^tinyint\(1\))i, Type::Boolean.new if emulate_booleans - m.alias_type %r(year)i, 'integer' - m.alias_type %r(bit)i, 'binary' + m.alias_type %r(year)i, "integer" + m.alias_type %r(bit)i, "binary" m.register_type(%r(enum)i) do |sql_type| limit = sql_type[/^enum\((.+)\)/i, 1] - .split(',').map{|enum| enum.strip.length - 2}.max + .split(",").map{|enum| enum.strip.length - 2}.max MysqlString.new(limit: limit) end m.register_type(%r(^set)i) do |sql_type| limit = sql_type[/^set\((.+)\)/i, 1] - .split(',').map{|set| set.strip.length - 1}.sum - 1 + .split(",").map{|set| set.strip.length - 1}.sum - 1 MysqlString.new(limit: limit) end end @@ -727,7 +727,7 @@ module ActiveRecord end def quoted_columns_for_index(column_names, options = {}) - option_strings = Hash[column_names.map {|name| [name, '']}] + option_strings = Hash[column_names.map {|name| [name, ""]}] # add index length option_strings = add_index_length(option_strings, column_names, options) @@ -789,7 +789,7 @@ module ActiveRecord auto_increment: column.auto_increment? } - current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'", 'SCHEMA')["Type"] + current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'", "SCHEMA")["Type"] td = create_table_definition(table_name) cd = td.new_column_definition(new_column_name, current_type, options) schema_creation.accept(ChangeColumnDefinition.new(cd, column.name)) @@ -836,30 +836,30 @@ module ActiveRecord subselect = Arel::SelectManager.new(select.engine) subselect.project Arel.sql(key.name) - subselect.from subsubselect.as('__active_record_temp') + subselect.from subsubselect.as("__active_record_temp") end def supports_rename_index? - mariadb? ? false : version >= '5.7.6' + mariadb? ? false : version >= "5.7.6" end def configure_connection variables = @config.fetch(:variables, {}).stringify_keys # By default, MySQL 'where id is null' selects the last inserted id; Turn this off. - variables['sql_auto_is_null'] = 0 + variables["sql_auto_is_null"] = 0 # Increase timeout so the server doesn't disconnect us. wait_timeout = @config[:wait_timeout] wait_timeout = 2147483 unless wait_timeout.is_a?(Integer) - variables['wait_timeout'] = self.class.type_cast_config_to_integer(wait_timeout) + variables["wait_timeout"] = self.class.type_cast_config_to_integer(wait_timeout) - defaults = [':default', :default].to_set + defaults = [":default", :default].to_set # Make MySQL reject illegal values rather than truncating or blanking them, see # http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_strict_all_tables # If the user has provided another value for sql_mode, don't replace it. - if sql_mode = variables.delete('sql_mode') + if sql_mode = variables.delete("sql_mode") sql_mode = quote(sql_mode) elsif !defaults.include?(strict_mode?) if strict_mode? @@ -890,22 +890,22 @@ module ActiveRecord "@@SESSION.#{k} = #{quote(v)}" end # or else nil; compact to clear nils out - end.compact.join(', ') + end.compact.join(", ") # ...and send them all in one query @connection.query "SET #{encoding} #{sql_mode_assignment} #{variable_assignments}" end def column_definitions(table_name) # :nodoc: - execute_and_free("SHOW FULL FIELDS FROM #{quote_table_name(table_name)}", 'SCHEMA') do |result| + execute_and_free("SHOW FULL FIELDS FROM #{quote_table_name(table_name)}", "SCHEMA") do |result| each_hash(result) end end def extract_foreign_key_action(specifier) # :nodoc: case specifier - when 'CASCADE'; :cascade - when 'SET NULL'; :nullify + when "CASCADE"; :cascade + when "SET NULL"; :nullify end end @@ -925,31 +925,31 @@ module ActiveRecord def integer_to_sql(limit) # :nodoc: case limit - when 1; 'tinyint' - when 2; 'smallint' - when 3; 'mediumint' - when nil, 4; 'int' - when 5..8; 'bigint' + when 1; "tinyint" + when 2; "smallint" + when 3; "mediumint" + when nil, 4; "int" + when 5..8; "bigint" else raise(ActiveRecordError, "No integer type has byte size #{limit}") end end def text_to_sql(limit) # :nodoc: case limit - when 0..0xff; 'tinytext' - when nil, 0x100..0xffff; 'text' - when 0x10000..0xffffff; 'mediumtext' - when 0x1000000..0xffffffff; 'longtext' + when 0..0xff; "tinytext" + when nil, 0x100..0xffff; "text" + when 0x10000..0xffffff; "mediumtext" + when 0x1000000..0xffffffff; "longtext" else raise(ActiveRecordError, "No text type has byte length #{limit}") end end def binary_to_sql(limit) # :nodoc: case limit - when 0..0xff; 'tinyblob' - when nil, 0x100..0xffff; 'blob' - when 0x10000..0xffffff; 'mediumblob' - when 0x1000000..0xffffffff; 'longblob' + when 0..0xff; "tinyblob" + when nil, 0x100..0xffff; "blob" + when 0x10000..0xffffff; "mediumblob" + when 0x1000000..0xffffffff; "longblob" else raise(ActiveRecordError, "No binary type has byte length #{limit}") end end diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb index 346916337e..dbb0a95444 100644 --- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -1,4 +1,4 @@ -require 'uri' +require "uri" module ActiveRecord module ConnectionAdapters @@ -37,11 +37,11 @@ module ActiveRecord def initialize(url) raise "Database URL cannot be empty" if url.blank? @uri = uri_parser.parse(url) - @adapter = @uri.scheme && @uri.scheme.tr('-', '_') + @adapter = @uri.scheme && @uri.scheme.tr("-", "_") @adapter = "postgresql" if @adapter == "postgres" if @uri.opaque - @uri.opaque, @query = @uri.opaque.split('?', 2) + @uri.opaque, @query = @uri.opaque.split("?", 2) else @query = @uri.query end @@ -74,7 +74,7 @@ module ActiveRecord # "localhost" # # => {} def query_hash - Hash[(@query || '').split("&").map { |pair| pair.split("=") }] + Hash[(@query || "").split("&").map { |pair| pair.split("=") }] end def raw_config @@ -95,7 +95,7 @@ module ActiveRecord # Returns name of the database. def database_from_path - if @adapter == 'sqlite3' + if @adapter == "sqlite3" # 'sqlite3:/foo' is absolute, because that makes sense. The # corresponding relative version, 'sqlite3:foo', is handled # elsewhere, as an "opaque". diff --git a/activerecord/lib/active_record/connection_adapters/mysql/column.rb b/activerecord/lib/active_record/connection_adapters/mysql/column.rb index ea554b188c..cb068a61c7 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/column.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/column.rb @@ -27,14 +27,14 @@ module ActiveRecord end def auto_increment? - extra == 'auto_increment' + extra == "auto_increment" end private def extract_default if blob_or_text_column? - @default = null || strict ? nil : '' + @default = null || strict ? nil : "" end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb index fb0eda753f..cd606d11a7 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb @@ -33,7 +33,7 @@ module ActiveRecord super end - def exec_query(sql, name = 'SQL', binds = [], prepare: false) + def exec_query(sql, name = "SQL", binds = [], prepare: false) if without_prepared_statement?(binds) execute_and_free(sql, name) do |result| ActiveRecord::Result.new(result.fields, result.to_a) if result diff --git a/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb b/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb index 1820853196..5a6b33cb04 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb @@ -39,7 +39,7 @@ module ActiveRecord def compute_column_widths(result) [].tap do |widths| result.columns.each_with_index do |column, i| - cells_in_column = [column] + result.rows.map {|r| r[i].nil? ? 'NULL' : r[i].to_s} + cells_in_column = [column] + result.rows.map {|r| r[i].nil? ? "NULL" : r[i].to_s} widths << cells_in_column.map(&:length).max end end @@ -47,21 +47,21 @@ module ActiveRecord def build_separator(widths) padding = 1 - '+' + widths.map {|w| '-' * (w + (padding*2))}.join('+') + '+' + "+" + widths.map {|w| "-" * (w + (padding*2))}.join("+") + "+" end def build_cells(items, widths) cells = [] items.each_with_index do |item, i| - item = 'NULL' if item.nil? - justifier = item.is_a?(Numeric) ? 'rjust' : 'ljust' + item = "NULL" if item.nil? + justifier = item.is_a?(Numeric) ? "rjust" : "ljust" cells << item.to_s.send(justifier, widths[i]) end - '| ' + cells.join(' | ') + ' |' + "| " + cells.join(" | ") + " |" end def build_footer(nrows, elapsed) - rows_label = nrows == 1 ? 'row' : 'rows' + rows_label = nrows == 1 ? "row" : "rows" "#{nrows} #{rows_label} in set (%.2f sec)" % elapsed end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb b/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb index af1db30047..381787868b 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb @@ -2,14 +2,14 @@ module ActiveRecord module ConnectionAdapters module MySQL module Quoting # :nodoc: - QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze + QUOTED_TRUE, QUOTED_FALSE = "1".freeze, "0".freeze def quote_column_name(name) @quoted_column_names[name] ||= "`#{super.gsub('`', '``')}`".freeze end def quote_table_name(name) - @quoted_table_names[name] ||= super.gsub('.', '`.`').freeze + @quoted_table_names[name] ||= super.gsub(".", "`.`").freeze end def quoted_true @@ -32,7 +32,7 @@ module ActiveRecord if supports_datetime_with_precision? super else - super.sub(/\.\d{6}\z/, '') + super.sub(/\.\d{6}\z/, "") end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb index 2ba9657f24..3e644f386f 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb @@ -5,17 +5,17 @@ module ActiveRecord def column_spec_for_primary_key(column) if column.bigint? spec = { id: :bigint.inspect } - spec[:default] = schema_default(column) || 'nil' unless column.auto_increment? + spec[:default] = schema_default(column) || "nil" unless column.auto_increment? else spec = super end - spec[:unsigned] = 'true' if column.unsigned? + spec[:unsigned] = "true" if column.unsigned? spec end def prepare_column_options(column) spec = super - spec[:unsigned] = 'true' if column.unsigned? + spec[:unsigned] = "true" if column.unsigned? spec end @@ -30,7 +30,7 @@ module ActiveRecord end def schema_type(column) - if column.sql_type == 'tinyblob' + if column.sql_type == "tinyblob" :blob else super diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 22d35f1db5..cace451df2 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -1,9 +1,9 @@ -require 'active_record/connection_adapters/abstract_mysql_adapter' -require 'active_record/connection_adapters/mysql/database_statements' +require "active_record/connection_adapters/abstract_mysql_adapter" +require "active_record/connection_adapters/mysql/database_statements" -gem 'mysql2', '>= 0.3.18', '< 0.5' -require 'mysql2' -raise 'mysql2 0.4.3 is not supported. Please upgrade to 0.4.4+' if Mysql2::VERSION == '0.4.3' +gem "mysql2", ">= 0.3.18", "< 0.5" +require "mysql2" +raise "mysql2 0.4.3 is not supported. Please upgrade to 0.4.4+" if Mysql2::VERSION == "0.4.3" module ActiveRecord module ConnectionHandling # :nodoc: @@ -11,7 +11,7 @@ module ActiveRecord def mysql2_connection(config) config = config.symbolize_keys - config[:username] = 'root' if config[:username].nil? + config[:username] = "root" if config[:username].nil? config[:flags] ||= 0 if Mysql2::Client.const_defined? :FOUND_ROWS @@ -35,7 +35,7 @@ module ActiveRecord module ConnectionAdapters class Mysql2Adapter < AbstractMysqlAdapter - ADAPTER_NAME = 'Mysql2'.freeze + ADAPTER_NAME = "Mysql2".freeze include MySQL::DatabaseStatements @@ -46,7 +46,7 @@ module ActiveRecord end def supports_json? - !mariadb? && version >= '5.7.8' + !mariadb? && version >= "5.7.8" end def supports_comments? diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb index da533463bf..b5a3340c18 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb @@ -4,7 +4,7 @@ module ActiveRecord module DatabaseStatements def explain(arel, binds = []) sql = "EXPLAIN #{to_sql(arel, binds)}" - PostgreSQL::ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds)) + PostgreSQL::ExplainPrettyPrinter.new.pp(exec_query(sql, "EXPLAIN", binds)) end def select_value(arel, name = nil, binds = []) @@ -74,9 +74,9 @@ module ActiveRecord # (2) $12.345.678,12 case data when /^-?\D+[\d,]+\.\d{2}$/ # (1) - data.gsub!(/[^-\d.]/, '') + data.gsub!(/[^-\d.]/, "") when /^-?\D+[\d.]+,\d{2}$/ # (2) - data.gsub!(/[^-\d,]/, '').sub!(/,/, '.') + data.gsub!(/[^-\d,]/, "").sub!(/,/, ".") end end end @@ -99,7 +99,7 @@ module ActiveRecord end end - def exec_query(sql, name = 'SQL', binds = [], prepare: false) + def exec_query(sql, name = "SQL", binds = [], prepare: false) execute_and_clear(sql, name, binds, prepare: prepare) do |result| types = {} fields = result.fields diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb b/activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb index 789b88912c..f95a63968c 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb @@ -26,12 +26,12 @@ module ActiveRecord pp = [] pp << header.center(width).rstrip - pp << '-' * width + pp << "-" * width pp += lines.map {|line| " #{line}"} nrows = result.rows.length - rows_label = nrows == 1 ? 'row' : 'rows' + rows_label = nrows == 1 ? "row" : "rows" pp << "(#{nrows} #{rows_label})" pp.join("\n") + "\n" diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb index 68752cdd80..8c318886cf 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb @@ -1,25 +1,25 @@ -require 'active_record/connection_adapters/postgresql/oid/array' -require 'active_record/connection_adapters/postgresql/oid/bit' -require 'active_record/connection_adapters/postgresql/oid/bit_varying' -require 'active_record/connection_adapters/postgresql/oid/bytea' -require 'active_record/connection_adapters/postgresql/oid/cidr' -require 'active_record/connection_adapters/postgresql/oid/date_time' -require 'active_record/connection_adapters/postgresql/oid/decimal' -require 'active_record/connection_adapters/postgresql/oid/enum' -require 'active_record/connection_adapters/postgresql/oid/hstore' -require 'active_record/connection_adapters/postgresql/oid/inet' -require 'active_record/connection_adapters/postgresql/oid/json' -require 'active_record/connection_adapters/postgresql/oid/jsonb' -require 'active_record/connection_adapters/postgresql/oid/money' -require 'active_record/connection_adapters/postgresql/oid/point' -require 'active_record/connection_adapters/postgresql/oid/rails_5_1_point' -require 'active_record/connection_adapters/postgresql/oid/range' -require 'active_record/connection_adapters/postgresql/oid/specialized_string' -require 'active_record/connection_adapters/postgresql/oid/uuid' -require 'active_record/connection_adapters/postgresql/oid/vector' -require 'active_record/connection_adapters/postgresql/oid/xml' +require "active_record/connection_adapters/postgresql/oid/array" +require "active_record/connection_adapters/postgresql/oid/bit" +require "active_record/connection_adapters/postgresql/oid/bit_varying" +require "active_record/connection_adapters/postgresql/oid/bytea" +require "active_record/connection_adapters/postgresql/oid/cidr" +require "active_record/connection_adapters/postgresql/oid/date_time" +require "active_record/connection_adapters/postgresql/oid/decimal" +require "active_record/connection_adapters/postgresql/oid/enum" +require "active_record/connection_adapters/postgresql/oid/hstore" +require "active_record/connection_adapters/postgresql/oid/inet" +require "active_record/connection_adapters/postgresql/oid/json" +require "active_record/connection_adapters/postgresql/oid/jsonb" +require "active_record/connection_adapters/postgresql/oid/money" +require "active_record/connection_adapters/postgresql/oid/point" +require "active_record/connection_adapters/postgresql/oid/rails_5_1_point" +require "active_record/connection_adapters/postgresql/oid/range" +require "active_record/connection_adapters/postgresql/oid/specialized_string" +require "active_record/connection_adapters/postgresql/oid/uuid" +require "active_record/connection_adapters/postgresql/oid/vector" +require "active_record/connection_adapters/postgresql/oid/xml" -require 'active_record/connection_adapters/postgresql/oid/type_map_initializer' +require "active_record/connection_adapters/postgresql/oid/type_map_initializer" module ActiveRecord module ConnectionAdapters diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb index 87593ef704..9e0e6732c3 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb @@ -8,7 +8,7 @@ module ActiveRecord attr_reader :subtype, :delimiter delegate :type, :user_input_in_time_zone, :limit, to: :subtype - def initialize(subtype, delimiter = ',') + def initialize(subtype, delimiter = ",") @subtype = subtype @delimiter = delimiter diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb index 838cb63281..5225609e37 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb @@ -1,4 +1,4 @@ -require 'ipaddr' +require "ipaddr" module ActiveRecord module ConnectionAdapters diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/date_time.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/date_time.rb index 424769f765..b7acbf7178 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/date_time.rb @@ -5,8 +5,8 @@ module ActiveRecord class DateTime < Type::DateTime # :nodoc: def cast_value(value) case value - when 'infinity' then ::Float::INFINITY - when '-infinity' then -::Float::INFINITY + when "infinity" then ::Float::INFINITY + when "-infinity" then -::Float::INFINITY when / BC$/ astronomical_year = format("%04d", -value[/^\d+/].to_i + 1) super(value.sub(/ BC$/, "").sub(/^\d+/, astronomical_year)) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb index 9270fc9f21..2e55a5f8b8 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb @@ -12,7 +12,7 @@ module ActiveRecord def deserialize(value) if value.is_a?(::String) ::Hash[value.scan(HstorePair).map { |k, v| - v = v.upcase == 'NULL' ? nil : v.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1') + v = v.upcase == "NULL" ? nil : v.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1') k = k.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1') [k, v] }] @@ -23,7 +23,7 @@ module ActiveRecord def serialize(value) if value.is_a?(::Hash) - value.map { |k, v| "#{escape_hstore(k)}=>#{escape_hstore(v)}" }.join(', ') + value.map { |k, v| "#{escape_hstore(k)}=>#{escape_hstore(v)}" }.join(", ") else value end @@ -43,7 +43,7 @@ module ActiveRecord def escape_hstore(value) if value.nil? - 'NULL' + "NULL" else if value == "" '""' diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb index dcc12ae2a4..7a91272d1c 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb @@ -25,9 +25,9 @@ module ActiveRecord value.sub!(/^\((.+)\)$/, '-\1') # (4) case value when /^-?\D+[\d,]+\.\d{2}$/ # (1) - value.gsub!(/[^-\d.]/, '') + value.gsub!(/[^-\d.]/, "") when /^-?\D+[\d.]+,\d{2}$/ # (2) - value.gsub!(/[^-\d,]/, '').sub!(/,/, '.') + value.gsub!(/[^-\d,]/, "").sub!(/,/, ".") end super(value) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb index bf565bcf47..3657f20433 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb @@ -12,10 +12,10 @@ module ActiveRecord def cast(value) case value when ::String - if value[0] == '(' && value[-1] == ')' + if value[0] == "(" && value[-1] == ")" value = value[1...-1] end - cast(value.split(',')) + cast(value.split(",")) when ::Array value.map { |v| Float(v) } else @@ -34,7 +34,7 @@ module ActiveRecord private def number_for_point(number) - number.to_s.gsub(/\.0$/, '') + number.to_s.gsub(/\.0$/, "") end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb index 4da240edb2..3a52f05091 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb @@ -16,7 +16,7 @@ module ActiveRecord when ::String return if value.blank? - if value[0] == '(' && value[-1] == ')' + if value[0] == "(" && value[-1] == ")" value = value[1...-1] end x, y = value.split(",") @@ -39,7 +39,7 @@ module ActiveRecord private def number_for_point(number) - number.to_s.gsub(/\.0$/, '') + number.to_s.gsub(/\.0$/, "") end def build_point(x, y) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb index a8d2310035..58bf5c5640 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/string/filters' +require "active_support/core_ext/string/filters" module ActiveRecord module ConnectionAdapters @@ -14,11 +14,11 @@ module ActiveRecord end def type_cast_for_schema(value) - value.inspect.gsub('Infinity', '::Float::INFINITY') + value.inspect.gsub("Infinity", "::Float::INFINITY") end def cast_value(value) - return if value == 'empty' + return if value == "empty" return value unless value.is_a?(::String) extracted = extract_bounds(value) @@ -60,16 +60,16 @@ module ActiveRecord end def type_cast_single_for_database(value) - infinity?(value) ? '' : @subtype.serialize(value) + infinity?(value) ? "" : @subtype.serialize(value) end def extract_bounds(value) - from, to = value[1..-2].split(',') + from, to = value[1..-2].split(",") { - from: (value[1] == ',' || from == '-infinity') ? infinity(negative: true) : from, - to: (value[-2] == ',' || to == 'infinity') ? infinity : to, - exclude_start: (value[0] == '('), - exclude_end: (value[-1] == ')') + from: (value[1] == "," || from == "-infinity") ? infinity(negative: true) : from, + to: (value[-2] == "," || to == "infinity") ? infinity : to, + exclude_start: (value[0] == "("), + exclude_end: (value[-1] == ")") } end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb index 6155e53632..3a75e8d69d 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb @@ -13,13 +13,13 @@ module ActiveRecord end def run(records) - nodes = records.reject { |row| @store.key? row['oid'].to_i } - mapped, nodes = nodes.partition { |row| @store.key? row['typname'] } - ranges, nodes = nodes.partition { |row| row['typtype'] == 'r'.freeze } - enums, nodes = nodes.partition { |row| row['typtype'] == 'e'.freeze } - domains, nodes = nodes.partition { |row| row['typtype'] == 'd'.freeze } - arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in'.freeze } - composites, nodes = nodes.partition { |row| row['typelem'].to_i != 0 } + nodes = records.reject { |row| @store.key? row["oid"].to_i } + mapped, nodes = nodes.partition { |row| @store.key? row["typname"] } + ranges, nodes = nodes.partition { |row| row["typtype"] == "r".freeze } + enums, nodes = nodes.partition { |row| row["typtype"] == "e".freeze } + domains, nodes = nodes.partition { |row| row["typtype"] == "d".freeze } + arrays, nodes = nodes.partition { |row| row["typinput"] == "array_in".freeze } + composites, nodes = nodes.partition { |row| row["typelem"].to_i != 0 } mapped.each { |row| register_mapped_type(row) } enums.each { |row| register_enum_type(row) } @@ -43,36 +43,36 @@ module ActiveRecord private def register_mapped_type(row) - alias_type row['oid'], row['typname'] + alias_type row["oid"], row["typname"] end def register_enum_type(row) - register row['oid'], OID::Enum.new + register row["oid"], OID::Enum.new end def register_array_type(row) - register_with_subtype(row['oid'], row['typelem'].to_i) do |subtype| - OID::Array.new(subtype, row['typdelim']) + register_with_subtype(row["oid"], row["typelem"].to_i) do |subtype| + OID::Array.new(subtype, row["typdelim"]) end end def register_range_type(row) - register_with_subtype(row['oid'], row['rngsubtype'].to_i) do |subtype| - OID::Range.new(subtype, row['typname'].to_sym) + register_with_subtype(row["oid"], row["rngsubtype"].to_i) do |subtype| + OID::Range.new(subtype, row["typname"].to_sym) end end def register_domain_type(row) if base_type = @store.lookup(row["typbasetype"].to_i) - register row['oid'], base_type + register row["oid"], base_type else warn "unknown base type (OID: #{row["typbasetype"]}) for domain #{row["typname"]}." end end def register_composite_type(row) - if subtype = @store.lookup(row['typelem'].to_i) - register row['oid'], OID::Vector.new(row['typdelim'], subtype) + if subtype = @store.lookup(row["typelem"].to_i) + register row["oid"], OID::Vector.new(row["typdelim"], subtype) end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb index 9fcf8dbb95..90e88b1f3c 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb @@ -58,7 +58,7 @@ module ActiveRecord def quote_default_expression(value, column) # :nodoc: if value.is_a?(Proc) value.call - elsif column.type == :uuid && value.include?('()') + elsif column.type == :uuid && value.include?("()") value # Does not quote function default values for UUID columns elsif column.respond_to?(:array?) value = type_cast_from_column(column, value) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_definitions.rb index 6399bddbee..a11dbe7dce 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_definitions.rb @@ -31,7 +31,7 @@ module ActiveRecord # a record (as primary keys cannot be +nil+). This might be done via the # +SecureRandom.uuid+ method and a +before_save+ callback, for instance. def primary_key(name, type = :primary_key, **options) - options[:default] = options.fetch(:default, 'uuid_generate_v4()') if type == :uuid + options[:default] = options.fetch(:default, "uuid_generate_v4()") if type == :uuid super end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb index a1e10fd364..2ed8f29b24 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb @@ -5,7 +5,7 @@ module ActiveRecord def column_spec_for_primary_key(column) spec = super if schema_type(column) == :uuid - spec[:default] ||= 'nil' + spec[:default] ||= "nil" end spec end @@ -13,7 +13,7 @@ module ActiveRecord # Adds +:array+ option to the default set def prepare_column_options(column) spec = super - spec[:array] = 'true' if column.array? + spec[:array] = "true" if column.array? spec end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb index 4cf6d4b14a..55c5fcafa6 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/string/strip' +require "active_support/core_ext/string/strip" module ActiveRecord module ConnectionAdapters @@ -36,7 +36,7 @@ module ActiveRecord # create_database config[:database], config # create_database 'foo_development', encoding: 'unicode' def create_database(name, options = {}) - options = { encoding: 'utf8' }.merge!(options.symbolize_keys) + options = { encoding: "utf8" }.merge!(options.symbolize_keys) option_string = options.inject("") do |memo, (key, value)| memo += case key @@ -78,11 +78,11 @@ module ActiveRecord MSG end - select_values("SELECT tablename FROM pg_tables WHERE schemaname = ANY(current_schemas(false))", 'SCHEMA') + select_values("SELECT tablename FROM pg_tables WHERE schemaname = ANY(current_schemas(false))", "SCHEMA") end def data_sources # :nodoc - select_values(<<-SQL, 'SCHEMA') + select_values(<<-SQL, "SCHEMA") SELECT c.relname FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace @@ -108,7 +108,7 @@ module ActiveRecord name = Utils.extract_schema_qualified_name(name.to_s) return false unless name.identifier - select_value(<<-SQL, 'SCHEMA').to_i > 0 + select_value(<<-SQL, "SCHEMA").to_i > 0 SELECT COUNT(*) FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace @@ -119,7 +119,7 @@ module ActiveRecord end def views # :nodoc: - select_values(<<-SQL, 'SCHEMA') + select_values(<<-SQL, "SCHEMA") SELECT c.relname FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace @@ -132,7 +132,7 @@ module ActiveRecord name = Utils.extract_schema_qualified_name(view_name.to_s) return false unless name.identifier - select_values(<<-SQL, 'SCHEMA').any? + select_values(<<-SQL, "SCHEMA").any? SELECT c.relname FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace @@ -148,7 +148,7 @@ module ActiveRecord # Returns true if schema exists. def schema_exists?(name) - select_value("SELECT COUNT(*) FROM pg_namespace WHERE nspname = '#{name}'", 'SCHEMA').to_i > 0 + select_value("SELECT COUNT(*) FROM pg_namespace WHERE nspname = '#{name}'", "SCHEMA").to_i > 0 end # Verifies existence of an index with a given name. @@ -156,7 +156,7 @@ module ActiveRecord table = Utils.extract_schema_qualified_name(table_name.to_s) index = Utils.extract_schema_qualified_name(index_name.to_s) - select_value(<<-SQL, 'SCHEMA').to_i > 0 + select_value(<<-SQL, "SCHEMA").to_i > 0 SELECT COUNT(*) FROM pg_class t INNER JOIN pg_index d ON t.oid = d.indrelid @@ -173,7 +173,7 @@ module ActiveRecord def indexes(table_name, name = nil) table = Utils.extract_schema_qualified_name(table_name.to_s) - result = query(<<-SQL, 'SCHEMA') + result = query(<<-SQL, "SCHEMA") SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid, pg_catalog.obj_description(i.oid, 'pg_class') AS comment, (SELECT COUNT(*) FROM pg_opclass o @@ -246,7 +246,7 @@ module ActiveRecord def table_comment(table_name) # :nodoc: name = Utils.extract_schema_qualified_name(table_name.to_s) if name.identifier - select_value(<<-SQL.strip_heredoc, 'SCHEMA') + select_value(<<-SQL.strip_heredoc, "SCHEMA") SELECT pg_catalog.obj_description(c.oid, 'pg_class') FROM pg_catalog.pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace @@ -259,32 +259,32 @@ module ActiveRecord # Returns the current database name. def current_database - select_value('select current_database()', 'SCHEMA') + select_value("select current_database()", "SCHEMA") end # Returns the current schema name. def current_schema - select_value('SELECT current_schema', 'SCHEMA') + select_value("SELECT current_schema", "SCHEMA") end # Returns the current database encoding format. def encoding - select_value("SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname LIKE '#{current_database}'", 'SCHEMA') + select_value("SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname LIKE '#{current_database}'", "SCHEMA") end # Returns the current database collation. def collation - select_value("SELECT datcollate FROM pg_database WHERE datname LIKE '#{current_database}'", 'SCHEMA') + select_value("SELECT datcollate FROM pg_database WHERE datname LIKE '#{current_database}'", "SCHEMA") end # Returns the current database ctype. def ctype - select_value("SELECT datctype FROM pg_database WHERE datname LIKE '#{current_database}'", 'SCHEMA') + select_value("SELECT datctype FROM pg_database WHERE datname LIKE '#{current_database}'", "SCHEMA") end # Returns an array of schema names. def schema_names - select_values(<<-SQL, 'SCHEMA') + select_values(<<-SQL, "SCHEMA") SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_.*' @@ -310,28 +310,28 @@ module ActiveRecord # This should be not be called manually but set in database.yml. def schema_search_path=(schema_csv) if schema_csv - execute("SET search_path TO #{schema_csv}", 'SCHEMA') + execute("SET search_path TO #{schema_csv}", "SCHEMA") @schema_search_path = schema_csv end end # Returns the active schema search path. def schema_search_path - @schema_search_path ||= select_value('SHOW search_path', 'SCHEMA') + @schema_search_path ||= select_value("SHOW search_path", "SCHEMA") end # Returns the current client message level. def client_min_messages - select_value('SHOW client_min_messages', 'SCHEMA') + select_value("SHOW client_min_messages", "SCHEMA") end # Set the client message level. def client_min_messages=(level) - execute("SET client_min_messages TO '#{level}'", 'SCHEMA') + execute("SET client_min_messages TO '#{level}'", "SCHEMA") end # Returns the sequence name for a table's primary key or some other specified key. - def default_sequence_name(table_name, pk = 'id') #:nodoc: + def default_sequence_name(table_name, pk = "id") #:nodoc: result = serial_sequence(table_name, pk) return nil unless result Utils.extract_schema_qualified_name(result).to_s @@ -340,7 +340,7 @@ module ActiveRecord end def serial_sequence(table, column) - select_value("SELECT pg_get_serial_sequence('#{table}', '#{column}')", 'SCHEMA') + select_value("SELECT pg_get_serial_sequence('#{table}', '#{column}')", "SCHEMA") end # Sets the sequence of a table's primary key to the specified value. @@ -351,7 +351,7 @@ module ActiveRecord if sequence quoted_sequence = quote_table_name(sequence) - select_value("SELECT setval('#{quoted_sequence}', #{value})", 'SCHEMA') + select_value("SELECT setval('#{quoted_sequence}', #{value})", "SCHEMA") else @logger.warn "#{table} has primary key #{pk} with no default sequence." if @logger end @@ -374,7 +374,7 @@ module ActiveRecord if pk && sequence quoted_sequence = quote_table_name(sequence) - select_value(<<-end_sql, 'SCHEMA') + select_value(<<-end_sql, "SCHEMA") SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false) end_sql end @@ -384,7 +384,7 @@ module ActiveRecord def pk_and_sequence_for(table) #:nodoc: # First try looking for a sequence with a dependency on the # given table's primary key. - result = query(<<-end_sql, 'SCHEMA')[0] + result = query(<<-end_sql, "SCHEMA")[0] SELECT attr.attname, nsp.nspname, seq.relname FROM pg_class seq, pg_attribute attr, @@ -404,7 +404,7 @@ module ActiveRecord end_sql if result.nil? or result.empty? - result = query(<<-end_sql, 'SCHEMA')[0] + result = query(<<-end_sql, "SCHEMA")[0] SELECT attr.attname, nsp.nspname, CASE WHEN pg_get_expr(def.adbin, def.adrelid) !~* 'nextval' THEN NULL @@ -435,7 +435,7 @@ module ActiveRecord end def primary_keys(table_name) # :nodoc: - select_values(<<-SQL.strip_heredoc, 'SCHEMA') + select_values(<<-SQL.strip_heredoc, "SCHEMA") WITH pk_constraint AS ( SELECT conrelid, unnest(conkey) AS connum FROM pg_constraint WHERE contype = 'p' @@ -583,7 +583,7 @@ module ActiveRecord end def foreign_keys(table_name) - fk_info = select_all(<<-SQL.strip_heredoc, 'SCHEMA') + fk_info = select_all(<<-SQL.strip_heredoc, "SCHEMA") SELECT t2.oid::regclass::text AS to_table, a1.attname AS column, a2.attname AS primary_key, c.conname AS name, c.confupdtype AS on_update, c.confdeltype AS on_delete FROM pg_constraint c JOIN pg_class t1 ON c.conrelid = t1.oid @@ -599,23 +599,23 @@ module ActiveRecord fk_info.map do |row| options = { - column: row['column'], - name: row['name'], - primary_key: row['primary_key'] + column: row["column"], + name: row["name"], + primary_key: row["primary_key"] } - options[:on_delete] = extract_foreign_key_action(row['on_delete']) - options[:on_update] = extract_foreign_key_action(row['on_update']) + options[:on_delete] = extract_foreign_key_action(row["on_delete"]) + options[:on_update] = extract_foreign_key_action(row["on_update"]) - ForeignKeyDefinition.new(table_name, row['to_table'], options) + ForeignKeyDefinition.new(table_name, row["to_table"], options) end end def extract_foreign_key_action(specifier) # :nodoc: case specifier - when 'c'; :cascade - when 'n'; :nullify - when 'r'; :restrict + when "c"; :cascade + when "n"; :nullify + when "r"; :restrict end end @@ -626,32 +626,32 @@ module ActiveRecord # Maps logical Rails types to PostgreSQL-specific data types. def type_to_sql(type, limit = nil, precision = nil, scale = nil, array = nil) sql = case type.to_s - when 'binary' + when "binary" # PostgreSQL doesn't support limits on binary (bytea) columns. # The hard limit is 1GB, because of a 32-bit size field, and TOAST. case limit when nil, 0..0x3fffffff; super(type) else raise(ActiveRecordError, "No binary type has byte size #{limit}.") end - when 'text' + when "text" # PostgreSQL doesn't support limits on text columns. # The hard limit is 1GB, according to section 8.3 in the manual. case limit when nil, 0..0x3fffffff; super(type) else raise(ActiveRecordError, "The limit on text can be at most 1GB - 1byte.") end - when 'integer' + when "integer" case limit - when 1, 2; 'smallint' - when nil, 3, 4; 'integer' - when 5..8; 'bigint' + when 1, 2; "smallint" + when nil, 3, 4; "integer" + when 5..8; "bigint" else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with scale 0 instead.") end else super(type, limit, precision, scale) end - sql << '[]' if array && type != :primary_key + sql << "[]" if array && type != :primary_key sql end @@ -662,11 +662,11 @@ module ActiveRecord # Convert Arel node to string s = s.to_sql unless s.is_a?(String) # Remove any ASC/DESC modifiers - s.gsub(/\s+(?:ASC|DESC)\b/i, '') - .gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, '') + s.gsub(/\s+(?:ASC|DESC)\b/i, "") + .gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, "") }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" } - [super, *order_columns].join(', ') + [super, *order_columns].join(", ") end def fetch_type_metadata(column_name, sql_type, oid, fmod) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 8a1fdc9f92..ced5fed2e2 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -1,6 +1,6 @@ # Make sure we're using pg high enough for type casts and Ruby 2.2+ compatibility -gem 'pg', '~> 0.18' -require 'pg' +gem "pg", "~> 0.18" +require "pg" require "active_record/connection_adapters/abstract_adapter" require "active_record/connection_adapters/postgresql/column" @@ -67,7 +67,7 @@ module ActiveRecord # In addition, default connection parameters of libpq can be set per environment variables. # See http://www.postgresql.org/docs/current/static/libpq-envars.html . class PostgreSQLAdapter < AbstractAdapter - ADAPTER_NAME = 'PostgreSQL'.freeze + ADAPTER_NAME = "PostgreSQL".freeze NATIVE_DATABASE_TYPES = { primary_key: "serial primary key", @@ -173,7 +173,7 @@ module ActiveRecord end def index_algorithms - { concurrently: 'CONCURRENTLY' } + { concurrently: "CONCURRENTLY" } end class StatementPool < ConnectionAdapters::StatementPool @@ -227,7 +227,7 @@ module ActiveRecord @type_map = Type::HashLookupTypeMap.new initialize_type_map(type_map) - @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"] + @local_tz = execute("SHOW TIME ZONE", "SCHEMA").first["TimeZone"] @use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true end @@ -242,7 +242,7 @@ module ActiveRecord # Is this connection alive and ready for queries? def active? - @connection.query 'SELECT 1' + @connection.query "SELECT 1" true rescue PGError false @@ -259,9 +259,9 @@ module ActiveRecord clear_cache! reset_transaction unless @connection.transaction_status == ::PG::PQTRANS_IDLE - @connection.query 'ROLLBACK' + @connection.query "ROLLBACK" end - @connection.query 'DISCARD ALL' + @connection.query "DISCARD ALL" configure_connection end @@ -287,7 +287,7 @@ module ActiveRecord end def set_standard_conforming_strings - execute('SET standard_conforming_strings = on', 'SCHEMA') + execute("SET standard_conforming_strings = on", "SCHEMA") end def supports_ddl_transactions? @@ -344,7 +344,7 @@ module ActiveRecord def extension_enabled?(name) if supports_extensions? res = exec_query "SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL) as enabled", - 'SCHEMA' + "SCHEMA" res.cast_values.first end end @@ -359,7 +359,7 @@ module ActiveRecord # Returns the configured supported identifier length supported by PostgreSQL def table_alias_length - @table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i + @table_alias_length ||= query("SHOW max_identifier_length", "SCHEMA")[0][0].to_i end # Set the authorized user for this session @@ -381,7 +381,7 @@ module ActiveRecord end def lookup_cast_type(sql_type) # :nodoc: - oid = execute("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").first['oid'].to_i + oid = execute("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").first["oid"].to_i super(oid) end @@ -430,7 +430,7 @@ module ActiveRecord private - def get_oid_type(oid, fmod, column_name, sql_type = '') # :nodoc: + def get_oid_type(oid, fmod, column_name, sql_type = "") # :nodoc: if !type_map.key?(oid) load_additional_types(type_map, [oid]) end @@ -444,51 +444,51 @@ module ActiveRecord end def initialize_type_map(m) # :nodoc: - register_class_with_limit m, 'int2', Type::Integer - register_class_with_limit m, 'int4', Type::Integer - register_class_with_limit m, 'int8', Type::Integer - m.alias_type 'oid', 'int2' - m.register_type 'float4', Type::Float.new - m.alias_type 'float8', 'float4' - m.register_type 'text', Type::Text.new - register_class_with_limit m, 'varchar', Type::String - m.alias_type 'char', 'varchar' - m.alias_type 'name', 'varchar' - m.alias_type 'bpchar', 'varchar' - m.register_type 'bool', Type::Boolean.new - register_class_with_limit m, 'bit', OID::Bit - register_class_with_limit m, 'varbit', OID::BitVarying - m.alias_type 'timestamptz', 'timestamp' - m.register_type 'date', Type::Date.new - - m.register_type 'money', OID::Money.new - m.register_type 'bytea', OID::Bytea.new - m.register_type 'point', OID::Point.new - m.register_type 'hstore', OID::Hstore.new - m.register_type 'json', OID::Json.new - m.register_type 'jsonb', OID::Jsonb.new - m.register_type 'cidr', OID::Cidr.new - m.register_type 'inet', OID::Inet.new - m.register_type 'uuid', OID::Uuid.new - m.register_type 'xml', OID::Xml.new - m.register_type 'tsvector', OID::SpecializedString.new(:tsvector) - m.register_type 'macaddr', OID::SpecializedString.new(:macaddr) - m.register_type 'citext', OID::SpecializedString.new(:citext) - m.register_type 'ltree', OID::SpecializedString.new(:ltree) - m.register_type 'line', OID::SpecializedString.new(:line) - m.register_type 'lseg', OID::SpecializedString.new(:lseg) - m.register_type 'box', OID::SpecializedString.new(:box) - m.register_type 'path', OID::SpecializedString.new(:path) - m.register_type 'polygon', OID::SpecializedString.new(:polygon) - m.register_type 'circle', OID::SpecializedString.new(:circle) + register_class_with_limit m, "int2", Type::Integer + register_class_with_limit m, "int4", Type::Integer + register_class_with_limit m, "int8", Type::Integer + m.alias_type "oid", "int2" + m.register_type "float4", Type::Float.new + m.alias_type "float8", "float4" + m.register_type "text", Type::Text.new + register_class_with_limit m, "varchar", Type::String + m.alias_type "char", "varchar" + m.alias_type "name", "varchar" + m.alias_type "bpchar", "varchar" + m.register_type "bool", Type::Boolean.new + register_class_with_limit m, "bit", OID::Bit + register_class_with_limit m, "varbit", OID::BitVarying + m.alias_type "timestamptz", "timestamp" + m.register_type "date", Type::Date.new + + m.register_type "money", OID::Money.new + m.register_type "bytea", OID::Bytea.new + m.register_type "point", OID::Point.new + m.register_type "hstore", OID::Hstore.new + m.register_type "json", OID::Json.new + m.register_type "jsonb", OID::Jsonb.new + m.register_type "cidr", OID::Cidr.new + m.register_type "inet", OID::Inet.new + m.register_type "uuid", OID::Uuid.new + m.register_type "xml", OID::Xml.new + m.register_type "tsvector", OID::SpecializedString.new(:tsvector) + m.register_type "macaddr", OID::SpecializedString.new(:macaddr) + m.register_type "citext", OID::SpecializedString.new(:citext) + m.register_type "ltree", OID::SpecializedString.new(:ltree) + m.register_type "line", OID::SpecializedString.new(:line) + m.register_type "lseg", OID::SpecializedString.new(:lseg) + m.register_type "box", OID::SpecializedString.new(:box) + m.register_type "path", OID::SpecializedString.new(:path) + m.register_type "polygon", OID::SpecializedString.new(:polygon) + m.register_type "circle", OID::SpecializedString.new(:circle) # FIXME: why are we keeping these types as strings? - m.alias_type 'interval', 'varchar' + m.alias_type "interval", "varchar" - register_class_with_precision m, 'time', Type::Time - register_class_with_precision m, 'timestamp', OID::DateTime + register_class_with_precision m, "time", Type::Time + register_class_with_precision m, "timestamp", OID::DateTime - m.register_type 'numeric' do |_, fmod, sql_type| + m.register_type "numeric" do |_, fmod, sql_type| precision = extract_precision(sql_type) scale = extract_scale(sql_type) @@ -534,7 +534,7 @@ module ActiveRecord $1.gsub("''".freeze, "'".freeze) end # Boolean types - when 'true'.freeze, 'false'.freeze + when "true".freeze, "false".freeze default # Numeric types when /\A\(?(-?\d+(\.\d*)?)\)?(::bigint)?\z/ @@ -579,7 +579,7 @@ module ActiveRecord query += initializer.query_conditions_for_initial_load(type_map) end - execute_and_clear(query, 'SCHEMA', []) do |records| + execute_and_clear(query, "SCHEMA", []) do |records| initializer.run(records) end end @@ -634,7 +634,7 @@ module ActiveRecord # # Check here for more details: # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573 - CACHED_PLAN_HEURISTIC = 'cached plan must not change result type'.freeze + CACHED_PLAN_HEURISTIC = "cached plan must not change result type".freeze def is_cached_plan_failure?(e) pgerror = e.cause code = pgerror.result.result_error_field(PGresult::PG_DIAG_SQLSTATE) @@ -690,7 +690,7 @@ module ActiveRecord if @config[:encoding] @connection.set_client_encoding(@config[:encoding]) end - self.client_min_messages = @config[:min_messages] || 'warning' + self.client_min_messages = @config[:min_messages] || "warning" self.schema_search_path = @config[:schema_search_path] || @config[:schema_order] # Use standard-conforming strings so we don't have to do the E'...' dance. @@ -700,27 +700,27 @@ module ActiveRecord # TIMESTAMP WITH ZONE types in UTC. # (SET TIME ZONE does not use an equals sign like other SET variables) if ActiveRecord::Base.default_timezone == :utc - execute("SET time zone 'UTC'", 'SCHEMA') + execute("SET time zone 'UTC'", "SCHEMA") elsif @local_tz - execute("SET time zone '#{@local_tz}'", 'SCHEMA') + execute("SET time zone '#{@local_tz}'", "SCHEMA") end # SET statements from :variables config hash # http://www.postgresql.org/docs/current/static/sql-set.html variables = @config[:variables] || {} variables.map do |k, v| - if v == ':default' || v == :default + if v == ":default" || v == :default # Sets the value to the global or compile default - execute("SET SESSION #{k} TO DEFAULT", 'SCHEMA') + execute("SET SESSION #{k} TO DEFAULT", "SCHEMA") elsif !v.nil? - execute("SET SESSION #{k} TO #{quote(v)}", 'SCHEMA') + execute("SET SESSION #{k} TO #{quote(v)}", "SCHEMA") end end end # Returns the current ID of a table's sequence. def last_insert_id_result(sequence_name) # :nodoc: - exec_query("SELECT currval('#{sequence_name}')", 'SQL') + exec_query("SELECT currval('#{sequence_name}')", "SQL") end # Returns the list of a table's column names, data types, and default values. @@ -742,7 +742,7 @@ module ActiveRecord # - format_type includes the column size constraint, e.g. varchar(50) # - ::regclass is a function that gives the id for a table name def column_definitions(table_name) # :nodoc: - query(<<-end_sql, 'SCHEMA') + query(<<-end_sql, "SCHEMA") SELECT a.attname, format_type(a.atttypid, a.atttypmod), pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod, (SELECT c.collname FROM pg_collation c, pg_type t @@ -794,13 +794,13 @@ module ActiveRecord def add_pg_decoders coders_by_name = { - 'int2' => PG::TextDecoder::Integer, - 'int4' => PG::TextDecoder::Integer, - 'int8' => PG::TextDecoder::Integer, - 'oid' => PG::TextDecoder::Integer, - 'float4' => PG::TextDecoder::Float, - 'float8' => PG::TextDecoder::Float, - 'bool' => PG::TextDecoder::Boolean, + "int2" => PG::TextDecoder::Integer, + "int4" => PG::TextDecoder::Integer, + "int8" => PG::TextDecoder::Integer, + "oid" => PG::TextDecoder::Integer, + "float4" => PG::TextDecoder::Float, + "float8" => PG::TextDecoder::Float, + "bool" => PG::TextDecoder::Boolean, } known_coder_types = coders_by_name.keys.map { |n| quote(n) } query = <<-SQL % known_coder_types.join(", ") @@ -810,7 +810,7 @@ module ActiveRecord SQL coders = execute_and_clear(query, "SCHEMA", []) do |result| result - .map { |row| construct_coder(row, coders_by_name[row['typname']]) } + .map { |row| construct_coder(row, coders_by_name[row["typname"]]) } .compact end @@ -821,7 +821,7 @@ module ActiveRecord def construct_coder(row, coder_class) return unless coder_class - coder_class.new(oid: row['oid'].to_i, name: row['typname']) + coder_class.new(oid: row["oid"].to_i, name: row["typname"]) end ActiveRecord::Type.add_modifier({ array: true }, OID::Array, adapter: :postgresql) diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb b/activerecord/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb index a946f5ebd0..6fe3e1211e 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb @@ -10,7 +10,7 @@ module ActiveRecord # def pp(result) result.rows.map do |row| - row.join('|') + row.join("|") end.join("\n") + "\n" end end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 41ed784d2e..47de43dfc3 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -1,11 +1,11 @@ -require 'active_record/connection_adapters/abstract_adapter' -require 'active_record/connection_adapters/statement_pool' -require 'active_record/connection_adapters/sqlite3/explain_pretty_printer' -require 'active_record/connection_adapters/sqlite3/quoting' -require 'active_record/connection_adapters/sqlite3/schema_creation' +require "active_record/connection_adapters/abstract_adapter" +require "active_record/connection_adapters/statement_pool" +require "active_record/connection_adapters/sqlite3/explain_pretty_printer" +require "active_record/connection_adapters/sqlite3/quoting" +require "active_record/connection_adapters/sqlite3/schema_creation" -gem 'sqlite3', '~> 1.3.6' -require 'sqlite3' +gem "sqlite3", "~> 1.3.6" +require "sqlite3" module ActiveRecord module ConnectionHandling # :nodoc: @@ -18,7 +18,7 @@ module ActiveRecord # Allow database path relative to Rails.root, but only if the database # path is not the special path that tells sqlite to build a database only # in memory. - if ':memory:' != config[:database] + if ":memory:" != config[:database] config[:database] = File.expand_path(config[:database], Rails.root) if defined?(Rails.root) dirname = File.dirname(config[:database]) Dir.mkdir(dirname) unless File.directory?(dirname) @@ -49,12 +49,12 @@ module ActiveRecord # # * <tt>:database</tt> - Path to the database file. class SQLite3Adapter < AbstractAdapter - ADAPTER_NAME = 'SQLite'.freeze + ADAPTER_NAME = "SQLite".freeze include SQLite3::Quoting NATIVE_DATABASE_TYPES = { - primary_key: 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL', + primary_key: "INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL", string: { name: "varchar" }, text: { name: "text" }, integer: { name: "integer" }, @@ -99,7 +99,7 @@ module ActiveRecord end def supports_partial_index? - sqlite_version >= '3.8.0' + sqlite_version >= "3.8.0" end # Returns true, since this connection adapter supports prepared statement @@ -130,7 +130,7 @@ module ActiveRecord end def supports_multi_insert? - sqlite_version >= '3.7.11' + sqlite_version >= "3.7.11" end def active? @@ -184,7 +184,7 @@ module ActiveRecord def explain(arel, binds = []) sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}" - SQLite3::ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', [])) + SQLite3::ExplainPrettyPrinter.new.pp(exec_query(sql, "EXPLAIN", [])) end def exec_query(sql, name = nil, binds = [], prepare: false) @@ -218,7 +218,7 @@ module ActiveRecord end end - def exec_delete(sql, name = 'SQL', binds = []) + def exec_delete(sql, name = "SQL", binds = []) exec_query(sql, name, binds) @connection.changes end @@ -233,15 +233,15 @@ module ActiveRecord end def begin_db_transaction #:nodoc: - log('begin transaction',nil) { @connection.transaction } + log("begin transaction",nil) { @connection.transaction } end def commit_db_transaction #:nodoc: - log('commit transaction',nil) { @connection.commit } + log("commit transaction",nil) { @connection.commit } end def exec_rollback_db_transaction #:nodoc: - log('rollback transaction',nil) { @connection.rollback } + log("rollback transaction",nil) { @connection.rollback } end # SCHEMA STATEMENTS ======================================== @@ -263,7 +263,7 @@ module ActiveRecord end def data_sources - select_values("SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name <> 'sqlite_sequence'", 'SCHEMA') + select_values("SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name <> 'sqlite_sequence'", "SCHEMA") end def table_exists?(table_name) @@ -282,11 +282,11 @@ module ActiveRecord sql = "SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name <> 'sqlite_sequence'" sql << " AND name = #{quote(table_name)}" - select_values(sql, 'SCHEMA').any? + select_values(sql, "SCHEMA").any? end def views # :nodoc: - select_values("SELECT name FROM sqlite_master WHERE type = 'view' AND name <> 'sqlite_sequence'", 'SCHEMA') + select_values("SELECT name FROM sqlite_master WHERE type = 'view' AND name <> 'sqlite_sequence'", "SCHEMA") end def view_exists?(view_name) # :nodoc: @@ -295,7 +295,7 @@ module ActiveRecord sql = "SELECT name FROM sqlite_master WHERE type = 'view' AND name <> 'sqlite_sequence'" sql << " AND name = #{quote(view_name)}" - select_values(sql, 'SCHEMA').any? + select_values(sql, "SCHEMA").any? end # Returns an array of +Column+ objects for the table specified by +table_name+. @@ -311,16 +311,16 @@ module ActiveRecord field["dflt_value"] = $1.gsub('""', '"') end - collation = field['collation'] - sql_type = field['type'] + collation = field["collation"] + sql_type = field["type"] type_metadata = fetch_type_metadata(sql_type) - new_column(field['name'], field['dflt_value'], type_metadata, field['notnull'].to_i == 0, table_name, nil, collation) + new_column(field["name"], field["dflt_value"], type_metadata, field["notnull"].to_i == 0, table_name, nil, collation) end end # Returns an array of indexes for the given table. def indexes(table_name, name = nil) #:nodoc: - exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", 'SCHEMA').map do |row| + exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", "SCHEMA").map do |row| sql = <<-SQL SELECT sql FROM sqlite_master @@ -330,22 +330,22 @@ module ActiveRecord FROM sqlite_temp_master WHERE name=#{quote(row['name'])} AND type='index' SQL - index_sql = exec_query(sql).first['sql'] + index_sql = exec_query(sql).first["sql"] match = /\sWHERE\s+(.+)$/i.match(index_sql) where = match[1] if match IndexDefinition.new( table_name, - row['name'], - row['unique'] != 0, + row["name"], + row["unique"] != 0, exec_query("PRAGMA index_info('#{row['name']}')", "SCHEMA").map { |col| - col['name'] + col["name"] }, nil, nil, where) end end def primary_keys(table_name) # :nodoc: - pks = table_structure(table_name).select { |f| f['pk'] > 0 } - pks.sort_by { |f| f['pk'] }.map { |f| f['name'] } + pks = table_structure(table_name).select { |f| f["pk"] > 0 } + pks.sort_by { |f| f["pk"] }.map { |f| f["name"] } end def remove_index(table_name, options = {}) #:nodoc: @@ -425,7 +425,7 @@ module ActiveRecord protected def table_structure(table_name) - structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA') + structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", "SCHEMA") raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty? table_structure_with_collation(table_name, structure) end @@ -501,15 +501,15 @@ module ActiveRecord from_columns = columns(from).collect(&:name) columns = columns.find_all{|col| from_columns.include?(column_mappings[col])} from_columns_to_copy = columns.map { |col| column_mappings[col] } - quoted_columns = columns.map { |col| quote_column_name(col) } * ',' - quoted_from_columns = from_columns_to_copy.map { |col| quote_column_name(col) } * ',' + quoted_columns = columns.map { |col| quote_column_name(col) } * "," + quoted_from_columns = from_columns_to_copy.map { |col| quote_column_name(col) } * "," exec_query("INSERT INTO #{quote_table_name(to)} (#{quoted_columns}) SELECT #{quoted_from_columns} FROM #{quote_table_name(from)}") end def sqlite_version - @sqlite_version ||= SQLite3Adapter::Version.new(select_value('select sqlite_version(*)')) + @sqlite_version ||= SQLite3Adapter::Version.new(select_value("select sqlite_version(*)")) end def translate_exception(exception, message) @@ -538,24 +538,24 @@ module ActiveRecord # Result will have following sample string # CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, # "password_digest" varchar COLLATE "NOCASE"); - result = exec_query(sql, 'SCHEMA').first + result = exec_query(sql, "SCHEMA").first if result # Splitting with left parentheses and picking up last will return all # columns separated with comma(,). - columns_string = result["sql"].split('(').last + columns_string = result["sql"].split("(").last - columns_string.split(',').each do |column_string| + columns_string.split(",").each do |column_string| # This regex will match the column name and collation type and will save # the value in $1 and $2 respectively. collation_hash[$1] = $2 if COLLATE_REGEX =~ column_string end basic_structure.map! do |column| - column_name = column['name'] + column_name = column["name"] if collation_hash.has_key? column_name - column['collation'] = collation_hash[column_name] + column["collation"] = collation_hash[column_name] end column diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb index f735bc697b..48e1dc1b0c 100644 --- a/activerecord/lib/active_record/connection_handling.rb +++ b/activerecord/lib/active_record/connection_handling.rb @@ -73,7 +73,7 @@ module ActiveRecord private def config @raw_config.dup.tap do |cfg| - if url = ENV['DATABASE_URL'] + if url = ENV["DATABASE_URL"] cfg[@env] ||= {} cfg[@env]["url"] ||= url end diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 3e3a7679ac..26a00e62d1 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -1,7 +1,7 @@ -require 'thread' -require 'active_support/core_ext/hash/indifferent_access' -require 'active_support/core_ext/object/duplicable' -require 'active_support/core_ext/string/filters' +require "thread" +require "active_support/core_ext/hash/indifferent_access" +require "active_support/core_ext/object/duplicable" +require "active_support/core_ext/string/filters" module ActiveRecord module Core @@ -253,7 +253,7 @@ module ActiveRecord elsif !connected? "#{super} (call '#{super}.connection' to establish a connection)" elsif table_exists? - attr_list = attribute_types.map { |name, type| "#{name}: #{type.type}" } * ', ' + attr_list = attribute_types.map { |name, type| "#{name}: #{type.type}" } * ", " "#{super}(#{attr_list})" else "#{super}(Table doesn't exist)" @@ -362,7 +362,7 @@ module ActiveRecord init_internals - @new_record = coder['new_record'] + @new_record = coder["new_record"] self.class.define_attribute_methods @@ -425,8 +425,8 @@ module ActiveRecord # coder # => {"attributes" => {"id" => nil, ... }} def encode_with(coder) self.class.yaml_encoder.encode(@attributes, coder) - coder['new_record'] = new_record? - coder['active_record_yaml_version'] = 2 + coder["new_record"] = new_record? + coder["active_record_yaml_version"] = 2 end # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ @@ -516,19 +516,19 @@ module ActiveRecord pp.object_address_group(self) do if defined?(@attributes) && @attributes column_names = self.class.column_names.select { |name| has_attribute?(name) || new_record? } - pp.seplist(column_names, proc { pp.text ',' }) do |column_name| + pp.seplist(column_names, proc { pp.text "," }) do |column_name| column_value = read_attribute(column_name) - pp.breakable ' ' + pp.breakable " " pp.group(1) do pp.text column_name - pp.text ':' + pp.text ":" pp.breakable pp.pp column_value end end else - pp.breakable ' ' - pp.text 'not initialized' + pp.breakable " " + pp.text "not initialized" end end end diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb index 1b6817554d..d21f7a6126 100644 --- a/activerecord/lib/active_record/counter_cache.rb +++ b/activerecord/lib/active_record/counter_cache.rb @@ -75,12 +75,12 @@ module ActiveRecord # # WHERE id IN (10, 15) def update_counters(id, counters) updates = counters.map do |counter_name, value| - operator = value < 0 ? '-' : '+' + operator = value < 0 ? "-" : "+" quoted_column = connection.quote_column_name(counter_name) "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}" end - unscoped.where(primary_key => id).update_all updates.join(', ') + unscoped.where(primary_key => id).update_all updates.join(", ") end # Increment a numeric field by one, via a direct SQL update. diff --git a/activerecord/lib/active_record/dynamic_matchers.rb b/activerecord/lib/active_record/dynamic_matchers.rb index 0bdebb3989..b41546064b 100644 --- a/activerecord/lib/active_record/dynamic_matchers.rb +++ b/activerecord/lib/active_record/dynamic_matchers.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/regexp' +require "active_support/core_ext/regexp" module ActiveRecord module DynamicMatchers #:nodoc: @@ -44,7 +44,7 @@ module ActiveRecord end def suffix - '' + "" end end @@ -53,7 +53,7 @@ module ActiveRecord def initialize(model, name) @model = model @name = name.to_s - @attribute_names = @name.match(self.class.pattern)[1].split('_and_') + @attribute_names = @name.match(self.class.pattern)[1].split("_and_") @attribute_names.map! { |n| @model.attribute_aliases[n] || n } end @@ -78,13 +78,13 @@ module ActiveRecord # The parameters in the signature may have reserved Ruby words, in order # to prevent errors, we start each param name with `_`. def signature - attribute_names.map { |name| "_#{name}" }.join(', ') + attribute_names.map { |name| "_#{name}" }.join(", ") end # Given that the parameters starts with `_`, the finder needs to use the # same parameter name. def attributes_hash - "{" + attribute_names.map { |name| ":#{name} => _#{name}" }.join(',') + "}" + "{" + attribute_names.map { |name| ":#{name} => _#{name}" }.join(",") + "}" end def finder diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index 5d401beb53..dcf1004879 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/object/deep_dup' +require "active_support/core_ext/object/deep_dup" module ActiveRecord # Declare an enum attribute where the values map to integers in the database, @@ -216,15 +216,15 @@ module ActiveRecord def detect_enum_conflict!(enum_name, method_name, klass_method = false) if klass_method && dangerous_class_method?(method_name) - raise_conflict_error(enum_name, method_name, type: 'class') + raise_conflict_error(enum_name, method_name, type: "class") elsif !klass_method && dangerous_attribute_method?(method_name) raise_conflict_error(enum_name, method_name) elsif !klass_method && method_defined_within?(method_name, _enum_methods_module, Module) - raise_conflict_error(enum_name, method_name, source: 'another enum') + raise_conflict_error(enum_name, method_name, source: "another enum") end end - def raise_conflict_error(enum_name, method_name, type: 'instance', source: 'Active Record') + def raise_conflict_error(enum_name, method_name, type: "instance", source: "Active Record") raise ArgumentError, ENUM_CONFLICT_MESSAGE % { enum: enum_name, klass: self.name, diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb index ac27e72f2b..980b8e1baa 100644 --- a/activerecord/lib/active_record/explain.rb +++ b/activerecord/lib/active_record/explain.rb @@ -1,5 +1,5 @@ -require 'active_support/lazy_load_hooks' -require 'active_record/explain_registry' +require "active_support/lazy_load_hooks" +require "active_record/explain_registry" module ActiveRecord module Explain diff --git a/activerecord/lib/active_record/explain_registry.rb b/activerecord/lib/active_record/explain_registry.rb index b652932f9c..ef1ce3dc85 100644 --- a/activerecord/lib/active_record/explain_registry.rb +++ b/activerecord/lib/active_record/explain_registry.rb @@ -1,4 +1,4 @@ -require 'active_support/per_thread_registry' +require "active_support/per_thread_registry" module ActiveRecord # This is a thread locals registry for EXPLAIN. For example diff --git a/activerecord/lib/active_record/explain_subscriber.rb b/activerecord/lib/active_record/explain_subscriber.rb index 90bcf5a205..706b57842f 100644 --- a/activerecord/lib/active_record/explain_subscriber.rb +++ b/activerecord/lib/active_record/explain_subscriber.rb @@ -1,5 +1,5 @@ -require 'active_support/notifications' -require 'active_record/explain_registry' +require "active_support/notifications" +require "active_record/explain_registry" module ActiveRecord class ExplainSubscriber # :nodoc: diff --git a/activerecord/lib/active_record/fixture_set/file.rb b/activerecord/lib/active_record/fixture_set/file.rb index e4a44244e2..0888208709 100644 --- a/activerecord/lib/active_record/fixture_set/file.rb +++ b/activerecord/lib/active_record/fixture_set/file.rb @@ -1,5 +1,5 @@ -require 'erb' -require 'yaml' +require "erb" +require "yaml" module ActiveRecord class FixtureSet @@ -24,17 +24,17 @@ module ActiveRecord end def model_class - config_row['model_class'] + config_row["model_class"] end private def rows - @rows ||= raw_rows.reject { |fixture_name, _| fixture_name == '_fixture' } + @rows ||= raw_rows.reject { |fixture_name, _| fixture_name == "_fixture" } end def config_row @config_row ||= begin - row = raw_rows.find { |fixture_name, _| fixture_name == '_fixture' } + row = raw_rows.find { |fixture_name, _| fixture_name == "_fixture" } if row row.last else @@ -66,7 +66,7 @@ module ActiveRecord # Validate our unmarshalled data. def validate(data) unless Hash === data || YAML::Omap === data - raise Fixture::FormatError, 'fixture is not a hash' + raise Fixture::FormatError, "fixture is not a hash" end raise Fixture::FormatError unless data.all? { |name, row| Hash === row } diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 0ec33f7d87..601366bc38 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -1,11 +1,11 @@ -require 'erb' -require 'yaml' -require 'zlib' -require 'set' -require 'active_support/dependencies' -require 'active_support/core_ext/digest/uuid' -require 'active_record/fixture_set/file' -require 'active_record/errors' +require "erb" +require "yaml" +require "zlib" +require "set" +require "active_support/dependencies" +require "active_support/core_ext/digest/uuid" +require "active_record/fixture_set/file" +require "active_record/errors" module ActiveRecord class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc: @@ -543,7 +543,7 @@ module ActiveRecord table_rows.each_key do |table| unless deleted_tables.include? table - conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete' + conn.delete "DELETE FROM #{conn.quote_table_name(table)}", "Fixture Delete" end deleted_tables << table end @@ -626,7 +626,7 @@ module ActiveRecord now = config.default_timezone == :utc ? Time.now.utc : Time.now # allow a standard key to be used for doing defaults in YAML - fixtures.delete('DEFAULTS') + fixtures.delete("DEFAULTS") # track any join tables we need to insert later rows = Hash.new { |h,table| h[table] = [] } @@ -868,7 +868,7 @@ module ActiveRecord class_attribute :pre_loaded_fixtures class_attribute :config - singleton_class.deprecate 'use_transactional_fixtures=' => 'use use_transactional_tests= instead' + singleton_class.deprecate "use_transactional_fixtures=" => "use use_transactional_tests= instead" self.fixture_table_names = [] self.use_instantiated_fixtures = false @@ -918,7 +918,7 @@ module ActiveRecord methods = Module.new do fixture_set_names.each do |fs_name| fs_name = fs_name.to_s - accessor_name = fs_name.tr('/', '_').to_sym + accessor_name = fs_name.tr("/", "_").to_sym define_method(accessor_name) do |*fixture_names| force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload @@ -962,7 +962,7 @@ module ActiveRecord def setup_fixtures(config = ActiveRecord::Base) if pre_loaded_fixtures && !use_transactional_tests - raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_tests' + raise RuntimeError, "pre_loaded_fixtures requires use_transactional_tests" end @fixture_cache = {} @@ -986,7 +986,7 @@ module ActiveRecord end # When connections are established in the future, begin a transaction too - @connection_subscriber = ActiveSupport::Notifications.subscribe('!connection.active_record') do |_, _, _, _, payload| + @connection_subscriber = ActiveSupport::Notifications.subscribe("!connection.active_record") do |_, _, _, _, payload| spec_name = payload[:spec_name] if payload.key?(:spec_name) if spec_name @@ -1041,10 +1041,10 @@ module ActiveRecord def instantiate_fixtures if pre_loaded_fixtures - raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::FixtureSet.all_loaded_fixtures.empty? + raise RuntimeError, "Load fixtures before instantiating them." if ActiveRecord::FixtureSet.all_loaded_fixtures.empty? ActiveRecord::FixtureSet.instantiate_all_loaded_fixtures(self, load_instances?) else - raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil? + raise RuntimeError, "Load fixtures before instantiating them." if @loaded_fixtures.nil? @loaded_fixtures.each_value do |fixture_set| ActiveRecord::FixtureSet.instantiate_fixtures(self, fixture_set, load_instances?) end diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index b5fec57c8c..5863f622b5 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/hash/indifferent_access' +require "active_support/core_ext/hash/indifferent_access" module ActiveRecord # == Single table inheritance diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb index d729deb07b..c16909bbb5 100644 --- a/activerecord/lib/active_record/integration.rb +++ b/activerecord/lib/active_record/integration.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/string/filters' +require "active_support/core_ext/string/filters" module ActiveRecord module Integration @@ -100,7 +100,7 @@ module ActiveRecord define_method :to_param do if (default = super()) && (result = send(method_name).to_s).present? && - (param = result.squish.parameterize.truncate(20, separator: /-/, omission: '')).present? + (param = result.squish.parameterize.truncate(20, separator: /-/, omission: "")).present? "#{default}-#{param}" else default diff --git a/activerecord/lib/active_record/internal_metadata.rb b/activerecord/lib/active_record/internal_metadata.rb index 8b649eab0f..20d61dba67 100644 --- a/activerecord/lib/active_record/internal_metadata.rb +++ b/activerecord/lib/active_record/internal_metadata.rb @@ -1,5 +1,5 @@ -require 'active_record/scoping/default' -require 'active_record/scoping/named' +require "active_record/scoping/default" +require "active_record/scoping/named" module ActiveRecord # This class is used to create a table that keeps track of values and keys such diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index 67b8efac66..5e519056a3 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -63,7 +63,7 @@ module ActiveRecord def increment_lock lock_col = self.class.locking_column previous_lock_value = send(lock_col).to_i - send(lock_col + '=', previous_lock_value + 1) + send(lock_col + "=", previous_lock_value + 1) end def _create_record(attribute_names = self.attribute_names, *) # :nodoc: @@ -106,7 +106,7 @@ module ActiveRecord # If something went wrong, revert the version. rescue Exception - send(lock_col + '=', previous_lock_value) + send(lock_col + "=", previous_lock_value) raise end end @@ -133,7 +133,7 @@ module ActiveRecord end module ClassMethods - DEFAULT_LOCKING_COLUMN = 'lock_version' + DEFAULT_LOCKING_COLUMN = "lock_version" # Returns true if the +lock_optimistically+ flag is set to true # (which it is, by default) and the table includes the @@ -198,11 +198,11 @@ module ActiveRecord end def init_with(coder) - __setobj__(coder['subtype']) + __setobj__(coder["subtype"]) end def encode_with(coder) - coder['subtype'] = __getobj__ + coder["subtype"] = __getobj__ end end end diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 1bb4688717..400501fb3d 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -1,6 +1,6 @@ -require 'set' +require "set" require "active_support/core_ext/module/attribute_accessors" -require 'active_support/core_ext/regexp' +require "active_support/core_ext/regexp" module ActiveRecord class MigrationError < ActiveRecordError#:nodoc: @@ -510,8 +510,8 @@ module ActiveRecord # Remember that you can still open your own transactions, even if you # are in a Migration with <tt>self.disable_ddl_transaction!</tt>. class Migration - autoload :CommandRecorder, 'active_record/migration/command_recorder' - autoload :Compatibility, 'active_record/migration/compatibility' + autoload :CommandRecorder, "active_record/migration/command_recorder" + autoload :Compatibility, "active_record/migration/compatibility" # This must be defined before the inherited hook, below class Current < Migration # :nodoc: @@ -830,7 +830,7 @@ module ActiveRecord end def method_missing(method, *arguments, &block) - arg_list = arguments.map(&:inspect) * ', ' + arg_list = arguments.map(&:inspect) * ", " say_with_time "#{method}(#{arg_list})" do unless connection.respond_to? :revert @@ -1052,7 +1052,7 @@ module ActiveRecord end def migrations_paths - @migrations_paths ||= ['db/migrate'] + @migrations_paths ||= ["db/migrate"] # just to not break things if someone uses: migrations_path = some_string Array(@migrations_paths) end diff --git a/activerecord/lib/active_record/migration/compatibility.rb b/activerecord/lib/active_record/migration/compatibility.rb index 74833f938f..5baca7183b 100644 --- a/activerecord/lib/active_record/migration/compatibility.rb +++ b/activerecord/lib/active_record/migration/compatibility.rb @@ -5,7 +5,7 @@ module ActiveRecord version = version.to_s name = "V#{version.tr('.', '_')}" unless const_defined?(name) - versions = constants.grep(/\AV[0-9_]+\z/).map { |s| s.to_s.delete('V').tr('_', '.').inspect } + versions = constants.grep(/\AV[0-9_]+\z/).map { |s| s.to_s.delete("V").tr("_", ".").inspect } raise ArgumentError, "Unknown migration version #{version.inspect}; expected one of #{versions.sort.join(', ')}" end const_get(name) diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index 41cebb0e34..63312a8d11 100644 --- a/activerecord/lib/active_record/model_schema.rb +++ b/activerecord/lib/active_record/model_schema.rb @@ -70,7 +70,7 @@ module ActiveRecord class_attribute :ignored_columns, instance_accessor: false self.ignored_columns = [].freeze - self.inheritance_column = 'type' + self.inheritance_column = "type" delegate :type_for_attribute, to: :class end @@ -316,8 +316,8 @@ module ActiveRecord @content_columns ||= columns.reject do |c| c.name == primary_key || c.name == inheritance_column || - c.name.end_with?('_id') || - c.name.end_with?('_count') + c.name.end_with?("_id") || + c.name.end_with?("_count") end end @@ -412,7 +412,7 @@ module ActiveRecord if parent < Base && !parent.abstract_class? contained = parent.table_name contained = contained.singularize if parent.pluralize_table_names - contained += '_' + contained += "_" end "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{full_table_name_suffix}" diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index fe68869143..819e181f61 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -1,6 +1,6 @@ -require 'active_support/core_ext/hash/except' -require 'active_support/core_ext/object/try' -require 'active_support/core_ext/hash/indifferent_access' +require "active_support/core_ext/hash/except" +require "active_support/core_ext/object/try" +require "active_support/core_ext/hash/indifferent_access" module ActiveRecord module NestedAttributes #:nodoc: @@ -267,7 +267,7 @@ module ActiveRecord # member.avatar_attributes = {icon: 'sad'} # member.avatar.width # => 200 module ClassMethods - REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } } + REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == "_destroy" || value.blank? } } # Defines an attributes writer for the specified association(s). # @@ -400,12 +400,12 @@ module ActiveRecord attributes = attributes.with_indifferent_access existing_record = send(association_name) - if (options[:update_only] || !attributes['id'].blank?) && existing_record && - (options[:update_only] || existing_record.id.to_s == attributes['id'].to_s) + if (options[:update_only] || !attributes["id"].blank?) && existing_record && + (options[:update_only] || existing_record.id.to_s == attributes["id"].to_s) assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes) - elsif attributes['id'].present? - raise_nested_attributes_record_not_found!(association_name, attributes['id']) + elsif attributes["id"].present? + raise_nested_attributes_record_not_found!(association_name, attributes["id"]) elsif !reject_new_record?(association_name, attributes) assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS) @@ -465,7 +465,7 @@ module ActiveRecord if attributes_collection.is_a? Hash keys = attributes_collection.keys - attributes_collection = if keys.include?('id') || keys.include?(:id) + attributes_collection = if keys.include?("id") || keys.include?(:id) [attributes_collection] else attributes_collection.values @@ -477,7 +477,7 @@ module ActiveRecord existing_records = if association.loaded? association.target else - attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact + attribute_ids = attributes_collection.map {|a| a["id"] || a[:id] }.compact attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids) end @@ -487,16 +487,16 @@ module ActiveRecord end attributes = attributes.with_indifferent_access - if attributes['id'].blank? + if attributes["id"].blank? unless reject_new_record?(association_name, attributes) association.build(attributes.except(*UNASSIGNABLE_KEYS)) end - elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s } + elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes["id"].to_s } unless call_reject_if(association_name, attributes) # Make sure we are operating on the actual object which is in the association's # proxy_target array (either by finding it, or adding it if not found) # Take into account that the proxy_target may have changed due to callbacks - target_record = association.target.detect { |record| record.id.to_s == attributes['id'].to_s } + target_record = association.target.detect { |record| record.id.to_s == attributes["id"].to_s } if target_record existing_record = target_record else @@ -506,7 +506,7 @@ module ActiveRecord assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) end else - raise_nested_attributes_record_not_found!(association_name, attributes['id']) + raise_nested_attributes_record_not_found!(association_name, attributes["id"]) end end end @@ -543,7 +543,7 @@ module ActiveRecord # Determines if a hash contains a truthy _destroy key. def has_destroy_flag?(hash) - Type::Boolean.new.cast(hash['_destroy']) + Type::Boolean.new.cast(hash["_destroy"]) end # Determines if a new record should be rejected by checking @@ -581,7 +581,7 @@ module ActiveRecord def raise_nested_attributes_record_not_found!(association_name, record_id) model = self.class._reflect_on_association(association_name).klass.name raise RecordNotFound.new("Couldn't find #{model} with ID=#{record_id} for #{self.class.name} with ID=#{id}", - model, 'id', record_id) + model, "id", record_id) end end end diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 510e8a6e43..dc4af4f390 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -66,7 +66,7 @@ module ActiveRecord def instantiate(attributes, column_types = {}) klass = discriminate_class_for_record(attributes) attributes = klass.attributes_builder.build_from_database(attributes, column_types) - klass.allocate.init_with('attributes' => attributes, 'new_record' => false) + klass.allocate.init_with("attributes" => attributes, "new_record" => false) end private @@ -439,7 +439,7 @@ module ActiveRecord self.class.unscoped { self.class.find(id) } end - @attributes = fresh_object.instance_variable_get('@attributes') + @attributes = fresh_object.instance_variable_get("@attributes") @new_record = false self end diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb index f8dd35df0f..7b4b8c60f8 100644 --- a/activerecord/lib/active_record/querying.rb +++ b/activerecord/lib/active_record/querying.rb @@ -46,7 +46,7 @@ module ActiveRecord class_name: name } - message_bus.instrument('instantiation.active_record', payload) do + message_bus.instrument("instantiation.active_record", payload) do result_set.map { |record| instantiate(record, column_types) } end end diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index 2c0ca62924..19bd1b8e65 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -17,10 +17,10 @@ module ActiveRecord :timestamps => true config.action_dispatch.rescue_responses.merge!( - 'ActiveRecord::RecordNotFound' => :not_found, - 'ActiveRecord::StaleObjectError' => :conflict, - 'ActiveRecord::RecordInvalid' => :unprocessable_entity, - 'ActiveRecord::RecordNotSaved' => :unprocessable_entity + "ActiveRecord::RecordNotFound" => :not_found, + "ActiveRecord::StaleObjectError" => :conflict, + "ActiveRecord::RecordInvalid" => :unprocessable_entity, + "ActiveRecord::RecordNotSaved" => :unprocessable_entity ) @@ -35,8 +35,8 @@ module ActiveRecord ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration if defined?(ENGINE_ROOT) && engine = Rails::Engine.find(ENGINE_ROOT) - if engine.paths['db/migrate'].existent - ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths['db/migrate'].to_a + if engine.paths["db/migrate"].existent + ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths["db/migrate"].to_a end end end @@ -102,7 +102,7 @@ module ActiveRecord initializer "active_record.warn_on_records_fetched_greater_than" do if config.active_record.warn_on_records_fetched_greater_than ActiveSupport.on_load(:active_record) do - require 'active_record/relation/record_fetch_warning' + require "active_record/relation/record_fetch_warning" end end end diff --git a/activerecord/lib/active_record/railties/controller_runtime.rb b/activerecord/lib/active_record/railties/controller_runtime.rb index c13238cbe2..adb3c6c4e6 100644 --- a/activerecord/lib/active_record/railties/controller_runtime.rb +++ b/activerecord/lib/active_record/railties/controller_runtime.rb @@ -1,5 +1,5 @@ -require 'active_support/core_ext/module/attr_internal' -require 'active_record/log_subscriber' +require "active_support/core_ext/module/attr_internal" +require "active_record/log_subscriber" module ActiveRecord module Railties # :nodoc: diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index fc1b62ee96..9481e5f7aa 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -1,4 +1,4 @@ -require 'active_record' +require "active_record" db_namespace = namespace :db do desc "Set the environment value for the database" @@ -22,7 +22,7 @@ db_namespace = namespace :db do 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.' + 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 ActiveRecord::Tasks::DatabaseTasks.create_current end @@ -33,7 +33,7 @@ db_namespace = namespace :db do 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.' + 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 db_namespace["drop:_unsafe"].invoke end @@ -56,7 +56,7 @@ db_namespace = namespace :db do desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)." task :migrate => [:environment, :load_config] do ActiveRecord::Tasks::DatabaseTasks.migrate - db_namespace['_dump'].invoke + db_namespace["_dump"].invoke end # IMPORTANT: This task won't dump the schema if ActiveRecord::Base.dump_schema_after_migration is set to false @@ -71,44 +71,44 @@ db_namespace = namespace :db do end # Allow this task to be called as many times as required. An example is the # migrate:redo task, which calls other two internally that depend on this one. - db_namespace['_dump'].reenable + db_namespace["_dump"].reenable end namespace :migrate do # desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).' task :redo => [:environment, :load_config] do - if ENV['VERSION'] - db_namespace['migrate:down'].invoke - db_namespace['migrate:up'].invoke + if ENV["VERSION"] + db_namespace["migrate:down"].invoke + db_namespace["migrate:up"].invoke else - db_namespace['rollback'].invoke - db_namespace['migrate'].invoke + db_namespace["rollback"].invoke + db_namespace["migrate"].invoke end 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 - version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil - raise 'VERSION is required' unless version + version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil + raise "VERSION is required" unless version ActiveRecord::Migrator.run(:up, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version) - db_namespace['_dump'].invoke + db_namespace["_dump"].invoke end # desc 'Runs the "down" for a given migration VERSION.' 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 + 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) - db_namespace['_dump'].invoke + db_namespace["_dump"].invoke end - desc 'Display status of migrations' + desc "Display status of migrations" task :status => [:environment, :load_config] do unless ActiveRecord::SchemaMigration.table_exists? - abort 'Schema migrations table does not exist yet.' + abort "Schema migrations table does not exist yet." end db_list = ActiveRecord::SchemaMigration.normalized_versions @@ -119,13 +119,13 @@ db_namespace = namespace :db do version, name, scope = ActiveRecord::Migrator.parse_migration_filename(file) version = ActiveRecord::SchemaMigration.normalize_migration_number(version) - status = db_list.delete(version) ? 'up' : 'down' + status = db_list.delete(version) ? "up" : "down" [status, version, (name + scope).humanize] end.compact end db_list.map! do |version| - ['up', version, '********** NO FILE **********'] + ["up", version, "********** NO FILE **********"] end # output puts "\ndatabase: #{ActiveRecord::Base.connection_config[:database]}\n\n" @@ -138,22 +138,22 @@ db_namespace = namespace :db do end end - desc 'Rolls the schema back to the previous version (specify steps w/ STEP=n).' + desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)." task :rollback => [:environment, :load_config] do - step = ENV['STEP'] ? ENV['STEP'].to_i : 1 + step = ENV["STEP"] ? ENV["STEP"].to_i : 1 ActiveRecord::Migrator.rollback(ActiveRecord::Tasks::DatabaseTasks.migrations_paths, step) - db_namespace['_dump'].invoke + db_namespace["_dump"].invoke end # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).' task :forward => [:environment, :load_config] do - step = ENV['STEP'] ? ENV['STEP'].to_i : 1 + step = ENV["STEP"] ? ENV["STEP"].to_i : 1 ActiveRecord::Migrator.forward(ActiveRecord::Tasks::DatabaseTasks.migrations_paths, step) - db_namespace['_dump'].invoke + 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 @@ -165,11 +165,11 @@ db_namespace = namespace :db do begin puts ActiveRecord::Tasks::DatabaseTasks.collation_current rescue NoMethodError - $stderr.puts 'Sorry, your database adapter is not supported yet. Feel free to submit a patch.' + $stderr.puts "Sorry, your database adapter is not supported yet. Feel free to submit a patch." end end - desc 'Retrieves the current schema version number' + desc "Retrieves the current schema version number" task :version => [:environment, :load_config] do puts "Current version: #{ActiveRecord::Migrator.current_version}" end @@ -181,36 +181,36 @@ db_namespace = namespace :db do if pending_migrations.any? puts "You have #{pending_migrations.size} pending #{pending_migrations.size > 1 ? 'migrations:' : 'migration:'}" pending_migrations.each do |pending_migration| - puts ' %4d %s' % [pending_migration.version, pending_migration.name] + puts " %4d %s" % [pending_migration.version, pending_migration.name] end abort %{Run `rails db:migrate` to update your database then try again.} end 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] + 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] - desc 'Loads the seed data from db/seeds.rb' + desc "Loads the seed data from db/seeds.rb" task :seed do - db_namespace['abort_if_pending_migrations'].invoke + db_namespace["abort_if_pending_migrations"].invoke ActiveRecord::Tasks::DatabaseTasks.load_seed end 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 - require 'active_record/fixtures' + require "active_record/fixtures" base_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path - fixtures_dir = if ENV['FIXTURES_DIR'] - File.join base_dir, ENV['FIXTURES_DIR'] + fixtures_dir = if ENV["FIXTURES_DIR"] + File.join base_dir, ENV["FIXTURES_DIR"] else base_dir end - fixture_files = if ENV['FIXTURES'] - ENV['FIXTURES'].split(',') + fixture_files = if ENV["FIXTURES"] + ENV["FIXTURES"].split(",") else # The use of String#[] here is to support namespaced fixtures Dir["#{fixtures_dir}/**/*.yml"].map {|f| f[(fixtures_dir.size + 1)..-5] } @@ -221,10 +221,10 @@ db_namespace = namespace :db do # 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 - require 'active_record/fixtures' + require "active_record/fixtures" - label, id = ENV['LABEL'], ENV['ID'] - raise 'LABEL or ID required' if label.blank? && id.blank? + label, id = ENV["LABEL"], ENV["ID"] + raise "LABEL or ID required" if label.blank? && id.blank? puts %Q(The fixture ID for "#{label}" is #{ActiveRecord::FixtureSet.identify(label)}.) if label @@ -245,37 +245,37 @@ db_namespace = namespace :db do end namespace :schema do - desc 'Creates a db/schema.rb file that is portable against any DB supported by Active Record' + desc "Creates a db/schema.rb file that is portable against any DB supported by Active Record" task :dump => [:environment, :load_config] do - require 'active_record/schema_dumper' - filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, 'schema.rb') + 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| ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file) end - db_namespace['schema:dump'].reenable + db_namespace["schema:dump"].reenable end - desc 'Loads a schema.rb file into the database' + desc "Loads a schema.rb file into the database" task :load => [:environment, :load_config, :check_protected_environments] do - ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV['SCHEMA']) + 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.' + desc "Creates a db/schema_cache.dump file." task :dump => [:environment, :load_config] do con = ActiveRecord::Base.connection filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump") con.schema_cache.clear! con.data_sources.each { |table| con.schema_cache.add(table) } - open(filename, 'wb') { |f| f.write(Marshal.dump(con.schema_cache)) } + open(filename, "wb") { |f| f.write(Marshal.dump(con.schema_cache)) } end - desc 'Clears a db/schema_cache.dump file.' + desc "Clears a db/schema_cache.dump file." task :clear => [:environment, :load_config] do filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump") rm_f filename, verbose: false @@ -285,9 +285,9 @@ db_namespace = namespace :db do end namespace :structure do - desc 'Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql' + desc "Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql" task :dump => [:environment, :load_config] do - filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql") + 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) @@ -298,15 +298,15 @@ db_namespace = namespace :db do f.print "\n" end end - db_namespace['structure:dump'].reenable + db_namespace["structure:dump"].reenable end desc "Recreates the databases from the structure.sql file" task :load => [:environment, :load_config, :check_protected_environments] do - ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:sql, ENV['SCHEMA']) + 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 @@ -335,7 +335,7 @@ db_namespace = namespace :db do begin should_reconnect = ActiveRecord::Base.connection_pool.active_connection? ActiveRecord::Schema.verbose = false - ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations['test'], :ruby, ENV['SCHEMA'] + ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations["test"], :ruby, ENV["SCHEMA"] ensure if should_reconnect ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[ActiveRecord::Tasks::DatabaseTasks.env]) @@ -345,7 +345,7 @@ db_namespace = namespace :db do # desc "Recreate the test database from an existent structure.sql file" task :load_structure => %w(db:test:purge) do - ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations['test'], :sql, ENV['SCHEMA'] + ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations["test"], :sql, ENV["SCHEMA"] end # desc "Recreate the test database from a fresh schema" @@ -366,13 +366,13 @@ db_namespace = namespace :db do # desc "Empty the test database" task :purge => %w(environment load_config check_protected_environments) do - ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations['test'] + ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations["test"] end # desc 'Load the test schema' task :prepare => %w(environment load_config) do unless ActiveRecord::Base.configurations.blank? - db_namespace['test:load'].invoke + db_namespace["test:load"].invoke end end end @@ -382,12 +382,12 @@ 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 - to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map(&:strip) + to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map(&:strip) railties = {} Rails.application.migration_railties.each do |railtie| next unless to_load == :all || to_load.include?(railtie.railtie_name) - if railtie.respond_to?(:paths) && (path = railtie.paths['db/migrate'].first) + if railtie.respond_to?(:paths) && (path = railtie.paths["db/migrate"].first) railties[railtie.railtie_name] = path end end diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index bf398b0d40..bd352d664d 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -1,5 +1,5 @@ -require 'thread' -require 'active_support/core_ext/string/filters' +require "thread" +require "active_support/core_ext/string/filters" module ActiveRecord # = Active Record Reflection diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 0792ba8f76..e96adc9af8 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -62,7 +62,7 @@ module ActiveRecord @klass.connection.insert( im, - 'SQL', + "SQL", primary_key || false, primary_key_value, nil, @@ -86,7 +86,7 @@ module ActiveRecord @klass.connection.update( um, - 'SQL', + "SQL", bvs, ) end @@ -382,7 +382,7 @@ module ActiveRecord stmt.wheres = arel.constraints end - @klass.connection.update stmt, 'SQL', bound_attributes + @klass.connection.update stmt, "SQL", bound_attributes end # Updates an object (or multiple objects) and saves it to the database, if validations pass. @@ -533,7 +533,7 @@ module ActiveRecord stmt.wheres = arel.constraints end - affected = @klass.connection.delete(stmt, 'SQL', bound_attributes) + affected = @klass.connection.delete(stmt, "SQL", bound_attributes) reset affected @@ -671,7 +671,7 @@ module ActiveRecord def inspect entries = records.take([limit_value, 11].compact.min).map!(&:inspect) - entries[10] = '...' if entries.size == 11 + entries[10] = "..." if entries.size == 11 "#<#{self.class.name} [#{entries.join(', ')}]>" end @@ -726,7 +726,7 @@ module ActiveRecord return [] if string.blank? # always convert table names to downcase as in Oracle quoted table names are in uppercase # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries - string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ['raw_sql_'] + string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"] end end end diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb index 20ed4526b0..f4dd106edf 100644 --- a/activerecord/lib/active_record/relation/batches.rb +++ b/activerecord/lib/active_record/relation/batches.rb @@ -1,4 +1,4 @@ -require 'active_record/relation/batches/batch_enumerator' +require "active_record/relation/batches/batch_enumerator" module ActiveRecord module Batches diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index a97b71815a..4af9f0859a 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -225,7 +225,7 @@ module ActiveRecord end def operation_over_aggregate_column(column, operation, distinct) - operation == 'count' ? column.count(distinct) : column.send(operation) + operation == "count" ? column.count(distinct) : column.send(operation) end def execute_simple_calculation(operation, column_name, distinct) #:nodoc: @@ -276,10 +276,10 @@ module ActiveRecord group_aliases = group_fields.map { |field| column_alias_for(field) } group_columns = group_aliases.zip(group_fields) - if operation == 'count' && column_name == :all - aggregate_alias = 'count_all' + if operation == "count" && column_name == :all + aggregate_alias = "count_all" else - aggregate_alias = column_alias_for([operation, column_name].join(' ')) + aggregate_alias = column_alias_for([operation, column_name].join(" ")) end select_values = [ @@ -340,24 +340,24 @@ module ActiveRecord end table_name = keys.to_s.downcase - table_name.gsub!(/\*/, 'all') - table_name.gsub!(/\W+/, ' ') + table_name.gsub!(/\*/, "all") + table_name.gsub!(/\W+/, " ") table_name.strip! - table_name.gsub!(/ +/, '_') + table_name.gsub!(/ +/, "_") @klass.connection.table_alias_for(table_name) end def type_for(field, &block) - field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last + field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split(".").last @klass.type_for_attribute(field_name, &block) end def type_cast_calculated_value(value, type, operation = nil) case operation - when 'count' then value.to_i - when 'sum' then type.deserialize(value || 0) - when 'average' then value.respond_to?(:to_d) ? value.to_d : value + when "count" then value.to_i + when "sum" then type.deserialize(value || 0) + when "average" then value.respond_to?(:to_d) ? value.to_d : value else type.deserialize(value) end end @@ -372,15 +372,15 @@ module ActiveRecord end def build_count_subquery(relation, column_name, distinct) - column_alias = Arel.sql('count_column') - subquery_alias = Arel.sql('subquery_for_count') + column_alias = Arel.sql("count_column") + subquery_alias = Arel.sql("subquery_for_count") aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias) relation.select_values = [aliased_column] subquery = relation.arel.as(subquery_alias) sm = Arel::SelectManager.new relation.engine - select_value = operation_over_aggregate_column(column_alias, 'count', distinct) + select_value = operation_over_aggregate_column(column_alias, "count", distinct) sm.project(select_value).from(subquery) end end diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb index ad74659cba..2cb1df05df 100644 --- a/activerecord/lib/active_record/relation/delegation.rb +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -1,5 +1,5 @@ -require 'active_support/concern' -require 'active_support/core_ext/regexp' +require "active_support/concern" +require "active_support/core_ext/regexp" module ActiveRecord module Delegation # :nodoc: @@ -18,7 +18,7 @@ module ActiveRecord delegate = Class.new(klass) { include ClassSpecificRelation } - const_set klass.name.gsub('::'.freeze, '_'.freeze), delegate + const_set klass.name.gsub("::".freeze, "_".freeze), delegate cache[klass] = delegate end end diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 916dca33bd..6241e0dbdb 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -1,8 +1,8 @@ -require 'active_support/core_ext/string/filters' +require "active_support/core_ext/string/filters" module ActiveRecord module FinderMethods - ONE_AS_ONE = '1 AS one' + ONE_AS_ONE = "1 AS one" # Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). # If one or more records can not be found for the requested ids, then RecordNotFound will be raised. If the primary key @@ -388,7 +388,7 @@ module ActiveRecord [] else arel = relation.arel - rows = connection.select_all(arel, 'SQL', relation.bound_attributes) + rows = connection.select_all(arel, "SQL", relation.bound_attributes) join_dependency.instantiate(rows, aliases) end end @@ -425,7 +425,7 @@ module ActiveRecord relation = relation.except(:select).select(values).distinct! arel = relation.arel - id_rows = @klass.connection.select_all(arel, 'SQL', relation.bound_attributes) + id_rows = @klass.connection.select_all(arel, "SQL", relation.bound_attributes) id_rows.map {|row| row[primary_key]} end diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb index 396638d74d..87a97803d5 100644 --- a/activerecord/lib/active_record/relation/merger.rb +++ b/activerecord/lib/active_record/relation/merger.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/hash/keys' +require "active_support/core_ext/hash/keys" module ActiveRecord class Relation diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index e5496c02b2..8dbff84950 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -1,13 +1,13 @@ module ActiveRecord class PredicateBuilder # :nodoc: - require 'active_record/relation/predicate_builder/array_handler' - require 'active_record/relation/predicate_builder/association_query_handler' - require 'active_record/relation/predicate_builder/base_handler' - require 'active_record/relation/predicate_builder/basic_object_handler' - require 'active_record/relation/predicate_builder/class_handler' - require 'active_record/relation/predicate_builder/polymorphic_array_handler' - require 'active_record/relation/predicate_builder/range_handler' - require 'active_record/relation/predicate_builder/relation_handler' + require "active_record/relation/predicate_builder/array_handler" + require "active_record/relation/predicate_builder/association_query_handler" + require "active_record/relation/predicate_builder/base_handler" + require "active_record/relation/predicate_builder/basic_object_handler" + require "active_record/relation/predicate_builder/class_handler" + require "active_record/relation/predicate_builder/polymorphic_array_handler" + require "active_record/relation/predicate_builder/range_handler" + require "active_record/relation/predicate_builder/relation_handler" delegate :resolve_column_aliases, to: :table @@ -52,7 +52,7 @@ module ActiveRecord key else key = key.to_s - key.split('.'.freeze).first if key.include?('.'.freeze) + key.split(".".freeze).first if key.include?(".".freeze) end end.compact end diff --git a/activerecord/lib/active_record/relation/query_attribute.rb b/activerecord/lib/active_record/relation/query_attribute.rb index 7ba964e802..a68e508fcc 100644 --- a/activerecord/lib/active_record/relation/query_attribute.rb +++ b/activerecord/lib/active_record/relation/query_attribute.rb @@ -1,4 +1,4 @@ -require 'active_record/attribute' +require "active_record/attribute" module ActiveRecord class Relation diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 0749bb30b5..3b86f1c605 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -2,9 +2,9 @@ require "active_record/relation/from_clause" require "active_record/relation/query_attribute" require "active_record/relation/where_clause" require "active_record/relation/where_clause_factory" -require 'active_model/forbidden_attributes_protection' -require 'active_support/core_ext/string/filters' -require 'active_support/core_ext/regexp' +require "active_model/forbidden_attributes_protection" +require "active_support/core_ext/string/filters" +require "active_support/core_ext/regexp" module ActiveRecord module QueryMethods @@ -271,7 +271,7 @@ module ActiveRecord # # => ActiveModel::MissingAttributeError: missing attribute: other_field def select(*fields) return super if block_given? - raise ArgumentError, 'Call this with at least one field' if fields.empty? + raise ArgumentError, "Call this with at least one field" if fields.empty? spawn._select!(*fields) end @@ -1014,7 +1014,7 @@ module ActiveRecord name = from_clause.name case opts when Relation - name ||= 'subquery' + name ||= "subquery" opts.arel.as(name.to_s) else opts @@ -1027,7 +1027,7 @@ module ActiveRecord when Hash, Symbol, Array :association_join else - raise ArgumentError, 'only Hash, Symbol and Array are allowed' + raise ArgumentError, "only Hash, Symbol and Array are allowed" end end @@ -1046,7 +1046,7 @@ module ActiveRecord when Arel::Nodes::Join :join_node else - raise 'unknown class: %s' % join.class.name + raise "unknown class: %s" % join.class.name end end @@ -1125,9 +1125,9 @@ module ActiveRecord if does_not_support_reverse?(o) raise IrreversibleOrderError, "Order #{o.inspect} can not be reversed automatically" end - o.split(',').map! do |s| + o.split(",").map! do |s| s.strip! - s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC') + s.gsub!(/\sasc\Z/i, " DESC") || s.gsub!(/\sdesc\Z/i, " ASC") || s.concat(" DESC") end else o @@ -1150,7 +1150,7 @@ module ActiveRecord end VALID_DIRECTIONS = [:asc, :desc, :ASC, :DESC, - 'asc', 'desc', 'ASC', 'DESC'] # :nodoc: + "asc", "desc", "ASC", "DESC"] # :nodoc: def validate_order_args(args) args.each do |arg| diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb index d5c18a2a4a..619616c878 100644 --- a/activerecord/lib/active_record/relation/spawn_methods.rb +++ b/activerecord/lib/active_record/relation/spawn_methods.rb @@ -1,6 +1,6 @@ -require 'active_support/core_ext/hash/except' -require 'active_support/core_ext/hash/slice' -require 'active_record/relation/merger' +require "active_support/core_ext/hash/except" +require "active_support/core_ext/hash/slice" +require "active_record/relation/merger" module ActiveRecord module SpawnMethods diff --git a/activerecord/lib/active_record/relation/where_clause.rb b/activerecord/lib/active_record/relation/where_clause.rb index 89396b518c..e1376ce00a 100644 --- a/activerecord/lib/active_record/relation/where_clause.rb +++ b/activerecord/lib/active_record/relation/where_clause.rb @@ -120,7 +120,7 @@ module ActiveRecord def invert_predicate(node) case node when NilClass - raise ArgumentError, 'Invalid argument for .where.not(), got nil.' + raise ArgumentError, "Invalid argument for .where.not(), got nil." when Arel::Nodes::In Arel::Nodes::NotIn.new(node.left, node.right) when Arel::Nodes::Equality @@ -158,7 +158,7 @@ module ActiveRecord end end - ARRAY_WITH_EMPTY_STRING = [''] + ARRAY_WITH_EMPTY_STRING = [""] def non_empty_predicates predicates - ARRAY_WITH_EMPTY_STRING end diff --git a/activerecord/lib/active_record/runtime_registry.rb b/activerecord/lib/active_record/runtime_registry.rb index 9e86999c1b..b79eb2263f 100644 --- a/activerecord/lib/active_record/runtime_registry.rb +++ b/activerecord/lib/active_record/runtime_registry.rb @@ -1,4 +1,4 @@ -require 'active_support/per_thread_registry' +require "active_support/per_thread_registry" module ActiveRecord # This is a thread locals registry for Active Record. For example: diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb index f007e9e733..26679bb1c3 100644 --- a/activerecord/lib/active_record/sanitization.rb +++ b/activerecord/lib/active_record/sanitization.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/regexp' +require "active_support/core_ext/regexp" module ActiveRecord module Sanitization @@ -70,7 +70,7 @@ module ActiveRecord # sanitize_sql_for_order("id ASC") # # => "id ASC" def sanitize_sql_for_order(condition) - if condition.is_a?(Array) && condition.first.to_s.include?('?') + if condition.is_a?(Array) && condition.first.to_s.include?("?") sanitize_sql_array(condition) else condition @@ -120,7 +120,7 @@ module ActiveRecord attrs.map do |attr, value| value = type_for_attribute(attr.to_s).serialize(value) "#{c.quote_table_name_for_assignment(table, attr)} = #{c.quote(value)}" - end.join(', ') + end.join(", ") end # Sanitizes a +string+ so that it is safe to use within an SQL @@ -157,7 +157,7 @@ module ActiveRecord statement, *values = ary if values.first.is_a?(Hash) && /:\w+/.match?(statement) replace_named_bind_variables(statement, values.first) - elsif statement.include?('?') + elsif statement.include?("?") replace_bind_variables(statement, values) elsif statement.blank? statement @@ -167,7 +167,7 @@ module ActiveRecord end def replace_bind_variables(statement, values) # :nodoc: - raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size) + raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size) bound = values.dup c = connection statement.gsub(/\?/) do @@ -185,7 +185,7 @@ module ActiveRecord def replace_named_bind_variables(statement, bind_vars) # :nodoc: statement.gsub(/(:?):([a-zA-Z]\w*)/) do |match| - if $1 == ':' # skip postgresql casts + if $1 == ":" # skip postgresql casts match # return the whole match elsif bind_vars.include?(match = $2.to_sym) replace_bind_variable(bind_vars[match]) @@ -200,7 +200,7 @@ module ActiveRecord if value.respond_to?(:empty?) && value.empty? c.quote(nil) else - value.map { |v| c.quote(v) }.join(',') + value.map { |v| c.quote(v) }.join(",") end else c.quote(value) diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index cc3bb1cd06..5105088b2f 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -1,4 +1,4 @@ -require 'stringio' +require "stringio" module ActiveRecord # = Active Record Schema Dumper @@ -111,7 +111,7 @@ HEADER case pk when String - tbl.print ", primary_key: #{pk.inspect}" unless pk == 'id' + tbl.print ", primary_key: #{pk.inspect}" unless pk == "id" pkcol = columns.detect { |c| c.name == pk } pkcolspec = @connection.column_spec_for_primary_key(pkcol) if pkcolspec.present? @@ -161,12 +161,12 @@ HEADER # add column type definition to our format string format_string.unshift " t.%-#{type_length}s " - format_string *= '' + format_string *= "" column_specs.each do |colspec| values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len } values.unshift colspec[:type] - tbl.print((format_string % values).gsub(/,\s*$/, '')) + tbl.print((format_string % values).gsub(/,\s*$/, "")) tbl.puts end @@ -213,7 +213,7 @@ HEADER index.columns.inspect, "name: #{index.name.inspect}", ] - index_parts << 'unique: true' if index.unique + index_parts << "unique: true" if index.unique index_lengths = (index.lengths || []).compact index_parts << "length: #{Hash[index.columns.zip(index.lengths)].inspect}" if index_lengths.any? diff --git a/activerecord/lib/active_record/schema_migration.rb b/activerecord/lib/active_record/schema_migration.rb index b6cb233e03..99b23e5593 100644 --- a/activerecord/lib/active_record/schema_migration.rb +++ b/activerecord/lib/active_record/schema_migration.rb @@ -1,5 +1,5 @@ -require 'active_record/scoping/default' -require 'active_record/scoping/named' +require "active_record/scoping/default" +require "active_record/scoping/named" module ActiveRecord # This class is used to create a table that keeps track of which migrations diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb index 7794af8ca4..78231594d4 100644 --- a/activerecord/lib/active_record/scoping.rb +++ b/activerecord/lib/active_record/scoping.rb @@ -1,4 +1,4 @@ -require 'active_support/per_thread_registry' +require "active_support/per_thread_registry" module ActiveRecord module Scoping diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb index 5395bd6076..46ee3540bd 100644 --- a/activerecord/lib/active_record/scoping/named.rb +++ b/activerecord/lib/active_record/scoping/named.rb @@ -1,6 +1,6 @@ -require 'active_support/core_ext/array' -require 'active_support/core_ext/hash/except' -require 'active_support/core_ext/kernel/singleton_class' +require "active_support/core_ext/array" +require "active_support/core_ext/hash/except" +require "active_support/core_ext/kernel/singleton_class" module ActiveRecord # = Active Record \Named \Scopes @@ -142,7 +142,7 @@ module ActiveRecord # Article.featured.titles def scope(name, body, &block) unless body.respond_to?(:call) - raise ArgumentError, 'The scope body needs to be callable.' + raise ArgumentError, "The scope body needs to be callable." end if dangerous_class_method?(name) diff --git a/activerecord/lib/active_record/secure_token.rb b/activerecord/lib/active_record/secure_token.rb index 8abda2ac49..2c412a45ed 100644 --- a/activerecord/lib/active_record/secure_token.rb +++ b/activerecord/lib/active_record/secure_token.rb @@ -25,7 +25,7 @@ module ActiveRecord # You're encouraged to add a unique index in the database to deal with this even more unlikely scenario. def has_secure_token(attribute = :token) # Load securerandom only when has_secure_token is used. - require 'active_support/core_ext/securerandom' + require "active_support/core_ext/securerandom" define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token } before_create { self.send("#{attribute}=", self.class.generate_unique_secure_token) unless self.send("#{attribute}?")} end diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb index 1b407f7702..2169d64137 100644 --- a/activerecord/lib/active_record/store.rb +++ b/activerecord/lib/active_record/store.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/hash/indifferent_access' +require "active_support/core_ext/hash/indifferent_access" module ActiveRecord # Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. @@ -192,7 +192,7 @@ module ActiveRecord end def load(yaml) - self.class.as_indifferent_hash(@coder.load(yaml || '')) + self.class.as_indifferent_hash(@coder.load(yaml || "")) end def self.as_indifferent_hash(obj) diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index e3e665e149..52b4fcb742 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/string/filters' +require "active_support/core_ext/string/filters" module ActiveRecord module Tasks # :nodoc: @@ -40,10 +40,10 @@ module ActiveRecord attr_writer :current_config, :db_dir, :migrations_paths, :fixtures_path, :root, :env, :seed_loader attr_accessor :database_configuration - LOCAL_HOSTS = ['127.0.0.1', 'localhost'] + LOCAL_HOSTS = ["127.0.0.1", "localhost"] def check_protected_environments! - unless ENV['DISABLE_DATABASE_ENVIRONMENT_CHECK'] + unless ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"] current = ActiveRecord::Migrator.current_environment stored = ActiveRecord::Migrator.last_stored_environment @@ -72,14 +72,14 @@ module ActiveRecord end def migrations_paths - @migrations_paths ||= Rails.application.paths['db/migrate'].to_a + @migrations_paths ||= Rails.application.paths["db/migrate"].to_a end def fixtures_path - @fixtures_path ||= if ENV['FIXTURES_PATH'] - File.join(root, ENV['FIXTURES_PATH']) + @fixtures_path ||= if ENV["FIXTURES_PATH"] + File.join(root, ENV["FIXTURES_PATH"]) else - File.join(root, 'test', 'fixtures') + File.join(root, "test", "fixtures") end end @@ -106,7 +106,7 @@ module ActiveRecord def create(*arguments) configuration = arguments.first - class_for_adapter(configuration['adapter']).new(*arguments).create + class_for_adapter(configuration["adapter"]).new(*arguments).create $stdout.puts "Created database '#{configuration['database']}'" rescue DatabaseAlreadyExists $stderr.puts "Database '#{configuration['database']}' already exists" @@ -133,7 +133,7 @@ module ActiveRecord def drop(*arguments) configuration = arguments.first - class_for_adapter(configuration['adapter']).new(*arguments).drop + class_for_adapter(configuration["adapter"]).new(*arguments).drop $stdout.puts "Dropped database '#{configuration['database']}'" rescue ActiveRecord::NoDatabaseError $stderr.puts "Database '#{configuration['database']}' does not exist" @@ -156,7 +156,7 @@ module ActiveRecord def migrate verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil - scope = ENV['SCOPE'] + scope = ENV["SCOPE"] verbose_was, Migration.verbose = Migration.verbose, verbose Migrator.migrate(migrations_paths, version) do |migration| scope.blank? || scope == migration.scope @@ -172,7 +172,7 @@ module ActiveRecord def charset(*arguments) configuration = arguments.first - class_for_adapter(configuration['adapter']).new(*arguments).charset + class_for_adapter(configuration["adapter"]).new(*arguments).charset end def collation_current(environment = env) @@ -181,11 +181,11 @@ module ActiveRecord def collation(*arguments) configuration = arguments.first - class_for_adapter(configuration['adapter']).new(*arguments).collation + class_for_adapter(configuration["adapter"]).new(*arguments).collation end def purge(configuration) - class_for_adapter(configuration['adapter']).new(configuration).purge + class_for_adapter(configuration["adapter"]).new(configuration).purge end def purge_all @@ -204,13 +204,13 @@ module ActiveRecord def structure_dump(*arguments) configuration = arguments.first filename = arguments.delete_at 1 - class_for_adapter(configuration['adapter']).new(*arguments).structure_dump(filename) + class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename) end def structure_load(*arguments) configuration = arguments.first filename = arguments.delete_at 1 - class_for_adapter(configuration['adapter']).new(*arguments).structure_load(filename) + class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename) end def load_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil) # :nodoc: @@ -285,17 +285,17 @@ module ActiveRecord def each_current_configuration(environment) environments = [environment] - environments << 'test' if environment == 'development' + environments << "test" if environment == "development" configurations = ActiveRecord::Base.configurations.values_at(*environments) configurations.compact.each do |configuration| - yield configuration unless configuration['database'].blank? + yield configuration unless configuration["database"].blank? end end def each_local_configuration ActiveRecord::Base.configurations.each_value do |configuration| - next unless configuration['database'] + next unless configuration["database"] if local_database?(configuration) yield configuration @@ -306,7 +306,7 @@ module ActiveRecord end def local_database?(configuration) - configuration['host'].blank? || LOCAL_HOSTS.include?(configuration['host']) + configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"]) end end end diff --git a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb index 8574807fd2..d10c1b05cd 100644 --- a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb @@ -11,7 +11,7 @@ module ActiveRecord def create establish_connection configuration_without_database - connection.create_database configuration['database'], creation_options + connection.create_database configuration["database"], creation_options establish_connection configuration rescue ActiveRecord::StatementInvalid => error if /database exists/ === error.message @@ -23,26 +23,26 @@ module ActiveRecord if error.respond_to?(:errno) && error.errno == ACCESS_DENIED_ERROR $stdout.print error.message establish_connection root_configuration_without_database - connection.create_database configuration['database'], creation_options - if configuration['username'] != 'root' - connection.execute grant_statement.gsub(/\s+/, ' ').strip + connection.create_database configuration["database"], creation_options + if configuration["username"] != "root" + connection.execute grant_statement.gsub(/\s+/, " ").strip end establish_connection configuration else $stderr.puts error.inspect $stderr.puts "Couldn't create database for #{configuration.inspect}, #{creation_options.inspect}" - $stderr.puts "(If you set the charset manually, make sure you have a matching collation)" if configuration['encoding'] + $stderr.puts "(If you set the charset manually, make sure you have a matching collation)" if configuration["encoding"] end end def drop establish_connection configuration - connection.drop_database configuration['database'] + connection.drop_database configuration["database"] end def purge establish_connection configuration - connection.recreate_database configuration['database'], creation_options + connection.recreate_database configuration["database"], creation_options end def charset @@ -61,15 +61,15 @@ module ActiveRecord args.concat(["--skip-comments"]) args.concat(["#{configuration['database']}"]) - run_cmd('mysqldump', args, 'dumping') + run_cmd("mysqldump", args, "dumping") end def structure_load(filename) args = prepare_command_options - args.concat(['--execute', %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}]) + args.concat(["--execute", %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}]) args.concat(["--database", "#{configuration['database']}"]) - run_cmd('mysql', args, 'loading') + run_cmd("mysql", args, "loading") end private @@ -79,19 +79,19 @@ module ActiveRecord end def configuration_without_database - configuration.merge('database' => nil) + configuration.merge("database" => nil) end def creation_options Hash.new.tap do |options| - options[:charset] = configuration['encoding'] if configuration.include? 'encoding' - options[:collation] = configuration['collation'] if configuration.include? 'collation' + options[:charset] = configuration["encoding"] if configuration.include? "encoding" + options[:collation] = configuration["collation"] if configuration.include? "collation" end end def error_class - if configuration['adapter'].include?('jdbc') - require 'active_record/railties/jdbcmysql_error' + if configuration["adapter"].include?("jdbc") + require "active_record/railties/jdbcmysql_error" ArJdbcMySQL::Error elsif defined?(Mysql2) Mysql2::Error @@ -110,8 +110,8 @@ IDENTIFIED BY '#{configuration['password']}' WITH GRANT OPTION; def root_configuration_without_database configuration_without_database.merge( - 'username' => 'root', - 'password' => root_password + "username" => "root", + "password" => root_password ) end @@ -122,17 +122,17 @@ IDENTIFIED BY '#{configuration['password']}' WITH GRANT OPTION; def prepare_command_options args = { - 'host' => '--host', - 'port' => '--port', - 'socket' => '--socket', - 'username' => '--user', - 'password' => '--password', - 'encoding' => '--default-character-set', - 'sslca' => '--ssl-ca', - 'sslcert' => '--ssl-cert', - 'sslcapath' => '--ssl-capath', - 'sslcipher' => '--ssl-cipher', - 'sslkey' => '--ssl-key' + "host" => "--host", + "port" => "--port", + "socket" => "--socket", + "username" => "--user", + "password" => "--password", + "encoding" => "--default-character-set", + "sslca" => "--ssl-ca", + "sslcert" => "--ssl-cert", + "sslcapath" => "--ssl-capath", + "sslcipher" => "--ssl-cipher", + "sslkey" => "--ssl-key" }.map { |opt, arg| "#{arg}=#{configuration[opt]}" if configuration[opt] }.compact args diff --git a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb index b19ab57ee4..d290b12b73 100644 --- a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb @@ -1,8 +1,8 @@ module ActiveRecord module Tasks # :nodoc: class PostgreSQLDatabaseTasks # :nodoc: - DEFAULT_ENCODING = ENV['CHARSET'] || 'utf8' - ON_ERROR_STOP_1 = 'ON_ERROR_STOP=1'.freeze + DEFAULT_ENCODING = ENV["CHARSET"] || "utf8" + ON_ERROR_STOP_1 = "ON_ERROR_STOP=1".freeze delegate :connection, :establish_connection, :clear_active_connections!, to: ActiveRecord::Base @@ -13,8 +13,8 @@ module ActiveRecord def create(master_established = false) establish_master_connection unless master_established - connection.create_database configuration['database'], - configuration.merge('encoding' => encoding) + connection.create_database configuration["database"], + configuration.merge("encoding" => encoding) establish_connection configuration rescue ActiveRecord::StatementInvalid => error if /database .* already exists/ === error.message @@ -26,7 +26,7 @@ module ActiveRecord def drop establish_master_connection - connection.drop_database configuration['database'] + connection.drop_database configuration["database"] end def charset @@ -48,28 +48,28 @@ module ActiveRecord search_path = case ActiveRecord::Base.dump_schemas when :schema_search_path - configuration['schema_search_path'] + configuration["schema_search_path"] when :all nil when String ActiveRecord::Base.dump_schemas end - args = ['-s', '-x', '-O', '-f', filename] + args = ["-s", "-x", "-O", "-f", filename] unless search_path.blank? - args += search_path.split(',').map do |part| + args += search_path.split(",").map do |part| "--schema=#{part.strip}" end end - args << configuration['database'] - run_cmd('pg_dump', args, 'dumping') + args << configuration["database"] + run_cmd("pg_dump", args, "dumping") File.open(filename, "a") { |f| f << "SET search_path TO #{connection.schema_search_path};\n\n" } end def structure_load(filename) set_psql_env - args = [ '-v', ON_ERROR_STOP_1, '-q', '-f', filename, configuration['database'] ] - run_cmd('psql', args, 'loading' ) + args = [ "-v", ON_ERROR_STOP_1, "-q", "-f", filename, configuration["database"] ] + run_cmd("psql", args, "loading" ) end private @@ -79,21 +79,21 @@ module ActiveRecord end def encoding - configuration['encoding'] || DEFAULT_ENCODING + configuration["encoding"] || DEFAULT_ENCODING end def establish_master_connection establish_connection configuration.merge( - 'database' => 'postgres', - 'schema_search_path' => 'public' + "database" => "postgres", + "schema_search_path" => "public" ) end def set_psql_env - ENV['PGHOST'] = configuration['host'] if configuration['host'] - ENV['PGPORT'] = configuration['port'].to_s if configuration['port'] - ENV['PGPASSWORD'] = configuration['password'].to_s if configuration['password'] - ENV['PGUSER'] = configuration['username'].to_s if configuration['username'] + ENV["PGHOST"] = configuration["host"] if configuration["host"] + ENV["PGPORT"] = configuration["port"].to_s if configuration["port"] + ENV["PGPASSWORD"] = configuration["password"].to_s if configuration["password"] + ENV["PGUSER"] = configuration["username"].to_s if configuration["username"] end def run_cmd(cmd, args, action) diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb index 9ec3c8a94a..8533fb6aa5 100644 --- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb @@ -8,15 +8,15 @@ module ActiveRecord end def create - raise DatabaseAlreadyExists if File.exist?(configuration['database']) + raise DatabaseAlreadyExists if File.exist?(configuration["database"]) establish_connection configuration connection end def drop - require 'pathname' - path = Pathname.new configuration['database'] + require "pathname" + path = Pathname.new configuration["database"] file = path.absolute? ? path.to_s : File.join(root, path) FileUtils.rm(file) @@ -36,12 +36,12 @@ module ActiveRecord end def structure_dump(filename) - dbfile = configuration['database'] + dbfile = configuration["database"] `sqlite3 #{dbfile} .schema > #{filename}` end def structure_load(filename) - dbfile = configuration['database'] + dbfile = configuration["database"] `sqlite3 #{dbfile} < "#{filename}"` end diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index 0ee1ebcfbe..a140dd236f 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -275,12 +275,12 @@ module ActiveRecord end def raise_in_transactional_callbacks - ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks is deprecated and will be removed without replacement.') + ActiveSupport::Deprecation.warn("ActiveRecord::Base.raise_in_transactional_callbacks is deprecated and will be removed without replacement.") true end def raise_in_transactional_callbacks=(value) - ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks= is deprecated, has no effect and will be removed without replacement.') + ActiveSupport::Deprecation.warn("ActiveRecord::Base.raise_in_transactional_callbacks= is deprecated, has no effect and will be removed without replacement.") value end diff --git a/activerecord/lib/active_record/type.rb b/activerecord/lib/active_record/type.rb index 4911d93dd9..1b2fc1b034 100644 --- a/activerecord/lib/active_record/type.rb +++ b/activerecord/lib/active_record/type.rb @@ -1,17 +1,17 @@ -require 'active_model/type' +require "active_model/type" -require 'active_record/type/internal/abstract_json' -require 'active_record/type/internal/timezone' +require "active_record/type/internal/abstract_json" +require "active_record/type/internal/timezone" -require 'active_record/type/date' -require 'active_record/type/date_time' -require 'active_record/type/time' +require "active_record/type/date" +require "active_record/type/date_time" +require "active_record/type/time" -require 'active_record/type/serialized' -require 'active_record/type/adapter_specific_registry' +require "active_record/type/serialized" +require "active_record/type/adapter_specific_registry" -require 'active_record/type/type_map' -require 'active_record/type/hash_lookup_type_map' +require "active_record/type/type_map" +require "active_record/type/hash_lookup_type_map" module ActiveRecord module Type diff --git a/activerecord/lib/active_record/type/adapter_specific_registry.rb b/activerecord/lib/active_record/type/adapter_specific_registry.rb index d440eac619..208bc8def5 100644 --- a/activerecord/lib/active_record/type/adapter_specific_registry.rb +++ b/activerecord/lib/active_record/type/adapter_specific_registry.rb @@ -1,4 +1,4 @@ -require 'active_model/type/registry' +require "active_model/type/registry" module ActiveRecord # :stopdoc: diff --git a/activerecord/lib/active_record/type/type_map.rb b/activerecord/lib/active_record/type/type_map.rb index 850a7a4e09..1f744ef115 100644 --- a/activerecord/lib/active_record/type/type_map.rb +++ b/activerecord/lib/active_record/type/type_map.rb @@ -1,4 +1,4 @@ -require 'concurrent/map' +require "concurrent/map" module ActiveRecord module Type diff --git a/activerecord/lib/active_record/type_caster.rb b/activerecord/lib/active_record/type_caster.rb index accc339d00..f1686e4913 100644 --- a/activerecord/lib/active_record/type_caster.rb +++ b/activerecord/lib/active_record/type_caster.rb @@ -1,5 +1,5 @@ -require 'active_record/type_caster/map' -require 'active_record/type_caster/connection' +require "active_record/type_caster/map" +require "active_record/type_caster/connection" module ActiveRecord module TypeCaster # :nodoc: diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb index cf76a13b44..146cfacc18 100644 --- a/activerecord/lib/active_record/version.rb +++ b/activerecord/lib/active_record/version.rb @@ -1,4 +1,4 @@ -require_relative 'gem_version' +require_relative "gem_version" module ActiveRecord # Returns the version of the currently loaded ActiveRecord as a <tt>Gem::Version</tt> diff --git a/activerecord/lib/rails/generators/active_record.rb b/activerecord/lib/rails/generators/active_record.rb index dc29213235..68fca44e3b 100644 --- a/activerecord/lib/rails/generators/active_record.rb +++ b/activerecord/lib/rails/generators/active_record.rb @@ -1,7 +1,7 @@ -require 'rails/generators/named_base' -require 'rails/generators/active_model' -require 'rails/generators/active_record/migration' -require 'active_record' +require "rails/generators/named_base" +require "rails/generators/active_model" +require "rails/generators/active_record/migration" +require "active_record" module ActiveRecord module Generators # :nodoc: diff --git a/activerecord/lib/rails/generators/active_record/migration.rb b/activerecord/lib/rails/generators/active_record/migration.rb index c2b2209638..4263c11ffc 100644 --- a/activerecord/lib/rails/generators/active_record/migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration.rb @@ -1,4 +1,4 @@ -require 'rails/generators/migration' +require "rails/generators/migration" module ActiveRecord module Generators # :nodoc: 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 de03550ec2..253961071e 100644 --- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb +++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb @@ -1,5 +1,5 @@ -require 'rails/generators/active_record' -require 'active_support/core_ext/regexp' +require "rails/generators/active_record" +require "active_support/core_ext/regexp" module ActiveRecord module Generators # :nodoc: @@ -28,7 +28,7 @@ module ActiveRecord @table_name = normalize_table_name($2) when /join_table/ if attributes.length == 2 - @migration_action = 'join' + @migration_action = "join" @join_tables = pluralize_table_names? ? attributes.map(&:plural_name) : attributes.map(&:singular_name) set_index_names 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 0d72913258..0d89b96ffd 100644 --- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/active_record' +require "rails/generators/active_record" module ActiveRecord module Generators # :nodoc: @@ -22,13 +22,13 @@ module ActiveRecord def create_model_file generate_application_record - template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb") + template "model.rb", File.join("app/models", class_path, "#{file_name}.rb") end def create_module_file return if regular_class_path.empty? generate_application_record - template 'module.rb', File.join('app/models', "#{class_path.join('/')}.rb") if behavior == :invoke + template "module.rb", File.join("app/models", "#{class_path.join('/')}.rb") if behavior == :invoke end hook_for :test_framework @@ -42,13 +42,13 @@ module ActiveRecord # FIXME: Change this file to a symlink once RubyGems 2.5.0 is required. def generate_application_record if self.behavior == :invoke && !application_record_exist? - template 'application_record.rb', application_record_file_name + template "application_record.rb", application_record_file_name end end # Used by the migration template to determine the parent name of the model def parent_class_name - options[:parent] || 'ApplicationRecord' + options[:parent] || "ApplicationRecord" end def application_record_exist? @@ -61,7 +61,7 @@ module ActiveRecord @application_record_file_name ||= if mountable_engine? "app/models/#{namespaced_path}/application_record.rb" else - 'app/models/application_record.rb' + "app/models/application_record.rb" end end end |