Class: DataMapper::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/dm-serializer/to_hal.rb

Instance Method Summary collapse

Instance Method Details

#to_hal(*args) ⇒ HypertextApplicationLanguage::Representation

Converts a collection to HAL. Represents a collection by constructing a set of embedded representations associated with a relation. The name of the relation is the table name of the collection’s underlying model. The collection representation includes other useful pieces of information: the offset, limit and chunk size, useful for paging.

Sends each to the collection to access the individual resources. Converts each one to HAL then embeds the results within the resulting collection representation. The resulting collection representation both embeds the resources and includes links to the same resources.

Only adds a link to self if the arguments include a Rack environment and the rack environment specifies the request path. This assumes that the request path is either an absolute path because it begins with a slash, or a relative path because higher-level Rack formatters will make the reference absolute by adding the base URL and script name.

Returns:

  • (HypertextApplicationLanguage::Representation)

    Representation of a collection of resources.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/dm-serializer/to_hal.rb', line 69

def to_hal(*args)
  keyword_args = args.last.is_a?(Hash) ? args.pop : {}
  representation = HypertextApplicationLanguage::Representation.new

  if (env = keyword_args[:env]) && (href = env['REQUEST_PATH'])
    representation.with_link(HypertextApplicationLanguage::Link::SELF_REL, href)
  end

  rel = model.to_s.tableize

  each do |resource|
    resource_representation = resource.to_hal(*args)
    representation.with_link(rel, resource_representation.link.href)
    representation.with_representation(rel, resource_representation)
  end

  %w(size).each do |name|
    representation.with_property(name, __send__(name))
  end
  %w(offset limit).each do |name|
    representation.with_property(name, query.__send__(name))
  end
  %w(count).each do |name|
    representation.with_property(name, model.__send__(name, conditions: query.conditions))
  end

  representation
end