Posts Tagged ‘static singleton class methods include extend module mixin ruby rails’

A Ruby Module that mixes in Class Methods (static) and Instance Methods

Thursday, February 4th, 2010

Ho ho, this one can catch you out more than once so it’s high time to write a blog post to cover this off. Turns out it’s a commonly used pattern to the rescue. Thanks to eoin on #ruby.ie for pointing to the solution on RailsTips.org.

Here’s quite a tasty diagram too for easy reference.

module Swingable

    def self.included(base)
        base.extend(ClassMethods)
    end

    def instance_swing
        puts 'Did an instance swing!'
    end

    module ClassMethods
        def static_swing
            puts 'Did a static swing!'
        end
    end
end

class BaseballBat
   include Swingable
end

BaseballBat.static_swing
BaseballBat.new.instance_swing