instance method
alias_attribute
Ruby on Rails 7.0.10
Since v3.0.20Signature
alias_attribute(new_name, old_name)
Allows you to make aliases for attributes.
class Person include ActiveModel::AttributeMethods attr_accessor :name attribute_method_suffix '_short?' define_attribute_methods :name alias_attribute :nickname, :name private def attribute_short?(attr) send(attr).length < 5 end end person = Person.new person.name = 'Bob' person.name # => "Bob" person.nickname # => "Bob" person.name_short? # => true person.nickname_short? # => true
Parameters
-
new_namereq -
old_namereq
Source
# File activemodel/lib/active_model/attribute_methods.rb, line 204
def alias_attribute(new_name, old_name)
self.attribute_aliases = attribute_aliases.merge(new_name.to_s => old_name.to_s)
ActiveSupport::CodeGenerator.batch(self, __FILE__, __LINE__) do |code_generator|
attribute_method_matchers.each do |matcher|
method_name = matcher.method_name(new_name).to_s
target_name = matcher.method_name(old_name).to_s
parameters = matcher.parameters
mangled_name = target_name
unless NAME_COMPILABLE_REGEXP.match?(target_name)
mangled_name = "__temp__#{target_name.unpack1("h*")}"
end
code_generator.define_cached_method(method_name, as: mangled_name, namespace: :alias_attribute) do |batch|
body = if CALL_COMPILABLE_REGEXP.match?(target_name)
"self.#{target_name}(#{parameters || ''})"
else
call_args = [":'#{target_name}'"]
call_args << parameters if parameters
"send(#{call_args.join(", ")})"
end
modifier = matcher.parameters == FORWARD_PARAMETERS ? "ruby2_keywords " : ""
batch <<
"#{modifier}def #{mangled_name}(#{parameters || ''})" <<
body <<
"end"
end
end
end
end
Defined in activemodel/lib/active_model/attribute_methods.rb line 204
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveModel::AttributeMethods::ClassMethods