[英]Ruby on Rails module include module
我想在rails helper中包含一个模块(也是一个模块)。
帮手是:
module SportHelper
.....
end
该模块是:
module Formula
def say()
....
end
end
现在,我要使用的方法say
在SportHelper
。 我该怎么办?
如果我这样写:
module SportHelper
def speak1()
require 'formula'
extend Formula
say()
end
def speak2()
require 'formula'
extend Formula
say()
end
end
这将有效,但我不想这样做,我只是想在辅助模块上添加方法,而不是每个方法。
您只需要在帮助程序中包含此模块:
require 'formula'
module SportHelper
include Formula
def speak1
say
end
def speak2
say
end
end
也许你不需要这行require 'formula'
,如果它已经在加载路径中。 要检查这一点,您可以检查$LOAD_PATH
变量。 有关更多信息,请参阅此答案 。
extend
和include
基本区别在于include用于向类的实例添加方法,extend用于添加类方法。
module Foo
def foo
puts 'heyyyyoooo!'
end
end
class Bar
include Foo
end
Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class
class Baz
extend Foo
end
Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>
如果在对象方法中使用extend
,它会将方法添加到类的实例中,但它们只能在这个方法中使用。
我认为直接包括应该工作
module SportHelper
include SportHelper
.........
end
end
我测试如下:
module A
def test
puts "aaaa"
end
end
module B
include A
def test1
test
end
end
class C
include B
end
c = C.new()
c.test1 #=> aaaa
它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.