Sha256: 970b21990cb1c005cf2259d43c3ca2be46ac9498f603dffb392f2ad6152c773b

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

module MetaBuilder

  def self.extended(klass)
    name = klass.name.gsub(/builder$/i, "")
    raise "The extending class must have 'Builder' on the class name" unless klass.name.downcase.include? "builder"
    Thread.current["#{name.downcase}_builder_defaults"] = Hash.new
    Thread.current["#{name.downcase}_builder_override"] = Hash.new
    klass.instance_variable_set("@_builder_name", name)
    Kernel.const_set name, Class
  end

  def builder_defaults(*defaults)
    raise "bulder_defaults expects pair arguments example: builder_defaults key, value, key, value ..." unless defaults.size % 2 == 0
    defaults.each_slice(2) do |pie|
      builder_default pie[0], pie[1]
    end
  end

  def builder_default(key, val)
    klazz = class << self; self; end
    name = @_builder_name.downcase
    klazz.send(:define_method, "with_#{key}".to_sym) do |overridden_val|
      Thread.current["#{name}_builder_defaults"][key.to_sym] = val
      Thread.current["#{name}_builder_override"][key.to_sym] = overridden_val
      return self
    end
  end

  def build
    name  = @_builder_name.downcase
    klazz = Kernel.const_get @_builder_name
    #klazz.instance_eval do
      defaults = Thread.current["#{name}_builder_defaults"]
      override = Thread.current["#{name}_builder_override"]
      properties = defaults.merge override
      properties.each do |key, value|
        klazz.send(:define_method, key.to_sym) do
          value
        end
      end
    #end
  end


end

class FooBuilder
  extend MetaBuilder
  builder_defaults :foo, 'bar', :bar, 'drank'
end


other_instance = FooBuilder.build
instance = FooBuilder.with_foo('zoo').with_bar('d').build

puts other_instance.instance_methods.grep /foo/

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dbuilder-0.5.0 meta_builder.rb