module DataMapper::Serialize

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

Public Instance Methods

to_json(*args) click to toggle source

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

@return <String> a JSON representation of the Resource

# 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