Sha256: 298a91bd0690dba35c4c90bdfa47b8b26174eb76963fd3d27793ab0d571149f3

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

=begin :rdoc:

= DynamicMixin

== Example

module Mixin
  extend DynamicMixin
  def self.default_options
    { :name => "Buffalo" }
  end
  def hello
    puts "Hello from #{dynamic_options[:name]}!"
  end
end

class T
  include Mixin[ :name => "Test" ]
end
t = T.new
t.hello

class S
  include Mixin[ :name => "Sister" ]
end
s = S.new
s.hello

module Mixin2
  extend DynamicMixin
  include Mixin[ :name => "Flo"]
end

class R
  include Mixin2[ :name => "Bruce"]
end
r = R.new
r.hello

=end

module DynamicMixin

  def self.extended( mod )
    mod.class_eval do
      define_method(:dynamic_options) {
        mod.respond_to?(:default_options) ? mod.default_options : {}
      } 
    end
  end

  def [](options = {})
    @cache ||= {} # Not really needed, but not much work either

    defaults = self.respond_to?( :default_options ) ? self.default_options : {}
    options = defaults.merge(options)

    mod = self.name
    opt_str = options.map { |pair| pair.join(" => ") }.join(", ")
    name = "#{self.name}[#{opt_str}]"

    @cache[options] ||= self.dup
    @cache[options].class_eval {
      meta = class << self; self; end
      meta.send(:define_method, :name) { name }
      define_method(:dynamic_options) { options }
    }
    return @cache[options]
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
carats-0.3.0 lib/carat/dynamic-mixin.rb