【问题标题】:Ruby on Rails module include moduleRuby on Rails 模块包含模块
【发布时间】:2014-01-03 06:44:55
【问题描述】:

我想在 rails 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?
  • 为什么不是每个方法,它们有哪些?

标签: ruby-on-rails module


【解决方案1】:

你只需要在你的助手中包含这个模块:

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,它会将方法添加到类的实例中,但它们只能在这个方法中使用。

【讨论】:

  • 可能想提一下require 的必要性或为什么不需要它(例如,由于 Rails 中的自动加载),因为 OP 对 require 与 include 与 extend 的明显混淆。
【解决方案2】:

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

 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

它应该可以工作。

【讨论】:

    猜你喜欢
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    相关资源
    最近更新 更多