How to alias a class method in rails model?

后端 未结 5 1674
一整个雨季
一整个雨季 2020-12-29 23:19

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         


        
相关标签:
5条回答
  • 2020-12-29 23:55
    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
    
    0 讨论(0)
  • 2020-12-30 00:04

    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

    0 讨论(0)
  • 2020-12-30 00:05

    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!

    0 讨论(0)
  • 2020-12-30 00:09

    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)
    
    0 讨论(0)
  • 2020-12-30 00:09

    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

    0 讨论(0)
提交回复
热议问题