Can a module class method be called from a class n

2019-07-03 14:41发布

问题:

Is it possible to call a module's class method from a nested class method? For instance, if I had:

module A
  def self.foo
    'hello'
  end
end

module A
  class B
    def self.bar
      foo # Fails since A is not in B's ancestor chain
    end
  end
end

I know that I can call foo directly on A by using

def self.bar
  A.foo
end

But ideally I would like a way to have A be part of B's ancestor chain if possible. Any tips would be appreciated.

回答1:

I'm not aware of a straightforward way to do exactly what you're asking. But you can move A's self methods to instance methods in another module and have B extend that module:

module A
  module ClassMethods
    def foo
      'hello'
    end
  end
  extend ClassMethods
end

module A
  class B
    extend A::ClassMethods

    def self.bar
      foo
    end
  end
end


回答2:

With ActiveSupport (you already have it if you use Rails) you can do something like this:

def self.bar
  self.to_s.deconstantize.constantize.foo
end

More about inflectors:

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html