module DataMapper::Serializer

Public Instance Methods

to_hal(*args) click to toggle source

Converts a Data Mapper resource to a hypertext application language (HAL) representation.

The resulting representation contains links for each relationship. There are two main kinds of Data Mapper relationships: to-one and to-many. For to-many relationships, the links contain a reference to a sub-path for accessing or creating sub-resources based on the name of the relationship. If the relationship is to-one, then the link depends on whether or not the to-one association exists. If it does already exist, then the link references a root-level hypertext path to the resource by its relationship name and its unique identifier; assuming that path relationship/identifier resolves to the existing resources representation.

# File lib/dm-serializer/to_hal.rb, line 19
def to_hal(*args)
  representation = HypertextApplicationLanguage::Representation.new

  rel = model.to_s.tableize
  representation.with_link(HypertextApplicationLanguage::Link::SELF_REL, "#{rel}/#{id}")

  model.relationships.each do |relationship|
    association = __send__(relationship.name)
    href = if association == nil || association.is_a?(DataMapper::Collection)
             "#{representation.link.href}/#{relationship.name}"
           else
             "#{association.model.to_s.tableize}/#{association.id}"
           end
    representation.with_link(relationship.name, href)
  end

  exclude = model.properties(repository.name).map(&:name).select do |name|
    name.to_s.end_with?('_id')
  end + %i(id)

  properties_to_serialize(exclude: exclude).map(&:name).each do |name|
    value = __send__(name)
    representation.with_property(name, value)
  end

  representation
end