我可以从同一个模块添加类方法和实例方法吗?

时间:2013-05-13 15:11:14

标签: ruby

新手问题:

我知道如何包含和扩展工作,我想知道是否有办法从单个模块获取类和实例方法?

这是我使用两个模块的方式:

module InstanceMethods
    def mod1
        "mod1"
    end
end

module ClassMethods
    def mod2
        "mod2"
    end
end

class Testing
    include InstanceMethods
    extend ClassMethods 
end

t = Testing.new
puts t.mod1
puts Testing::mod2

感谢您抽出宝贵的时间......

3 个答案:

答案 0 :(得分:12)

有一个共同的习惯用法。它使用included对象模型钩子。每次将模块包含在模块/类

中时,都会调用此挂钩
module MyExtensions
  def self.included(base)
    # base is our target class. Invoke `extend` on it and pass nested module with class methods.
    base.extend ClassMethods
  end

  def mod1
    "mod1"
  end

  module ClassMethods
    def mod2
      "mod2"
    end
  end
end

class Testing
  include MyExtensions
end

t = Testing.new
puts t.mod1
puts Testing::mod2
# >> mod1
# >> mod2

我个人也喜欢将实例方法分组到嵌套模块。但据我所知,这是不太被接受的做法。

module MyExtensions
  def self.included(base)
    base.extend ClassMethods
    base.include(InstanceMethods)

    # or this, if you have an old ruby and the line above doesn't work
    # base.send :include, InstanceMethods
  end

  module InstanceMethods
    def mod1
      "mod1"
    end
  end

  module ClassMethods
    def mod2
      "mod2"
    end
  end
end

答案 1 :(得分:3)

module Foo
 def self.included(m)
   def m.show1
     p "hi"
   end
 end

 def show2
   p "hello"

 end
end

class Bar
 include Foo
end

Bar.new.show2 #=> "hello"
Bar.show1 #=> "hi"

答案 2 :(得分:2)

是。由于红宝石的天才,它就像你期望的一样简单:

module Methods
    def mod
        "mod"
    end
end

class Testing
    include Methods # will add mod as an instance method
    extend Methods # will add mod as a class method
end

t = Testing.new
puts t.mod
puts Testing::mod

或者,你可以这样做:

module Methods
    def mod1
        "mod1"
    end

    def mod2
        "mod2"
    end
end

class Testing
    include Methods # will add both mod1 and mod2 as instance methods
    extend Methods # will add both mod1 and mod2 as class methods
end

t = Testing.new
puts t.mod1
puts Testing::mod2
# But then you'd also get
puts t.mod2
puts Testing::mod1