访问类方法,如实例方法

时间:2010-08-05 21:40:20

标签: ruby

class Foo
  def self.bar
    puts "foobar"
  end

  def bar
    self.class.bar
  end
end

我想避免需要定义实例方法bar。有没有办法自动使类方法作为实例方法可访问?也许有一些method_missing?魔法?

2 个答案:

答案 0 :(得分:1)

尝试类似:

class Foo

  def self.bar
    puts "foobar"
  end

  def respond_to? name
    super or self.class.respond_to? name
  end

  def method_missing name, *args, &block
    if self.class.respond_to? name
      self.class.send name, *args, &block
    else
      super
    end
  end

end

你也可以这样做(简单版):

module ChainsToClass
  def respond_to? name
    super or self.class.respond_to? name
  end
  def method_missing name, *args, &block
    if self.class.respond_to? name
      self.class.send name, *args, &block
    else
      super
    end
  end
end

class Foo
  def self.bar
    puts "foobar"
  end
end

Foo.send :include, ChainsToClass

答案 1 :(得分:1)

最简单的方法是在子模块中定义方法并将其扩展并包含在类中:

class Foo

  module FooMethods
    def bar
      puts "foobar"
    end
  end

  # Add methods from module FooMethods as class methods to class Foo
  extend FooMethods

  # Add methods from module FooMethods as instance methods to class Foo
  include FooMethods
end