【问题标题】:How to alias a class method in rails model?如何在rails模型中为类方法起别名?
【发布时间】:2015-04-27 22:34:53
【问题描述】:

我想为我的一个 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,但这不适用于类方法。如何在不复制方法的情况下做到这一点?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    你可以使用:

    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)
    

    【讨论】:

    • 感谢您的回答。明天我会试一试,标记为正确。
    • 我想有人忘记了~
    【解决方案2】:

    我可以确认:

    class <<self
      alias_method :alias_for_class_method, :class_method
    end
    

    即使它是从基类继承的,也能完美运行。谢谢!

    【讨论】:

      【解决方案3】:

      要将实例方法添加为类方法的别名,您可以使用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

      【讨论】:

        【解决方案4】:
        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
        

        【讨论】:

          【解决方案5】:

          让我更快地做出正确行为的快速提醒是,这个 alias_method'ing 应该作为你的 class 定义的最后一件事发生。

          class Foo
            def self.bar(parameter)
              ....
            end
          
            ...
          
            singleton_class.send(:alias_method, :new_bar_name, :bar)
          end
          

          祝你好运! 干杯

          【讨论】:

            猜你喜欢
            • 2012-10-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-05-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多