Reputation: 3308
I want to alias a class method on one of my Rails models.
def self.sub_agent
id = SubAgentStatus.where(name: "active").first.id
where(type: "SubAgent",sub_agent_status_id: id).order(:first_name)
end
If this was an instance method, I would simply use alias_method
, but that doesn't work for class methods. How can I do this without duplicating the method?
Upvotes: 37
Views: 17453
Reputation: 8403
You can use alias_method
with any class, not just classes that you wrote, and this answer does not require Rails.
For example, to alias the method ActiveSupport::NumberHelper.number_to_human_size
as to_human
:
require 'active_support'
require 'active_support/core_ext/numeric/conversions'
ActiveSupport::NumberHelper.alias_method :to_human, :number_to_human_size
nh = ActiveSupport::NumberHelper
puts nh.to_human 123456
The above prints: 121 KB
.
Upvotes: 0
Reputation: 7511
class Foo
def self.sub_agent
id = SubAgentStatus.where(name: "active").first.id
where(type: "SubAgent",sub_agent_status_id: id).order(:first_name)
end
self.singleton_class.send(:alias_method, :sub_agent_new, :sub_agent)
end
Upvotes: 1
Reputation: 206
A quick reminder that would have gotten me to the right behaviour a bit faster is that this alias_method
'ing should happen as the last thing of your class
definition.
class Foo
def self.bar(parameter)
....
end
...
singleton_class.send(:alias_method, :new_bar_name, :bar)
end
Good luck! Cheers
Upvotes: 1
Reputation: 17919
To add instance method as an alias for class method you can use delegate :method_name, to: :class
Example:
class World
def self.hello
'Hello World'
end
delegate :hello, to: :class
end
World.hello
# => 'Hello World'
World.new.hello
# => 'Hello World'
Upvotes: 2
Reputation: 1149
I can confirm that:
class <<self
alias_method :alias_for_class_method, :class_method
end
works perfectly even when it is inherited from a base class. Thanks!
Upvotes: 1
Reputation: 11137
You can use:
class Foo
def instance_method
end
alias_method :alias_for_instance_method, :instance_method
def self.class_method
end
class <<self
alias_method :alias_for_class_method, :class_method
end
end
OR Try:
self.singleton_class.send(:alias_method, :new_name, :original_name)
Upvotes: 60