Can I use active_model_serializers with Sinatra? If not, is there any better way for json output in Sinatra for building a web service?
-
1of course you can, its pure ruby, not tied to Rails – apneadiving Nov 07 '14 at 09:01
-
Awesome. I'm still not sure if I made a right choice using Sinatra for web service (I'm writing backend of my application as a service), but we'll see. – Bhushan Lodha Nov 07 '14 at 09:02
-
1well why not, if you start having 50+ end points, might be more difficult to organize in sinatra but... why not – apneadiving Nov 07 '14 at 09:11
-
@apneadiving - I think Sinatra is the way to go. I created an API with 60 endpoints. It is easy to organize. – B Seven Nov 08 '14 at 14:46
-
@BSeven well you know Rails provides much security for free, taste and colours :) – apneadiving Nov 08 '14 at 15:25
3 Answers
Yes, you can. However, the design and architecture of AMS is strongly focuses on ActiveModel instances, therefore if you don't use an ActiveModel-based library (such as Mongoid, ActiveRecord, etc) the choice may be overkill.
Still, the approach reflects the common Presenter pattern applied to JSON serialization. You can easily create your own simple library to extract the attributes you define from an object you pass.
Sinatra also provides some JSON serialization extensions. What they do by default, is to call as_json
. That's not the best approach, it is not extremely flexible, but you can combine those two elements to create your own solution, or start from scratch.

- 173,507
- 49
- 363
- 364
You can, includes a json.rb inside the lib folder with the following piece of code and do require this file on your application.rb .
# lib/json.rb
module Sinatra
module JSON
def json(object, options={})
serializer = ActiveModel::Serializer.serializer_for(object, options)
if serializer
serializer.new(object, options).to_json
else
object.to_json(options)
end
end
end
end
To use just do
get '/foo' do
json Foo.find(params[:id])
end
get '/bar' do
json Bar.find(params[:id]), { scope: self }
end

- 524
- 5
- 6
-
I did this gem to help: https://rubygems.org/gems/sinatra-active-model-serializers – Saulo Santiago Feb 10 '15 at 17:55
I used to_json
to return JSON output from Sinatra API's. It turns out that there are dozens of JSON gems for Ruby, of varying efficiency.
One approach is to create list of attributes for each object that you want to render to JSON. For example, if your User has an image that you don't want to render, you could create a blacklist for the User class:
JSON_BLACKLIST = [ 'image' ]
Then, when you render the JSON, you can call:
user.attributes.reject{|a| JSON_BLACKLIST.include?( a )}.to_json

- 44,484
- 66
- 240
- 385