lib/locomotive/steam/models/mapper.rb in locomotivecms_steam-1.0.0.pre.alpha.3 vs lib/locomotive/steam/models/mapper.rb in locomotivecms_steam-1.0.0.pre.beta.1

- old
+ new

@@ -46,26 +46,44 @@ @associations << [type, name.to_sym, repository_klass, options || {}, block] end def to_entity(attributes) entity_klass.new(deserialize(attributes)).tap do |entity| - attach_entity_to_associations(entity) - set_default_attributes(entity) entity.localized_attributes = @localized_attributes_hash || {} + entity.associations = {} + attach_entity_to_associations(entity) + entity.base_url = @repository.base_url(entity) end end def deserialize(attributes) build_localized_attributes(attributes) build_associations(attributes) attributes end + def serialize(entity) + entity.serialize.tap do |attributes| + # scope + @repository.scope.apply(attributes) + + # localized fields + @localized_attributes.each do |name| + entity.send(name).serialize(attributes) + end + + # association name -> id (belongs_to) or ids (many_to_many) + (entity.associations || {}).each do |name, association| + association.__serialize__(attributes) + end + end + end + def entity_klass options[:entity] end def i18n_value_of(entity, name, locale) @@ -86,14 +104,11 @@ # create a proxy class for each association def build_associations(attributes) @associations.each do |(type, name, repository_klass, options, block)| klass = ASSOCIATION_CLASSES[type] - _options = options.merge({ - association_name: name, - mapper_name: self.name - }) + _options = options.merge(association_name: name, mapper_name: self.name) attributes[name] = (if type == :embedded klass.new(repository_klass, attributes[name], @repository.scope, _options) else klass.new(repository_klass, @repository.scope, @repository.adapter, _options, &block) @@ -101,10 +116,13 @@ end end def attach_entity_to_associations(entity) @associations.each do |(type, name, _)| - entity[name].__attach__(entity) + association = entity[name] + association.__attach__(entity) + + entity.associations[name] = association end end def set_default_attributes(entity) @default_attributes.each do |(name, value)|