[英]Ruby on Rails module include module
I want to include a module in a rails helper(is also a module). 我想在rails helper中包含一个模块(也是一个模块)。
The helper is: 帮手是:
module SportHelper
.....
end
And the module is: 该模块是:
module Formula
def say()
....
end
end
Now, I want to use the method say
in SportHelper
. 现在,我要使用的方法say
在SportHelper
。 What should I do? 我该怎么办?
If I write like this: 如果我这样写:
module SportHelper
def speak1()
require 'formula'
extend Formula
say()
end
def speak2()
require 'formula'
extend Formula
say()
end
end
This will work, but I don't want to do so, I just want to add the methods on the helper module,not every methods. 这将有效,但我不想这样做,我只是想在辅助模块上添加方法,而不是每个方法。
You need just to include this module in your helper: 您只需要在帮助程序中包含此模块:
require 'formula'
module SportHelper
include Formula
def speak1
say
end
def speak2
say
end
end
Maybe you don't need this line require 'formula'
, if it's already in the load path. 也许你不需要这行require 'formula'
,如果它已经在加载路径中。 For check this you can inspect $LOAD_PATH
variable. 要检查这一点,您可以检查$LOAD_PATH
变量。 For more information see this answer . 有关更多信息,请参阅此答案 。
Basic difference between extend
and include
is that include is for adding methods to an instance of a class and extend is for adding class methods. 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>
And if you use extend
inside the object method, it will adding methods to an instance of a class, but they would be available only inside this one method. 如果在对象方法中使用extend
,它会将方法添加到类的实例中,但它们只能在这个方法中使用。
I think directly include should work 我认为直接包括应该工作
module SportHelper
include SportHelper
.........
end
end
I tested like below: 我测试如下:
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
It should work. 它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.