Skip to content

Instantly share code, notes, and snippets.

@tkrotoff
Created October 9, 2012 13:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkrotoff/3858908 to your computer and use it in GitHub Desktop.
Save tkrotoff/3858908 to your computer and use it in GitHub Desktop.
Rails JSON serialization and deserialization
class Event < ActiveRecord::Base
include EventJSON
attr_accessible *EventJSON.attributes
validates :starts_at, presence: true
validates :ends_at, presence: true
validates :all_day, inclusion: { in: [true, false] }
end
# JSON attributes for Event model.
# See How to override default deserialisation of params to model object? http://stackoverflow.com/questions/12750125/how-to-override-default-deserialisation-of-params-to-model-object
# See Various issues and questions when using inside a Rails engine https://github.com/josevalim/active_model_serializers/issues/135
module EventJSON
# Attributes that are allowed in JSON
def self.attributes
[ :title, :start, :end, :allDay, :description, :location, :color ]
end
# JSON input allDay matches all_day
alias_attribute :allDay, :all_day
# JSON input start matches starts_at
# +time+:: UNIX time
def start=(time)
self.starts_at = Time.at(time)
end
# JSON input end matches ends_at
# +time+:: UNIX time
def end=(time)
self.ends_at = Time.at(time)
end
# Override the JSON output.
def as_json(options = nil)
{
id: id,
title: title,
start: starts_at,
end: ends_at,
allDay: all_day,
description: description,
location: location,
color: color
}
end
end
class EventsController < ApplicationController
wrap_parameters Event, include: EventJSON.attributes
respond_to :json
# GET /events
def index
respond_with Event.all
end
# GET /events/1
def show
respond_with Event.find(params[:id])
end
# POST /events
def create
respond_with Event.create(params[:event])
end
# PUT /events/1
def update
respond_with Event.update(params[:id], params[:event])
end
# DELETE /events/1
def destroy
respond_with Event.destroy(params[:id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment