Skip to content

Instantly share code, notes, and snippets.

@brundage
Created June 18, 2012 22:35
Show Gist options
  • Save brundage/2951192 to your computer and use it in GitHub Desktop.
Save brundage/2951192 to your computer and use it in GitHub Desktop.
Replaces ActiveModel::Serializers with ActiveModel::Serializer
module JsonSerializationUnifier
# ActiveModel::Serializer only works in the controller's render method
# This modue replaces ActiveModel::Serializers with ActiveModel::Serializer
# yup, a little confusing. Include in in your model classes so to_json and
# as_json work as expected in the console and elsewhere.
extend ActiveSupport::Concern
def as_json(value=nil, use_options = true)
return active_model_serializer.as_json if active_model_serializer
super
end
def to_json(options=nil)
return active_model_serializer.to_json if active_model_serializer
super
end
private
def active_model_serializer_class
self.class.respond_to?(:active_model_serializer) && self.class.active_model_serializer
end
def active_model_serializer
@_serializer ||= active_model_serializer_class.new(self)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment