/
attribute_list.rb
78 lines (63 loc) · 2 KB
/
attribute_list.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
module FactoryGirl
class AttributeList
include Enumerable
def initialize
@attributes = {}
end
def define_attribute(attribute)
if attribute_defined?(attribute.name)
raise AttributeDefinitionError, "Attribute already defined: #{attribute.name}"
end
add_attribute attribute
end
def add_callback(name, &block)
unless valid_callback_names.include?(name.to_sym)
raise InvalidCallbackNameError, "#{name} is not a valid callback name. Valid callback names are #{valid_callback_names.inspect}"
end
add_attribute Attribute::Callback.new(name.to_sym, block)
end
def each(&block)
flattened_attributes.each(&block)
end
def attribute_defined?(attribute_name)
!@attributes.values.flatten.detect do |attribute|
attribute.name == attribute_name &&
!attribute.is_a?(FactoryGirl::Attribute::Callback)
end.nil?
end
def apply_attributes(attributes_to_apply)
new_attributes = []
attributes_to_apply.each do |attribute|
if attribute_defined?(attribute.name)
@attributes[attribute.priority].delete_if do |attrib|
new_attributes << attrib.clone if attrib.name == attribute.name
end
else
new_attributes << attribute.clone
end
end
prepend_attributes new_attributes
end
private
def valid_callback_names
[:after_build, :after_create, :after_stub]
end
def add_attribute(attribute)
@attributes[attribute.priority] ||= []
@attributes[attribute.priority] << attribute
attribute
end
def prepend_attributes(new_attributes)
new_attributes.group_by {|attr| attr.priority }.each do |priority, attributes|
@attributes[priority] ||= []
@attributes[priority].unshift *attributes
end
end
def flattened_attributes
@attributes.keys.sort.inject([]) do |result, key|
result << @attributes[key]
result
end.flatten
end
end
end