Skip to content

Instantly share code, notes, and snippets.

@jphenow
Created January 8, 2014 16:25
Show Gist options
  • Save jphenow/8319574 to your computer and use it in GitHub Desktop.
Save jphenow/8319574 to your computer and use it in GitHub Desktop.
ActiveModel Serializers with custom root bits
require File.expand_path("../config/environment", __FILE__)
require 'rspec'
# Disable for all serializers (except ArraySerializer)
ActiveModel::Serializer.root = false
#
# # Disable for ArraySerializer
ActiveModel::ArraySerializer.root = false
class AMSEnvelope
attr_accessor :metadata, :errors, :result
def initialize(meta, err, res)
self.metadata = meta
self.errors = err
self.result = serializer(res).new(res).as_json
end
def read_attribute_for_serialization(attr)
send(attr)
end
def serializer(obj)
"#{obj.class.name}Serializer".safe_constantize ||
ActiveModel::DefaultSerializer
end
end
class AMSEnvelopeSerializer < ActiveModel::Serializer
attributes :metadata, :errors, :result
end
class GroupSerializer < ActiveModel::Serializer
attributes :name
end
describe "AMS with envelope" do
let(:envelope) { AMSEnvelope.new({ current_user: {} }, [], Group.new(name: "test")) }
subject { AMSEnvelopeSerializer.new(envelope) }
it "renders all the things" do
subject.as_json.should == { metadata: { current_user: {} }, errors: [], result: { name: "test" } }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment