简体   繁体   中英

Ruby on Rails module include module

I want to include a module in a rails helper(is also a module).

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 . 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. For check this you can inspect $LOAD_PATH variable. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM