Ruby 关于 Rails:我可以从 class 方法调用 class 方法吗?

Ruby On Rails: Can I call a class method from a class method?

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

我的模型上有一个 class,我的一个 class 方法越来越长:

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

两者都必须是class方法

如何从 method1 调用此 method2

谢谢。

此处回答:Calling a class method within a class

再次重申:

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

一个完整的class例子:

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' )

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

class Foo
  def self.bar
    puts self
  end
end

Foo.bar
# => Foo

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

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.

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

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!