lib/pupa/models/model.rb in pupa-0.0.10 vs lib/pupa/models/model.rb in pupa-0.0.11

- old
+ new

@@ -26,12 +26,19 @@ self.properties = Set.new self.foreign_keys = Set.new self.foreign_objects = Set.new + # @return [String] The object's unique identifier. attr_reader :_id - attr_accessor :_type, :extras + # @return [Hash] The object's non-schema properties. + attr_reader :extras + # @return [String] The underscored, lowercase form of the object's class. + attr_accessor :_type + # @return [Moped::BSON::Document,nil] The object's matching document in + # the database. Set before persisting the object to the database. + attr_accessor :document dump :_id, :_type, :extras end module ClassMethods @@ -122,10 +129,17 @@ # @param [String,Moped::BSON::ObjectId] id an ID def _id=(id) @_id = id.to_s # in case of Moped::BSON::ObjectId end + # Sets the extras. + # + # @param [Array] extras a list of extras + def extras=(extras) + @extras = symbolize_keys(extras) + end + # Adds a key-value pair to the object. # # @param [Symbol] key a key # @param value a value def add_extra(key, value) @@ -157,12 +171,12 @@ end end # Returns the object as a hash. # - # @param [Boolean] persist whether the object is being persisted, validated - # or used as a MongoDB selecto, in which case foreign objects (i.e. hints) + # @param [Boolean] persist whether the object is being persisted, validated, + # or used as a MongoDB selector, in which case foreign objects (i.e. hints) # are excluded # @return [Hash] the object as a hash def to_h(persist: false) {}.tap do |hash| (persist ? properties - foreign_objects : properties).each do |property| @@ -187,23 +201,31 @@ a == b end private - def stringify_keys(object) + def transform_keys(object, meth) case object when Hash {}.tap do |hash| object.each do |key,value| - hash[key.to_s] = stringify_keys(value) + hash[key.send(meth)] = transform_keys(value, meth) end end when Array object.map do |value| - stringify_keys(value) + transform_keys(value, meth) end else object end + end + + def symbolize_keys(object) + transform_keys(object, :to_sym) + end + + def stringify_keys(object) + transform_keys(object, :to_s) end end end