module MongoidNestedFields::NestedField
Public Class Methods
included(base)
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 104 def self.included(base) base.extend(ClassMethods) base.send(:include, ActiveModel::Validations) end
new(attrs)
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 116 def initialize(attrs) attrs.each_pair do |k,v| if v.is_a?(Hash) && !v['_type'].nil? v = v['_type'].classify.constantize.new(v) end self.send("#{k}=", v) end end
Public Instance Methods
[](key)
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 138 def [](key) read_attribute(key) end
_nested_fields()
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 160 def _nested_fields self.class.instance_variable_get(:@_nested_fields) end
_type()
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 112 def _type self.class.to_s.underscore end
_type=(t)
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 109 def _type=(t) end
attributes()
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 142 def attributes @_attributes end
nested_fields_must_be_valid()
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 164 def nested_fields_must_be_valid _nested_fields.each do |field| value = read_attribute(field) i = 0 field_errors = {} value.each do |v| if v.respond_to?(:invalid?) and v.invalid? field_errors[i.to_s] = v.errors i += 1 end end if value.respond_to? :each errors.add(field, field_errors) unless field_errors.empty? end unless _nested_fields.nil? end
read_attribute(name)
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 131 def read_attribute(name) @_attributes ||= {} fields = self.class.instance_variable_get(:@_fields) raise "Field #{name} doesn't exist in #{self.class}" if fields.nil? or !fields.include?(name.to_sym) @_attributes[name.to_sym] end
to_mongo()
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 146 def to_mongo attrs = MongoidNestedFields::NestedFieldHash.new attributes.each_key do |key| if self.send(key.to_sym).is_a?(Array) attrs[key.to_s] = self.send(key.to_sym).map{ |v| v.respond_to?(:to_mongo) ? v.to_mongo : v } else attrs[key.to_s] = self.send(key.to_sym) end end attrs['_type'] = _type attrs.origin = self attrs end
write_attribute(name, value)
click to toggle source
# File lib/mongoid_nested_fields/nested_field_part.rb, line 125 def write_attribute(name, value) @_attributes ||= {} @_attributes[name.to_sym] = value end