Rails - Override Alias method

1k views Asked by At

This is a smelly code and the alias method has been used at many places . Now I would want to call the actuals rails .destory method thereby deleting all assocaited dependents of Books - Is there a way I could ignore the alias method and call the .destory AR method ?

class Books < ActiveRecord::Base
  def disable
    self.is_active = false
    save!
  end
  alias_method :destroy, :disable
end
2

There are 2 answers

3
Sergio Tulentsev On BEST ANSWER

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.

0
Ilya On

If you have Ruby >= 2.2, you can use Method#super_method:

book.method(:destroy).super_method.call

In this case, you'll call AR method instead of alias. It's a quick fix, but I suggest to refactor your code.