Misha Moroshko
Misha Moroshko

Reputation: 171321

How to wrap instance and class methods in Ruby?

I would like to add to class D some common functionality that composed of instance methods and class methods. I tried to do this like below, but it didn't work. What is the right way to achieve this ?

module A
  def foo
    puts "foo!"
  end
end

module B
  def wow
    puts "wow!"
  end
end

module C
  include A   # instance methods
  extend B    # class methods
end

class D
  include C
end

D.new.foo
D.wow

Upvotes: 1

Views: 947

Answers (1)

Maurício Linhares
Maurício Linhares

Reputation: 40323

You'll have to define C like this to be able to do what you want:

module C
  include A

  def self.included( base )
    base.extend B #"base" here is "D"
  end

end

Upvotes: 6

Related Questions