Sha256: b9ed5c566814223150ca315607a6bf376f751fb993ef3287c3b4a9fd30a8cfad

Contents?: true

Size: 1.33 KB

Versions: 2

Compression:

Stored size: 1.33 KB

Contents

module Makers
  class Proxy
    include Callbacks

    def initialize(maker, &block)
      @maker = maker
      @attributes = []
      @sequences = {}
      instance_eval &block
    end

    def attributes
      {}.tap do |hash|
        if @maker.parent
          hash.merge! @maker.parent.proxy.attributes
        end
        @attributes.each do |name|
          hash[name] = send(name)
        end
      end
    end

    def sequence(name, &block)
      @attributes << name
      @sequences[name] = Sequence.new(&block)
      class_eval do
        define_method(name) { @sequences[name] }
      end
    end

    def method_missing(name, *args, &block)
      unless name == :maker
        options = args.extract_options!
        strategy = options.delete(:strategy) || :build
        if block_given?
          logic = block
        elsif maker = Makers.definitions.find(name) rescue nil
          logic = -> { maker.send(strategy, options) }
        elsif maker = Makers.definitions.find(name.to_s.singularize.to_sym) rescue nil
          logic = -> { maker.send(strategy, (args.first || 1), options) }
        elsif args.any?
          logic = -> { args.first }
        end
        if defined? logic
          @attributes.send (block_given? ? :push : :unshift), name
          class_eval { define_method(name, logic) }
        end
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
makers-0.1.3 lib/makers/proxy.rb
makers-0.1.2 lib/makers/proxy.rb