Class: Yaks::Builder

Inherits:
Object
  • Object
show all
Includes:
Configurable
Defined in:
lib/yaks/builder.rb

Overview

State monad-ish thing.

Generate a DSL syntax for immutable classes.

Examples:


# 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

Instance Attribute Summary

Attributes included from Configurable

#config

Instance Method Summary collapse

Methods included from Configurable

#def_add, #def_forward, #def_set, extended, #inherited

Constructor Details

#initialize(klass, methods = [], &block) ⇒ Builder

Returns a new instance of Builder.



22
23
24
25
26
27
# File 'lib/yaks/builder.rb', line 22

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

Instance Method Details

#build(init_state, *extra_args, &block) ⇒ Object



33
34
35
36
37
# File 'lib/yaks/builder.rb', line 33

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

#create(*args, &block) ⇒ Object



29
30
31
# File 'lib/yaks/builder.rb', line 29

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

#inspectObject



39
40
41
# File 'lib/yaks/builder.rb', line 39

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