Module: DataMapper::Serializer

Defined in:
lib/dm-serializer/to_hal.rb

Instance Method Summary collapse

Instance Method Details

#to_hal(*args) ⇒ Object

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.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 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