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: \"SubAg
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
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
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!
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)
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'
Link on documentation