Forum: Ruby on Rails Need a bit help on "module_function" method

249c7fd851c5c5ac5a1abdb756472ae1?d=identicon&s=25 Arup Rakshit (my-ruby)
on 2013-08-29 21:16
The documentation is very straight forward and the mentioned example
also cleared all the lines except the one mentioned inside **.

http://ruby-doc.org/core-2.0.0/Module.html#method-...

Creates module functions for the named methods. These functions may be
called with the module as a receiver, and also become available as
instance methods to classes that mix in the module. Module functions are
copies of the original, and so may be changed independently. The
instance-method versions are made private. *If used with no arguments,
subsequently defined methods become module functions.*


module Mod
  def one
    "This is one"
  end
  module_function :one
end
class Cls
  include Mod
  def call_one
    one
  end
end
Mod.one     #=> "This is one"
c = Cls.new
c.call_one  #=> "This is one"
module Mod
  def one
    "This is the new one"
  end
end
Mod.one     #=> "This is one"
c.call_one  #=> "This is the new one"

Please help me to understand what does mean by "If used with no
arguments, subsequently defined methods become module functions."?
249c7fd851c5c5ac5a1abdb756472ae1?d=identicon&s=25 Arup Rakshit (my-ruby)
on 2013-08-29 21:24
> Please help me to understand what does mean by "If used with no
> arguments, subsequently defined methods become module functions."?

Okay got it now:-

module Party
  module_function
  def foo
    "I am foo"
  end
  def bar
    "I am bar"
  end
end

Party.foo # => "I am foo"
Party.bar # => "I am bar"
Aa082c8b00a50928e5860dcd70bf2368?d=identicon&s=25 tamouse m. (tamouse_m)
on 2013-08-30 07:39
(Received via mailing list)
On Aug 29, 2013, at 2:16 PM, Love U Ruby <lists@ruby-forum.com> wrote:
> Please help me to understand what does mean by "If used with no
> arguments, subsequently defined methods become module functions."?

That means you can use it as a means of saying "All the methods defined
below are module functions":


Module M

  def foo
  end

  module_function

  def bar
  end

  def baz
  end

end

and so you can then call M.bar and M.baz, but not M.foo.

This is identical to:

Module M
  def foo;end
  def bar;end
  def baz;end
  module_function :bar, :baz
end

It is *also* identical to:

Module M
  def foo;end
  def self.bar; end
  def self.baz; end
end
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.