我希望在rails助手中包含一个模块(也是一个模块)。
助手是:
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这是可行的,但我不想这样做,我只想在helper模块上添加方法,而不是每个方法。
发布于 2014-01-03 07:23:29
您只需将此模块包含在您的助手中:
require 'formula'
module SportHelper
include Formula
def speak1
say
end
def speak2
say
end
end也许您不需要这一行require 'formula',如果它已经在加载路径中。要检查这一点,您可以检查$LOAD_PATH变量。有关更多信息,请参见this answer。
extend和include的基本区别在于,包含用于将方法添加到类的实例,扩展用于添加类方法。
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>如果在object方法中使用extend,它会将方法添加到类的实例中,但它们只能在这一个方法中使用。
发布于 2014-01-03 07:28:46
我认为直接包括应该有效
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应该管用的。
https://stackoverflow.com/questions/20898142
复制相似问题