Ruby on Rails模块包含模块

5

我希望在一个Rails helper中包含一个模块(该helper本身也是一个模块)。

该helper的代码如下:

module SportHelper 
  .....
end

此模块为:

module Formula
  def say()
    ....
  end
end

现在,我想在 SportHelper 中使用方法 say。我该怎么做?

如果我这样写:

module SportHelper 
  def speak1()
    require 'formula'
    extend Formula
    say()
  end

  def speak2()
    require 'formula'
    extend Formula
    say()
  end
end

这个方法可以运行,但我不想这么做,我只想在助手模块上添加方法,而不是添加所有方法。

你好,你的应用程序使用哪个版本的Ruby和Rails? - hernanvicente
为什么不是每个方法都可以使用,哪些方法可以使用呢? - Малъ Скрылевъ
2个回答

5
你只需要在你的helper中包含这个模块:
require 'formula'

module SportHelper
  include Formula

  def speak1
    say
  end

  def speak2
    say
  end
end

也许你不需要这一行require 'formula',如果它已经在加载路径中。要检查这个问题,你可以检查$LOAD_PATH变量。欲了解更多信息,请参见此答案extendinclude的基本区别是,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,它将向类的实例添加方法,但这些方法仅在此方法内部可用。


1
可能需要提到 require 的必要性或者为什么不需要(例如在 Rails 中由于自动加载),鉴于原帖作者对 require vs. include vs. extend 的混淆。 - Peter Alfvin

1

我认为直接包含应该可以工作。

 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

它应该可以工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接