instance method
define_read_method
Ruby on Rails 3.1.12
Since v3.0.20 Last seen in v3.1.12 PrivateAvailable in: v3.0.20 v3.1.12
Signature
define_read_method(method_name, attr_name, column)
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
Parameters
-
method_namereq -
attr_namereq -
columnreq
Source
# File activerecord/lib/active_record/attribute_methods/read.rb, line 64
def define_read_method(method_name, attr_name, column)
cast_code = column.type_cast_code('v')
access_code = "(v=@attributes['#{attr_name}']) && #{cast_code}"
unless attr_name.to_s == self.primary_key.to_s
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 =~ ActiveModel::AttributeMethods::COMPILABLE_REGEXP
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__
def _#{method_name}
#{access_code}
end
alias #{method_name} _#{method_name}
STR
else
generated_attribute_methods.module_eval do
define_method("_#{method_name}") { eval(access_code) }
alias_method(method_name, "_#{method_name}")
end
end
end
Defined in activerecord/lib/active_record/attribute_methods/read.rb line 64
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::AttributeMethods::Read::ClassMethods