Module: MongoidNestedFields::NestedFieldSetter::ClassMethods
- Defined in:
- lib/mongoid_nested_fields/nested_field_setter.rb
Instance Method Summary collapse
- #_allowed_types_in_field(field) ⇒ Object
- #_is_allowed_type?(field, type) ⇒ Boolean
- #_set_allowed_types_in_field(field, type) ⇒ Object
- #_set_serialization ⇒ Object
- #_set_validations ⇒ Object
- #nested_field(name, options = {}) ⇒ Object
Instance Method Details
#_allowed_types_in_field(field) ⇒ Object
54 55 56 57 58 |
# File 'lib/mongoid_nested_fields/nested_field_setter.rb', line 54 def _allowed_types_in_field(field) field = field.to_sym @_allowed_types_in_field ||= {} return @_allowed_types_in_field[field] || [] end |
#_is_allowed_type?(field, type) ⇒ Boolean
59 60 61 62 |
# File 'lib/mongoid_nested_fields/nested_field_setter.rb', line 59 def _is_allowed_type?(field, type) field = field.to_sym _allowed_types_in_field(field).include?(type) end |
#_set_allowed_types_in_field(field, type) ⇒ Object
46 47 48 49 50 51 52 53 |
# File 'lib/mongoid_nested_fields/nested_field_setter.rb', line 46 def _set_allowed_types_in_field(field, type) field = field.to_sym @_allowed_types_in_field ||= {} @_allowed_types_in_field[field] ||= [] @_allowed_types_in_field[field] << type @_allowed_types_in_field[field].flatten! @_allowed_types_in_field[field].uniq! unless @_allowed_types_in_field[field].nil? end |
#_set_serialization ⇒ Object
37 38 39 40 |
# File 'lib/mongoid_nested_fields/nested_field_setter.rb', line 37 def _set_serialization before_save :_serialize_nested_fields after_save :_restore_nested_fields end |
#_set_validations ⇒ Object
42 43 44 |
# File 'lib/mongoid_nested_fields/nested_field_setter.rb', line 42 def _set_validations validate :_nested_fields_must_be_valid end |
#nested_field(name, options = {}) ⇒ Object
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 |
# File 'lib/mongoid_nested_fields/nested_field_setter.rb', line 6 def nested_field(name, = {}) @_nested_fields ||= [] @_nested_fields << name.to_s [:type] = MongoidNestedFields::NestedFieldHolder _set_allowed_types_in_field(name, .delete(:allowed_types)) _set_validations _set_serialization field(name, ) meth = .delete(:as) || name define_method("#{meth}=") do |value| raise TypeError unless [String, Array, NilClass].include?(value.class) if value.is_a? String parser = Yajl::Parser.new value = parser.parse(value) end processed_values = [] value.to_a.each do |v| v.stringify_keys! if v.is_a? Hash if((v.is_a?(Hash) or v.is_a?(BSON::OrderedHash)) and !v['_type'].nil?) v = v['_type'].classify.constantize.new(v.to_hash) end raise MongoidNestedFields::Errors::UnexpectedType.new(v.class, name) unless self.class._is_allowed_type?(name, v.class) processed_values << v end write_attribute(name, processed_values) end end |