Module: CouchRest::Mixins::Properties
- Defined in:
- lib/couchrest/mixins/properties.rb
Defined Under Namespace
Modules: ClassMethods
Classes: IncludeError
Class Method Summary
collapse
Instance Method Summary
collapse
Class Method Details
.included(base) ⇒ Object
29
30
31
32
33
34
35
36
|
# File 'lib/couchrest/mixins/properties.rb', line 29
def self.included(base)
base.class_eval <<-EOS, __FILE__, __LINE__
extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
self.properties ||= []
EOS
base.extend(ClassMethods)
raise CouchRest::Mixins::Properties::IncludeError, "You can only mixin Properties in a class responding to [] and []=, if you tried to mixin CastedModel, make sure your class inherits from Hash or responds to the proper methods" unless (base.new.respond_to?(:[]) && base.new.respond_to?(:[]=))
end
|
Instance Method Details
#apply_defaults ⇒ Object
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
# File 'lib/couchrest/mixins/properties.rb', line 38
def apply_defaults
return if self.respond_to?(:new_document?) && (new_document? == false)
return unless self.class.respond_to?(:properties)
return if self.class.properties.empty?
self.class.properties.each do |property|
key = property.name.to_s
unless property.default.nil?
if property.default.class == Proc
self[key] = property.default.call
else
self[key] = Marshal.load(Marshal.dump(property.default))
end
end
end
end
|
#cast_float(value) ⇒ Object
93
94
95
96
97
98
99
|
# File 'lib/couchrest/mixins/properties.rb', line 93
def cast_float(value)
begin
Float(value)
rescue
value
end
end
|
#cast_keys ⇒ Object
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
# File 'lib/couchrest/mixins/properties.rb', line 56
def cast_keys
return unless self.class.properties
self.class.properties.each do |property|
next unless property.casted
key = self.has_key?(property.name) ? property.name : property.name.to_sym
next unless self[key]
target = property.type
if target.is_a?(Array)
klass = ::CouchRest.constantize(target[0])
self[property.name] = self[key].collect do |value|
obj = ( (property.init_method == 'new') && klass == Time) ? Time.parse(value) : klass.send(property.init_method, value)
obj.casted_by = self if obj.respond_to?(:casted_by)
obj
end
else
self[property.name] = if ((property.init_method == 'new') && target == 'Time')
self[key].is_a?(String) ? Time.mktime_with_offset(self[key].dup) : self[key]
elsif ((property.init_method == 'new') && target == 'Float')
cast_float(self[key])
elsif ((property.init_method == 'new') && target == 'boolean')
self[key]
else
klass = ::CouchRest.constantize(target)
klass.send(property.init_method, self[key].dup)
end
self[property.name].casted_by = self if self[property.name].respond_to?(:casted_by)
end
end
def cast_float(value)
begin
Float(value)
rescue
value
end
end
end
|