Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Sep 20 ’10

Making a module testable with ‘extend self’

It’s great to pull out common functionality into a module, so you can use it in several classes. But it can be a little awkward to test the module, because you can’t call its methods directly.
Well, unless you can: use extend self to make the module’s instance methods available as class methods. Now you can call the methods of the module directly without having an instance of a class that includes this module.

module ShoutMachine
  extend self

  def shout(text)
    "#{text.upcase}!"
  end
end

class BigMachine
  include ShoutMachine
end

>> ShoutMachine.shout('booyeah')   # => BOOYEAH!
>> BigMachine.new.shout('booyeah') # => BOOYEAH!

This tip was submitted by Nick Stielau.

10 notes 0 comments

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus