Sunday, August 12, 2012

Customizing JSON services in Rails

In my previous sample I got this result from a JSON service:
[
{"created_at":"2012-08-12T13:56:42Z","id":1,"time":"2012-08-12T13:30:00Z","title":"Test Event \u21161","updated_at":"2012-08-12T13:57:40Z"},
{"created_at":"2012-08-12T13:57:07Z","id":2,"time":"2012-08-17T16:00:00Z","title":"Test Event \u21162","updated_at":"2012-08-12T13:57:07Z"},
{"created_at":"2012-08-12T13:57:29Z","id":3,"time":"2012-08-20T10:00:00Z","title":"Test Event \u21161","updated_at":"2012-08-12T13:57:29Z"}]

But what if I want to customize the result? Here is when function overriding comes handy.
Override as_json function in data model Event, like this:

class Event < ActiveRecord::Base
  attr_accessible :time, :title
 def as_json(options = {})
  result = {id: self.id, EventName: self.title, WillTakePlace: self.time }
 end
end

Viola! This is customised JSON data (as you see, I chose only three attributes and renamed two of them):

[
{"id":1,"EventName":"Test Event \u21161","WillTakePlace":"2012-08-12T13:30:00Z"},
{"id":2,"EventName":"Test Event \u21162","WillTakePlace":"2012-08-17T16:00:00Z"},
{"id":3,"EventName":"Test Event \u21161","WillTakePlace":"2012-08-20T10:00:00Z"}]

and what if I need something more complicated? Probably, I would call to RABL

No comments:

Post a Comment