Class: SampleModels::Creation::SpecifiedAttributes

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sampler, *args) ⇒ SpecifiedAttributes

Returns a new instance of SpecifiedAttributes.



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/sample_models/creation.rb', line 112

def initialize(sampler, *args)
  @sampler = sampler
  @result = if args.first.is_a?(Symbol)
    sample_name = args.shift
    @sampler.named_samples[sample_name].clone
  else
    {}
  end
  @result.merge!(args.pop) if args.last.is_a?(Hash)
  args.each do |associated_value|
    assign_associated_record_from_args(associated_value)
  end
  model.belongs_to_associations.each do |assoc|
    build_belongs_to_record_from_shortcut_args(assoc)
  end
  model.has_many_associations.each do |assoc|
    build_has_many_record_from_shortcut_args(assoc)
  end
  @result = HashWithIndifferentAccess.new(@result)
end

Instance Attribute Details

#resultObject (readonly)

Returns the value of attribute result.



110
111
112
# File 'lib/sample_models/creation.rb', line 110

def result
  @result
end

Instance Method Details

#assign_associated_record_from_args(associated_value) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/sample_models/creation.rb', line 133

def assign_associated_record_from_args(associated_value)
  assocs = model.associations.select { |a|
    begin
      a.klass == associated_value.class
    rescue NameError
      false
    end
  }
  if assocs.size == 1
    @result[assocs.first.name] = associated_value
  else
    raise "Not sure what to do with associated value #{associated_value.inspect}"
  end
end

#build_belongs_to_record_from_shortcut_args(assoc) ⇒ Object



148
149
150
151
152
153
154
155
156
# File 'lib/sample_models/creation.rb', line 148

def build_belongs_to_record_from_shortcut_args(assoc)
  if value = @result[assoc.name]
    if value.is_a?(Hash)
      @result[assoc.name] = assoc.klass.sample(value)
    elsif value.is_a?(Array)
      @result[assoc.name] = assoc.klass.sample(*value)
    end
  end
end

#build_has_many_record_from_shortcut_args(assoc) ⇒ Object



158
159
160
161
162
163
164
# File 'lib/sample_models/creation.rb', line 158

def build_has_many_record_from_shortcut_args(assoc)
  if values = @result[assoc.name]
    @result[assoc.name] = values.map { |value|
      value.is_a?(Hash) ? assoc.klass.sample(value) : value
    }
  end
end

#modelObject



166
167
168
# File 'lib/sample_models/creation.rb', line 166

def model
  @sampler.model
end