user2851669
user2851669

Reputation:

call method from an included class when a method with same name is defined in the class

I have the following code - (from rubymonks)

module Foo
  class ClassMethods
    def guitar
      "gently weeps"
    end
  end
end

class Bar
  include Foo
  def self.guitar
    puts "hehe"
    #call guitar function from ClassMethods
  end
end

puts Bar.guitar

Here, how do I call the guitar function from ClassMethods. ClassMethods is not a super class, so can't use super keyword.

Upvotes: 0

Views: 53

Answers (1)

Stefan
Stefan

Reputation: 114188

That kind of structure is usually used to both, include and extend a Module with a single call to include. It works by setting up an included callback that invokes the extend call:

module Foo
  def self.included(mod)
    mod.extend(ClassMethods)
  end

  module ClassMethods
    def guitar
      "gently weeps"
    end
  end
end

class Bar
  include Foo

  def self.guitar
    puts "hehe"
    super
  end
end

puts Bar.guitar
#=> hehe
#=> gently weeps

The above is equivalent to:

module Foo
  module ClassMethods
    def guitar
      "gently weeps"
    end
  end
end

class Bar
  include Foo
  extend Foo::ClassMethods

  def self.guitar
    puts "hehe"
    super
  end
end

Of course, include Foo only makes sense if there are instance methods (or constants / module variables). In your example, you only need extend.

Upvotes: 1

Related Questions