Class: ServiceFactory::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/service_factory.rb

Defined Under Namespace

Classes: Error, UnexpectedParams

Instance Method Summary collapse

Constructor Details

#initialize(blocks) ⇒ Builder



22
23
24
25
26
# File 'lib/service_factory.rb', line 22

def initialize(blocks)
  @blocks = blocks
  @memoized_values = {}
  @memoization = false
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/service_factory.rb', line 33

def method_missing(m, *args, &block)
  prepared_block = args_to_block(args, &block)
  if @memoization
    @blocks[m] = Proc.new { @memoized_values[m] ||= prepared_block.call }
  else
    @blocks[m] = prepared_block
  end
end

Instance Method Details

#args_to_block(args, &block) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/service_factory.rb', line 42

def args_to_block(args, &block)
  if block_given?
    block
  elsif args.first.is_a?(Class)
    cl = args.first
    Proc.new { |*class_args| cl.new(*class_args) }
  else
    raise UnexpectedParams.new("expected class or block")
  end
end

#build(&block) ⇒ Object



28
29
30
31
# File 'lib/service_factory.rb', line 28

def build(&block)
  instance_eval(&block)
  @blocks
end

#env(*environments, &block) ⇒ Object



53
54
55
56
57
# File 'lib/service_factory.rb', line 53

def env(*environments, &block)
  if environments.map{|e| e.to_s}.include?(Rails.env)
    instance_eval(&block)
  end
end

#memoize(&block) ⇒ Object



59
60
61
62
63
# File 'lib/service_factory.rb', line 59

def memoize(&block)
  @memoization = true
  instance_eval(&block)
  @memoization = false
end