Ruby on Rails模块包含模块

时间:2014-01-03 06:44:56

标签: ruby-on-rails 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

这样可行,但我不想这样做,我只是想在辅助模块上添加方法,而不是每个方法。

2 个答案:

答案 0 :(得分:2)

您只需要在帮助程序中包含此模块:

require 'formula'

module SportHelper
  include Formula

  def speak1
    say
  end

  def speak2
    say
  end
end

如果它已经在加载路径中,也许您不需要此行require 'formula'。要检查这一点,您可以检查$LOAD_PATH变量。有关详细信息,请参阅this answer

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 :(得分: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

它应该有用。