Skip to content

Commit

Permalink
Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized i…
Browse files Browse the repository at this point in the history
…nstance vars

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8481 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
jeremy committed Dec 22, 2007
1 parent dc901ce commit 8b5f4e4
Show file tree
Hide file tree
Showing 15 changed files with 282 additions and 237 deletions.
396 changes: 207 additions & 189 deletions activerecord/lib/active_record/associations.rb

Large diffs are not rendered by default.

Expand Up @@ -33,10 +33,10 @@ def find(*args)


if ids.size == 1 if ids.size == 1
id = ids.first.to_i id = ids.first.to_i
record = load_target.detect { |record| id == record.id } record = load_target.detect { |r| id == r.id }
expects_array ? [record] : record expects_array ? [record] : record
else else
load_target.select { |record| ids.include?(record.id) } load_target.select { |r| ids.include?(r.id) }
end end
else else
conditions = "#{@finder_sql}" conditions = "#{@finder_sql}"
Expand Down Expand Up @@ -84,19 +84,19 @@ def insert_record(record, force=true)
else else
columns = @owner.connection.columns(@reflection.options[:join_table], "#{@reflection.options[:join_table]} Columns") columns = @owner.connection.columns(@reflection.options[:join_table], "#{@reflection.options[:join_table]} Columns")


attributes = columns.inject({}) do |attributes, column| attributes = columns.inject({}) do |attrs, column|
case column.name case column.name
when @reflection.primary_key_name when @reflection.primary_key_name
attributes[column.name] = @owner.quoted_id attrs[column.name] = @owner.quoted_id
when @reflection.association_foreign_key when @reflection.association_foreign_key
attributes[column.name] = record.quoted_id attrs[column.name] = record.quoted_id
else else
if record.attributes.has_key?(column.name) if record.has_attribute?(column.name)
value = @owner.send(:quote_value, record[column.name], column) value = @owner.send(:quote_value, record[column.name], column)
attributes[column.name] = value unless value.nil? attrs[column.name] = value unless value.nil?
end end
end end
attributes attrs
end end


sql = sql =
Expand Down
Expand Up @@ -41,10 +41,10 @@ def find(*args)


if ids.size == 1 if ids.size == 1
id = ids.first id = ids.first
record = load_target.detect { |record| id == record.id } record = load_target.detect { |r| id == r.id }
expects_array ? [ record ] : record expects_array ? [ record ] : record
else else
load_target.select { |record| ids.include?(record.id) } load_target.select { |r| ids.include?(r.id) }
end end
else else
conditions = "#{@finder_sql}" conditions = "#{@finder_sql}"
Expand Down
Expand Up @@ -262,12 +262,31 @@ def construct_sql
end end


def conditions def conditions
@conditions ||= [ @conditions = build_conditions unless defined?(@conditions)
(interpolate_sql(@reflection.klass.send(:sanitize_sql, @reflection.options[:conditions])) if @reflection.options[:conditions]), @conditions
(interpolate_sql(@reflection.active_record.send(:sanitize_sql, @reflection.through_reflection.options[:conditions])) if @reflection.through_reflection.options[:conditions]), end
(interpolate_sql(@reflection.active_record.send(:sanitize_sql, @reflection.source_reflection.options[:conditions])) if @reflection.source_reflection.options[:conditions]),
("#{@reflection.through_reflection.table_name}.#{@reflection.through_reflection.klass.inheritance_column} = #{@reflection.klass.quote_value(@reflection.through_reflection.klass.name.demodulize)}" unless @reflection.through_reflection.klass.descends_from_active_record?) def build_conditions
].compact.collect { |condition| "(#{condition})" }.join(' AND ') unless (!@reflection.options[:conditions] && !@reflection.through_reflection.options[:conditions] && !@reflection.source_reflection.options[:conditions] && @reflection.through_reflection.klass.descends_from_active_record?) association_conditions = @reflection.options[:conditions]
through_conditions = @reflection.through_reflection.options[:conditions]
source_conditions = @reflection.source_reflection.options[:conditions]
uses_sti = !@reflection.through_reflection.klass.descends_from_active_record?

if association_conditions || through_conditions || source_conditions || uses_sti
all = []

[association_conditions, through_conditions, source_conditions].each do |conditions|
all << interpolate_sql(sanitize_sql(conditions)) if conditions
end

all << build_sti_condition if uses_sti

all.map { |sql| "(#{sql})" } * ' AND '
end
end

def build_sti_condition
"#{@reflection.through_reflection.table_name}.#{@reflection.through_reflection.klass.inheritance_column} = #{@reflection.klass.quote_value(@reflection.through_reflection.klass.name.demodulize)}"
end end


alias_method :sql_conditions, :conditions alias_method :sql_conditions, :conditions
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/attribute_methods.rb
Expand Up @@ -5,7 +5,7 @@ module AttributeMethods #:nodoc:


def self.included(base) def self.included(base)
base.extend ClassMethods base.extend ClassMethods
base.attribute_method_suffix *DEFAULT_SUFFIXES base.attribute_method_suffix(*DEFAULT_SUFFIXES)
base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
base.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT base.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
end end
Expand Down
32 changes: 18 additions & 14 deletions activerecord/lib/active_record/base.rb
Expand Up @@ -592,7 +592,7 @@ def create(attributes = nil)
def update(id, attributes) def update(id, attributes)
if id.is_a?(Array) if id.is_a?(Array)
idx = -1 idx = -1
id.collect { |id| idx += 1; update(id, attributes[idx]) } id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) }
else else
object = find(id) object = find(id)
object.update_attributes(attributes) object.update_attributes(attributes)
Expand Down Expand Up @@ -642,7 +642,11 @@ def delete(id)
# todos = [1,2,3] # todos = [1,2,3]
# Todo.destroy(todos) # Todo.destroy(todos)
def destroy(id) def destroy(id)
id.is_a?(Array) ? id.each { |id| destroy(id) } : find(id).destroy if id.is_a?(Array)
id.map { |one_id| destroy(one_id) }
else
find(id).destroy
end
end end


# Updates all records with details given if they match a set of conditions supplied, limits and order can # Updates all records with details given if they match a set of conditions supplied, limits and order can
Expand Down Expand Up @@ -1075,9 +1079,9 @@ def table_exists?


# Returns an array of column objects for the table associated with this class. # Returns an array of column objects for the table associated with this class.
def columns def columns
unless @columns unless defined?(@columns) && @columns
@columns = connection.columns(table_name, "#{name} Columns") @columns = connection.columns(table_name, "#{name} Columns")
@columns.each {|column| column.primary = column.name == primary_key} @columns.each { |column| column.primary = column.name == primary_key }
end end
@columns @columns
end end
Expand Down Expand Up @@ -1217,7 +1221,7 @@ def base_class
# Returns whether this class is a base AR class. If A is a base class and # Returns whether this class is a base AR class. If A is a base class and
# B descends from A, then B.base_class will return B. # B descends from A, then B.base_class will return B.
def abstract_class? def abstract_class?
abstract_class == true defined?(@abstract_class) && @abstract_class == true
end end


private private
Expand Down Expand Up @@ -1428,7 +1432,7 @@ def add_joins!(sql, options, scope = :auto)
case join case join
when Symbol, Hash, Array when Symbol, Hash, Array
join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil) join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil)
sql << " #{join_dependency.join_associations.collect{|join| join.association_join }.join} " sql << " #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} "
else else
sql << " #{join} " sql << " #{join} "
end end
Expand Down Expand Up @@ -1962,7 +1966,7 @@ def id=(value)


# Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet. # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet.
def new_record? def new_record?
@new_record defined?(@new_record) && @new_record
end end


# * No record exists: Creates a new record with values matching those of the object attributes. # * No record exists: Creates a new record with values matching those of the object attributes.
Expand Down Expand Up @@ -2213,7 +2217,7 @@ def frozen?
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back # Returns +true+ if the record is read only. Records loaded through joins with piggy-back
# attributes will be marked as read only since they cannot be saved. # attributes will be marked as read only since they cannot be saved.
def readonly? def readonly?
@readonly == true defined?(@readonly) && @readonly == true
end end


# Marks this record as read only. # Marks this record as read only.
Expand Down Expand Up @@ -2334,11 +2338,11 @@ def attributes_protected_by_default
# Returns a copy of the attributes hash where all the values have been safely quoted for use in # Returns a copy of the attributes hash where all the values have been safely quoted for use in
# an SQL statement. # an SQL statement.
def attributes_with_quotes(include_primary_key = true, include_readonly_attributes = true) def attributes_with_quotes(include_primary_key = true, include_readonly_attributes = true)
quoted = attributes.inject({}) do |quoted, (name, value)| quoted = attributes.inject({}) do |result, (name, value)|
if column = column_for_attribute(name) if column = column_for_attribute(name)
quoted[name] = quote_value(value, column) unless !include_primary_key && column.primary result[name] = quote_value(value, column) unless !include_primary_key && column.primary
end end
quoted result
end end
include_readonly_attributes ? quoted : remove_readonly_attributes(quoted) include_readonly_attributes ? quoted : remove_readonly_attributes(quoted)
end end
Expand Down Expand Up @@ -2454,9 +2458,9 @@ def object_from_yaml(string)
end end


def clone_attributes(reader_method = :read_attribute, attributes = {}) def clone_attributes(reader_method = :read_attribute, attributes = {})
self.attribute_names.inject(attributes) do |attributes, name| self.attribute_names.inject(attributes) do |attrs, name|
attributes[name] = clone_attribute_value(reader_method, name) attrs[name] = clone_attribute_value(reader_method, name)
attributes attrs
end end
end end


Expand Down
Expand Up @@ -71,7 +71,7 @@ def clear_active_connection_name #:nodoc:
# also be used to "borrow" the connection to do database work unrelated # also be used to "borrow" the connection to do database work unrelated
# to any of the specific Active Records. # to any of the specific Active Records.
def connection def connection
if @active_connection_name && (conn = active_connections[@active_connection_name]) if defined?(@active_connection_name) && (conn = active_connections[@active_connection_name])
conn conn
else else
# retrieve_connection sets the cache key. # retrieve_connection sets the cache key.
Expand Down
Expand Up @@ -192,14 +192,14 @@ def fast_string_to_time(string)
end end


def fallback_string_to_date(string) def fallback_string_to_date(string)
new_date *ParseDate.parsedate(string)[0..2] new_date(*ParseDate.parsedate(string)[0..2])
end end


def fallback_string_to_time(string) def fallback_string_to_time(string)
time_hash = Date._parse(string) time_hash = Date._parse(string)
time_hash[:sec_fraction] = microseconds(time_hash) time_hash[:sec_fraction] = microseconds(time_hash)


new_time *time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction) new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
end end
end end


Expand Down
Expand Up @@ -30,6 +30,7 @@ def initialize(connection, logger = nil) #:nodoc:
@connection, @logger = connection, logger @connection, @logger = connection, logger
@runtime = 0 @runtime = 0
@last_verification = 0 @last_verification = 0
@query_cache_enabled = false
end end


# Returns the human-readable name of the adapter. Use mixed case - one # Returns the human-readable name of the adapter. Use mixed case - one
Expand Down
9 changes: 4 additions & 5 deletions activerecord/lib/active_record/migration.rb
Expand Up @@ -230,7 +230,7 @@ def migrate(direction)
# recursively. We use @ignore_new_methods as a guard to indicate whether # recursively. We use @ignore_new_methods as a guard to indicate whether
# it is safe for the call to proceed. # it is safe for the call to proceed.
def singleton_method_added(sym) #:nodoc: def singleton_method_added(sym) #:nodoc:
return if @ignore_new_methods return if defined?(@ignore_new_methods) && @ignore_new_methods


begin begin
@ignore_new_methods = true @ignore_new_methods = true
Expand Down Expand Up @@ -356,15 +356,14 @@ def pending_migrations


private private
def migration_classes def migration_classes
migrations = migration_files.inject([]) do |migrations, migration_file| classes = migration_files.inject([]) do |migrations, migration_file|
load(migration_file) load(migration_file)
version, name = migration_version_and_name(migration_file) version, name = migration_version_and_name(migration_file)
assert_unique_migration_version(migrations, version.to_i) assert_unique_migration_version(migrations, version.to_i)
migrations << migration_class(name, version.to_i) migrations << migration_class(name, version.to_i)
end end.sort_by(&:version)


sorted = migrations.sort_by { |m| m.version } down? ? classes.reverse : classes
down? ? sorted.reverse : sorted
end end


def assert_unique_migration_version(migrations, version) def assert_unique_migration_version(migrations, version)
Expand Down
6 changes: 3 additions & 3 deletions activerecord/lib/active_record/transactions.rb
Expand Up @@ -15,7 +15,7 @@ def self.included(base)
end end
end end


# Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. # Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action.
# The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and # The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and
# vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. # vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs.
# So basically you should use transaction blocks whenever you have a number of statements that must be executed together or # So basically you should use transaction blocks whenever you have a number of statements that must be executed together or
Expand Down Expand Up @@ -116,7 +116,7 @@ def save_with_transactions! #:nodoc:
def rollback_active_record_state! def rollback_active_record_state!
id_present = has_attribute?(self.class.primary_key) id_present = has_attribute?(self.class.primary_key)
previous_id = id previous_id = id
previous_new_record = @new_record previous_new_record = new_record?
yield yield
rescue Exception rescue Exception
@new_record = previous_new_record @new_record = previous_new_record
Expand All @@ -125,7 +125,7 @@ def rollback_active_record_state!
else else
@attributes.delete(self.class.primary_key) @attributes.delete(self.class.primary_key)
@attributes_cache.delete(self.class.primary_key) @attributes_cache.delete(self.class.primary_key)
end end
raise raise
end end
end end
Expand Down
7 changes: 5 additions & 2 deletions activerecord/test/active_schema_test_mysql.rb
Expand Up @@ -3,13 +3,16 @@
class ActiveSchemaTest < Test::Unit::TestCase class ActiveSchemaTest < Test::Unit::TestCase
def setup def setup
ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
alias_method :real_execute, :execute alias_method :execute_without_stub, :execute
def execute(sql, name = nil) return sql end def execute(sql, name = nil) return sql end
end end
end end


def teardown def teardown
ActiveRecord::ConnectionAdapters::MysqlAdapter.send(:alias_method, :execute, :real_execute) ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
remove_method :execute
alias_method :execute, :execute_without_stub
end
end end


def test_drop_table def test_drop_table
Expand Down
1 change: 1 addition & 0 deletions activerecord/test/adapter_test.rb
Expand Up @@ -76,6 +76,7 @@ class << @connection
assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts') assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts')


class << @connection class << @connection
remove_method :table_alias_length
alias_method :table_alias_length, :old_table_alias_length alias_method :table_alias_length, :old_table_alias_length
end end
end end
Expand Down
2 changes: 1 addition & 1 deletion activerecord/test/associations/callbacks_test.rb
Expand Up @@ -128,7 +128,7 @@ def test_has_many_and_belongs_to_many_callbacks_for_save_on_parent
callback_log = ["before_adding<new>", "after_adding<new>"] callback_log = ["before_adding<new>", "after_adding<new>"]
assert_equal callback_log, project.developers_log assert_equal callback_log, project.developers_log
assert project.save assert project.save
assert_equal 1, project.developers_with_callbacks.count assert_equal 1, project.developers_with_callbacks.size
assert_equal callback_log, project.developers_log assert_equal callback_log, project.developers_log
end end


Expand Down
6 changes: 3 additions & 3 deletions activerecord/test/associations/join_model_test.rb
Expand Up @@ -304,7 +304,7 @@ def test_belongs_to_polymorphic_with_counter_cache
end end


def test_unavailable_through_reflection def test_unavailable_through_reflection
assert_raises (ActiveRecord::HasManyThroughAssociationNotFoundError) { authors(:david).nothings } assert_raise(ActiveRecord::HasManyThroughAssociationNotFoundError) { authors(:david).nothings }
end end


def test_has_many_through_join_model_with_conditions def test_has_many_through_join_model_with_conditions
Expand All @@ -313,10 +313,10 @@ def test_has_many_through_join_model_with_conditions
end end


def test_has_many_polymorphic def test_has_many_polymorphic
assert_raises ActiveRecord::HasManyThroughAssociationPolymorphicError do assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicError do
assert_equal posts(:welcome, :thinking), tags(:general).taggables assert_equal posts(:welcome, :thinking), tags(:general).taggables
end end
assert_raises ActiveRecord::EagerLoadPolymorphicError do assert_raise ActiveRecord::EagerLoadPolymorphicError do
assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable) assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable)
end end
end end
Expand Down

0 comments on commit 8b5f4e4

Please sign in to comment.