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

Rog*_*ist 8 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
Run Code Online (Sandbox Code Playgroud)

谢谢你花时间......

Ser*_*sev 13

有一个共同的习惯用法.它利用了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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)


Aru*_*hit 5

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"
Run Code Online (Sandbox Code Playgroud)