hahcho
hahcho

Reputation: 1409

Accessing method from specific included module

I have this setup:

module FirstModule
  def foo(arg)
    23 + arg + @private_variable
  end
end

module SecondModule
  def foo(arg)
    24 + arg + @private_variable
  end
end

class Foo
  include FirstModule
  include SecondModule

  def initialize
    @private_variable = 0
  end

  def access_place
    # call FirstModule#foo(1)
    puts foo(1)
  end
end


Foo.new.access_place

I am trying to access FirstModule#foo. I was wondering if there is any way to do so or if you have any other sugggestion. It is important that both methods in this modules have the same name and have access to some private data, so using module_function is not an option.

Upvotes: 0

Views: 41

Answers (4)

koffeinfrei
koffeinfrei

Reputation: 2045

You can get the specific module's method, bind it to self and then call it.

method = FirstModule.instance_method(:foo)
method.bind(self).call

Upvotes: 1

jan.zikan
jan.zikan

Reputation: 1316

Modules are a way how to add methods to the object lookup path. If you include two modules that define method with the same name and list of parameters, only the last defined method will be used.

Upvotes: 0

hahcho
hahcho

Reputation: 1409

Found another solution wihout polluting my class. Using Module#instance_method:

FirstModule.instance_method(:foo).bind(self).call(1)

Upvotes: 0

Stefan
Stefan

Reputation: 114138

You can use alias_method to keep the overridden method:

class Foo
  include FirstModule
  alias_method :first_foo, :foo
  include SecondModule

  def access_place
    first_foo(1)   # FirstModule#foo
    foo(1)         # SecondModule#foo
  end

end

Upvotes: 3

Related Questions