Define an attribute reader method. Cope with nil column. method_name is
the same as attr_name except when a non-standard primary key is used, we
still define #id as an accessor for the key
# File activerecord/lib/active_record/attribute_methods/read.rb, line 60
def define_read_method(method_name, attr_name, column)
cast_code = column.type_cast_code('v') if column
access_code = cast_code ? "(v=@attributes['#{attr_name}']) && #{cast_code}" : "@attributes['#{attr_name}']"
unless attr_name.to_s == self.primary_key.to_s
access_code = access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ")
end
if cache_attribute?(attr_name)
access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})"
end
# Where possible, generate the method by evalling a string, as this will result in
# faster accesses because it avoids the block eval and then string eval incurred
# by the second branch.
#
# The second, slower, branch is necessary to support instances where the database
# returns columns with extra stuff in (like 'my_column(omg)').
if method_name =~ /^[a-zA-Z_]\w*[!?=]?$/
generated_attribute_methods.module_eval def _#{method_name} #{access_code} end alias #{method_name} _#{method_name}, __FILE__, __LINE__
else
generated_attribute_methods.module_eval do
define_method("_#{method_name}") { eval(access_code) }
alias_method(method_name, "_#{method_name}")
end
end
end