如何在rails模型中为类方法添加别名?

时间:2015-04-27 22:34:53

标签: ruby-on-rails ruby

我想在我的一个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,但这对于类方法不起作用。如何在不重复方法的情况下完成此操作?

5 个答案:

答案 0 :(得分:23)

您可以使用:

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)

答案 1 :(得分:1)

我可以确认:

class <<self
  alias_method :alias_for_class_method, :class_method
end

即使从基类继承,也能正常工作。谢谢!

答案 2 :(得分:0)

要将实例方法添加为类方法的别名,可以使用class World def self.hello 'Hello World' end delegate :hello, to: :class end World.hello # => 'Hello World' World.new.hello # => 'Hello World'

示例:

d1 = { "name": "John", "id": 1}
d2 = { "name": "Carl", "id": 5}
d3 = { "name": "John", "id": 1}
s = set()

for d in [d1,d2,d3]:
    if str(d) not in s:
        s.add(str(d))

Link on documentation

答案 3 :(得分:0)

一个快速提醒我,可以使我更快地进行正确的操作是:alias_method应该是您的class定义的最后一部分。

class Foo
  def self.bar(parameter)
    ....
  end

  ...

  singleton_class.send(:alias_method, :new_bar_name, :bar)
end

祝你好运! 干杯

答案 4 :(得分:0)

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