Module: Huberry::HattrAccessor
- Defined in:
- lib/hattr_accessor.rb
Defined Under Namespace
Modules: ActiveRecordExtensions
Classes: MissingAttributeError
Instance Method Summary
collapse
Instance Method Details
#hattr_accessor(*attrs) ⇒ Object
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
79
80
81
82
83
84
85
86
87
|
# File 'lib/hattr_accessor.rb', line 15
def hattr_accessor(*attrs)
options = attrs.last.is_a?(Hash) ? attrs.pop : {}
raise MissingAttributeError, 'Must specify the :attribute option with the name of an attribute which will store the hash' if options[:attribute].nil?
attrs.each do |name|
hattr_attributes << name
define_method name do
value = send("#{name}_before_type_cast".to_sym)
return value if options[:allow_nil] && value.nil?
case options[:type]
when :string
value.to_s
when :symbol
value.to_s.to_sym
when :integer
value.to_i
when :float
value.to_f
when :boolean
![false, nil, 0, '0', ''].include?(value)
when :decimal
BigDecimal.new(value.to_s)
when :array
Array(value)
else
value
end
end
define_method "#{name}?" do
send(name) ? true : false
end
define_method "#{name}=" do |value|
send(options[:attribute])[name] = value
end
define_method "#{name}_before_type_cast" do
send(options[:attribute]).key?(name) ? send(options[:attribute])[name] : (options[:default].respond_to?(:call) ? options[:default].call(self) : options[:default])
end
end
attr_reader options[:attribute] unless instance_methods.include?(options[:attribute].to_s)
attr_writer options[:attribute] unless instance_methods.include?("#{options[:attribute]}=")
unless instance_methods.include?("#{options[:attribute]}_with_hattr_accessor")
class_eval <<-EOF
def #{options[:attribute]}_with_hattr_accessor
self.#{options[:attribute]} = {} if #{options[:attribute]}_without_hattr_accessor.nil?
#{options[:attribute]}_without_hattr_accessor
end
alias_method :#{options[:attribute]}_without_hattr_accessor, :#{options[:attribute]}
alias_method :#{options[:attribute]}, :#{options[:attribute]}_with_hattr_accessor
EOF
end
end
|
#hattr_attributes ⇒ Object
11
12
13
|
# File 'lib/hattr_accessor.rb', line 11
def hattr_attributes
@hattr_attributes ||= []
end
|
#hattr_defined?(attribute) ⇒ Boolean
7
8
9
|
# File 'lib/hattr_accessor.rb', line 7
def hattr_defined?(attribute)
hattr_attributes.include?(attribute.to_sym)
end
|