【问题标题】:Ruby On Rails: Can I call a class method from a class method?Ruby On Rails:我可以从类方法调用类方法吗?
【发布时间】:2018-06-10 14:24:12
【问题描述】:

我需要知道是否可以从类方法调用类方法以及如何调用。

我的模型上有一个类,我的一个类方法变长了:

def self.method1(bar)
  # Really long method that I need to split
  # Do things with bar
end

所以我想把这个方法分成2个方法。类似的东西

def self.method1(bar)
  # Do things with bar
  # Call to method2
end

def self.method2(bar)
  # Do things
end

它们都必须是类方法

如何从 method1 调用此 method2

谢谢。

【问题讨论】:

  • 当然你可以打这个电话。你试过了吗?你收到错误了吗?您可能需要使用self. 来限定它:self.method2(bar)
  • 如果它们在你通常调用 method2(bar) 的类中

标签: ruby class-method


【解决方案1】:

这里有答案:Calling a class method within a class

重新迭代:

def self.method1(bar)
  # Do things with bar
  # Call to method2
  method2( bar )
end

一个完整的类示例:

class MyClass
  def self.method1(bar)
    bar = "hello #{ bar }!"
    method2( bar )
  end

  def self.method2(bar)
    puts "bar is #{ bar }"
  end
end

MyClass.method1( 'Foo' )

【讨论】:

    【解决方案2】:

    为了让您了解发生了什么,您必须检查类方法内的范围。

    class Foo
      def self.bar
        puts self
      end
    end
    
    Foo.bar
    # => Foo
    

    Foo.bar被调用时,Foo被返回。不是实例,而是类。这意味着您可以在self.bar 方法中访问Foo 的每个类方法。

    class Foo
      def self.bar
        puts "bar was called"
        self.qux
      end
    
      def self.qux
        puts "qux was called."
      end
    end
    
    Foo.bar
    # => bar was called
    #    qux was called.
    

    【讨论】:

      【解决方案3】:

      self 在类方法的上下文中是类本身。所以可以访问当前类中定义的每一个类方法。上面的例子非常有用,但我想再给你一个更清楚的例子(在我看来):

      class MyClass
         def self.method1
           p self
           puts "#{method2}"
         end
      
         def self.method2
           puts "Hello Ruby World!\n I am class method called from another class method!"
         end
       end
      
      MyClass.method1
      # => MyClass
      
      # => Hello Ruby World!
           I am class method called from another class method!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多