Class: Makers::Dsl::Maker

Inherits:
Object
  • Object
show all
Defined in:
lib/makers/dsl/maker.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}, &block) ⇒ Maker

Returns a new instance of Maker.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/makers/dsl/maker.rb', line 5

def initialize(name, options={}, &block)
  class_name = options[:class_name] ||= name.to_s.classify
  @model = class_name.constantize
  @name = name
  @assignments = {}
  @associations = {}
  @sequences = {}
  @options = options
  if block_given?
    instance_eval &block
  end
  Array(options[:traits]).each do |id|
    block = Makers.traits.find(id)
    instance_eval &block
  end
  Makers.definitions.add(
    [name] + Array(options[:aliases]),
    @name,
    @model,
    @assignments,
    @associations,
    @sequences,
    @options
  )
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



80
81
82
83
84
85
86
87
88
# File 'lib/makers/dsl/maker.rb', line 80

def method_missing(name, *args, &block)
  if @model.reflections.has_key?(name.to_s)
    association name, *args
  elsif block_given?
    @assignments[name] = block
  elsif args.size > 0
    @assignments[name] = -> { args.first }
  end
end

Instance Method Details

#association(name, *args) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/makers/dsl/maker.rb', line 55

def association(name, *args)
  options = args.extract_options!
  lookup = (options[:maker] || name)
  action = (options[:strategy] || :build)
  reflection = @model.reflections[name.to_s]
  class_name = @model.name
  case reflection.macro
  when :belongs_to,:has_one
    @assignments[name] = -> {
      maker = Makers.definitions.find(lookup).dup
      maker.disabled_association = class_name
      maker.send action
    }
  when :has_many
    @assignments[name] = -> {
      maker = Makers.definitions.find(lookup.to_s.singularize.to_sym).dup
      maker.disabled_association = class_name
      (args.first || 1).times.map do
        maker.send action
      end
    }
  end
  @associations[name] = reflection.class_name
end

#maker(name, overrides = {}, &block) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/makers/dsl/maker.rb', line 31

def maker(name, overrides={}, &block)
  options = @options.dup
  options.delete :aliases
  options.delete :traits
  options.merge! overrides
  options.merge! parent: @name
  Dsl::Maker.new name, options, &block
end

#sequence(name, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/makers/dsl/maker.rb', line 40

def sequence(name, &block)
  index = 0
  if block_given?
    @assignments[name] = -> {
      index += 1
      instance_exec index, &block
    }
  else
    @assignments[name] = -> {
      index += 1
    }
  end
  @sequences[name] = index
end