Module: DataMapper::Serialize
- Defined in:
- lib/restfulx/datamapper_foo.rb
Overview
Monkey patches dm-serialization to_json method to add ruby_class: YourClass to all serialized objects
Instance Method Summary collapse
-
#to_json(*args) ⇒ String
Serialize a Resource to JavaScript Object Notation (JSON; RFC 4627).
Instance Method Details
#to_json(*args) ⇒ String
Serialize a Resource to JavaScript Object Notation (JSON; RFC 4627)
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 48 49 |
# File 'lib/restfulx/datamapper_foo.rb', line 16 def to_json(*args) = args.first || {} result = '{ ' fields = [] propset = properties_to_serialize() fields += propset.map do |property| "#{property.name.to_json}: #{send(property.getter).to_json}" end fields << "\"ruby_class\": #{self.class.to_json}" # add methods ([: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 ([: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 |