Why Alias_Method Fails in Rails Model

Why alias_method fails in Rails model

ActiveRecord uses method_missing (AFAIK via ActiveModel::AttributeMethods#method_missing) to create attribute accessor and mutator methods the first time they're called. That means that there is no langEN method when you call alias_method and alias_method :name, :langEN fails with your "undefined method" error. Doing the aliasing explicitly:

def name
langEN
end

works because the langEN method will be created (by method_missing) the first time you try to call it.

Rails offers alias_attribute:

alias_attribute(new_name, old_name)

Allows you to make aliases for attributes, which includes getter, setter, and query methods.

which you can use instead:

alias_attribute :name, :langEN

The built-in method_missing will know about aliases registered with alias_attribute and will set up the appropriate aliases as needed.

alias_method on ActiveRecord::Base results in NameError

According a site I found, you're supposed to use alias_attribute instead:

The problem is that ActiveRecord doesn't create the accessor methods
on the fly until the database connection is live and it has parsed the
table schema. That's a long time after the class has been loaded.

class LeadImport::Base < ActiveRecord::Base
alias_attribute :address_1, :address_line_1
end

Rails - alias_method_chain with a 'attribute=' method

alias_method_chain is a simple, two-line method:

def alias_method_chain( target, feature )
alias_method "#{target}_without_#{feature}", target
alias_method target, "#{target}_with_#{feature}"
end

I think the answer you want is to simply make the two alias_method calls yourself in this case:

alias_method :foo_without_bar=, :foo=
alias_method :foo=, :foo_with_bar=

And you would define your method like so:

def foo_with_bar=(value)
...
end

Ruby symbols process the trailing = and ? of method names without a problem.

Rails - Override Alias method

That was an attempt at implementing paranoia mode, I guess. Smelly code, indeed. It overwrites destroy method and you can't call the original implementation anymore (easily). But you can save the original implementation!

class Book < ActiveRecord::Base
alias_method :ar_destroy, :destroy
alias_method :destroy, :disable
end

Now you can call book.ar_destroy to invoke AR's destroy implementation. Although, getting rid of the alias would be a better solution.



Related Topics



Leave a reply



Submit