Module: DynamicMixin

Defined in:
lib/carat/dynamic-mixin.rb

Overview

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(mod) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/carat/dynamic-mixin.rb', line 44

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

Instance Method Details

#[](options = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/carat/dynamic-mixin.rb', line 52

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