/
factory.rb
45 lines (39 loc) · 1003 Bytes
/
factory.rb
1
2
3
4
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module Factory
# Build actions for the class
def self.build(klass, &block)
name = klass.to_s.underscore
define_method("#{name}_attributes", block)
module_eval <<-end_eval
def valid_#{name}_attributes(attributes = {})
#{name}_attributes(attributes)
attributes
end
def new_#{name}(attributes = {})
#{klass}.new(valid_#{name}_attributes(attributes))
end
def create_#{name}(*args)
record = new_#{name}(*args)
record.save!
record.reload
record
end
end_eval
end
build Car do |attributes|
attributes.reverse_merge!(
:name => 'Porsche'
)
end
build Preference do |attributes|
attributes[:owner] = create_user unless attributes.include?(:owner)
attributes.reverse_merge!(
:attribute => 'notifications',
:value => false
)
end
build User do |attributes|
attributes.reverse_merge!(
:login => 'admin'
)
end
end