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
|
# File 'lib/schema/schema.rb', line 17
def attribute_macro(attr_name, type=nil, strict: nil, default: nil)
if type.nil? && !strict.nil?
raise Schema::Attribute::Error, "The \"#{attr_name}\" attribute is declared with the \"strict\" option but a type is not specified"
end
if type == Boolean && strict == false
raise Schema::Attribute::Error, "The \"#{attr_name}\" attribute is declared with the \"strict\" option disabled but boolean type is specified"
end
check = nil
if type == Boolean
strict ||= true
check = proc do |val|
unless val.nil? || Boolean.(val)
raise Schema::Attribute::TypeError, "#{val.inspect} is not a boolean"
end
end
elsif !type.nil?
strict ||= false
check = proc do |val|
unless val.nil?
if strict
raise Schema::Attribute::TypeError, "#{val.inspect} is not an instance of #{type.name}" unless val.instance_of? type
else
raise Schema::Attribute::TypeError, "#{val.inspect} is not a kind of #{type.name}" unless val.is_a? type
end
end
end
end
initialize_value = nil
if default.is_a? Proc
initialize_value = default
elsif !default.nil?
initialize_value = proc { default }
end
::Attribute::Define.(self, attr_name, :accessor, check: check, &initialize_value)
attribute = attributes.register(attr_name, type, strict)
attribute
end
|