Module: DataMapper::Serialize

Defined in:
lib/restfulx/rx_datamapper.rb

Overview

Monkey patches dm-serialization to_json method to add ruby_class: YourClass to all serialized objects

Instance Method Summary collapse

Instance Method Details

#to_json(*args) ⇒ String

Serialize a Resource to JavaScript Object Notation (JSON; RFC 4627)



14
15
16
17
18
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
46
47
# File 'lib/restfulx/rx_datamapper.rb', line 14

def to_json(*args)
  options = args.first || {}
  result = '{ '
  fields = []

  propset = properties_to_serialize(options)

  fields += propset.map do |property|
    "#{property.name.to_json}: #{send(property.getter).to_json}"
  end
  
  fields << "\"ruby_class\": #{self.class.to_json}"

  # add methods
  (options[:methods] || []).each do |meth|
    if self.respond_to?(meth)
      fields << "#{meth.to_json}: #{send(meth).to_json}"
    end
  end

  # Note: if you want to include a whole other model via relation, use :methods
  # comments.to_json(:relationships=>{:user=>{:include=>[:first_name],:methods=>[:age]}})
  # add relationships
  # TODO: This needs tests and also needs to be ported to #to_xml and #to_yaml
  (options[:relationships] || {}).each do |rel,opts|
    if self.respond_to?(rel)
      fields << "#{rel.to_json}: #{send(rel).to_json(opts)}"
    end
  end

  result << fields.join(', ')
  result << ' }'
  result
end