Sha256: 67ce12172d7be96800e2f1253f18b96874945f0a9782ed3f2543f690ef4ca3e9

Contents?: true

Size: 896 Bytes

Versions: 4

Compression:

Stored size: 896 Bytes

Contents

module Yaks
  # State monad-ish thing.
  #
  # Generate a DSL syntax for immutable classes.
  #
  # @example
  #
  #   # This code
  #   Form.create(:search)
  #       .method("POST")
  #       .action("/search")
  #
  #   # Can be written as
  #   Builder.new(Form, [:method, :action]).create(:search) do
  #     method "POST"
  #     action "/search"
  #   end
  #
  class Builder
    include Configurable

    def initialize(klass, methods = [], &block)
      @klass = klass
      @methods = methods
      def_forward(*methods) if methods.any?
      instance_eval(&block) if block
    end

    def create(*args, &block)
      build(@klass.create(*args), &block)
    end

    def build(init_state, *extra_args, &block)
      @config = init_state
      instance_exec(*extra_args, &block) if block
      @config
    end

    def inspect
      "#<Builder #{@klass} #{@methods}>"
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
yaks-0.13.0 lib/yaks/builder.rb
yaks-0.12.0 lib/yaks/builder.rb
yaks-0.11.0 lib/yaks/builder.rb
yaks-0.10.0 lib/yaks/builder.rb