Class: DataMapper::Collection

Inherits:
Object
  • Object
show all
Includes:
Serializer::Collection::ToYaml
Defined in:
lib/dm-serializer/to_yaml.rb,
lib/dm-serializer/to_csv.rb,
lib/dm-serializer/to_xml.rb,
lib/dm-serializer/to_json.rb

Overview

module Serializer

Instance Method Summary collapse

Methods included from Serializer::Collection::ToYaml

#encode_with, #to_yaml

Instance Method Details

#to_csv(*args) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/dm-serializer/to_csv.rb', line 55

def to_csv(*args)
  result = ''
  each do |item|
    result << item.to_csv(args.first) + "\n"
  end
  result
end

#to_json(*args) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/dm-serializer/to_json.rb', line 80

def to_json(*args)
  options = args.first
  options = {} unless options.kind_of?(Hash)

  resource_options = options.merge(:to_json => false)
  collection = map { |resource| resource.to_json(resource_options) }

  # default to making JSON
  if options.fetch(:to_json, true)
    MultiJson.encode(collection)
  else
    collection
  end
end

#to_xml(opts = {}) ⇒ Object



93
94
95
# File 'lib/dm-serializer/to_xml.rb', line 93

def to_xml(opts = {})
  to_xml_document(opts).to_s
end

#to_xml_document(opts = {}) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/dm-serializer/to_xml.rb', line 97

def to_xml_document(opts = {})
  xml = DataMapper::Serializer::XML.serializer
  doc = xml.new_document

  default_collection_element_name = lambda {
    DataMapper::Inflector.pluralize(DataMapper::Inflector.underscore(self.model.to_s)).tr("/", "-")
  }

  root = xml.root_node(
    doc,
    opts[:collection_element_name] || default_collection_element_name[],
    {'type' => 'array'}
  )

  self.each do |item|
    item.to_xml_document(opts, doc)
  end

  doc
end