Can a module class method be called from a class n

2019-07-03 15:09发布

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.

2条回答
叼着烟拽天下
2楼-- · 2019-07-03 15:17

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

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-03 15:35

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
查看更多
登录 后发表回答