James McMahon
James McMahon

Reputation: 49659

Accessing module methods from a class in that module?

Under Ruby 2.0, what is the correct way to access a module method from a class in that module?

For instance, if I have

module Foo
    class Foo
        def do_something
            Foo::module_method
        end
    end

    def self.module_method
        puts 'How do I call this?'
    end
end 

I get,

./so-module.rb:7:in do_something': undefined methodmodule_method' for Foo::Foo:Class (NoMethodError) from ./so-module.rb:16:in `'

What is the correct way to define the module method so I can access it from class Foo?

Upvotes: 0

Views: 91

Answers (2)

uncutstone
uncutstone

Reputation: 408

Please take a look at following code:

module Foo
    class Bar
        include Foo
        def do_something
            module_method
        end
    end
    def module_method
        puts 'How do I call this?'
    end
end

b = Foo::Bar.new
b.do_something

result:

How do I call this?

You can even try adding following code:

b1 = Foo::Bar::Bar.new
b1.do_something

It's tricky and has same result:

How do I call this?

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 97004

You have to define the method on the module’s singleton class:

module Foo
  class Bar
    def do_something
      Foo.module_method
    end
  end

  def self.module_method
    'Success!'
  end
end

Foo::Bar.new.do_something  #=> "Success!"

Upvotes: 1

Related Questions