开发者

Accessing class methods like instance methods

开发者 https://www.devze.com 2023-01-10 05:20 出处:网络
class Foo def self.bar puts \"foobar\" end def bar self.class.bar end end I want to refrain from needing to define the instance method bar. Is there a way to automatically make class methods access
class Foo
  def self.bar
    puts "foobar"
  end

  def bar
    self.class.bar
  end
end

I want to refrain from needing to define the instance method bar. Is there a way to automatically make class methods accessible as instance methods? Maybe with some method_mis开发者_如何学Gosing? magic?


Try something like:

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

You can also do this (simple version):

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


The easiest way would be to define methods in a submodule and extend and include it into the class:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消