我想在我的一个Rails模型上给一个类方法起别名。
def self.sub_agent
id = SubAgentStatus.where(name: "active").first.id
where(type: "SubAgent",sub_agent_status_id: id).order(:first_name)
end如果这是一个实例方法,我会简单地使用alias_method,但这不适用于类方法。如何才能在不复制方法的情况下做到这一点?
发布于 2015-04-28 06:38:44
您可以使用:
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 或者尝试:
self.singleton_class.send(:alias_method, :new_name, :original_name)发布于 2017-03-24 00:20:13
我可以证实:
class <<self
alias_method :alias_for_class_method, :class_method
end即使它是从基类继承而来的,也可以完美地工作。谢谢!
发布于 2017-10-26 22:48:38
要添加实例方法作为类方法的别名,可以使用delegate :method_name, to: :class
示例:
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
https://stackoverflow.com/questions/29907157
复制相似问题