class ActiveModel::Serializer
end
end
post.author == options[:scope]
def author?
end
hash
hash.merge!(:email => post.email) if author?
hash = super
def attributes
private
has_many :comments
attributes :title, :body
class PostSerializer < ActiveModel::Serializer
author of the post:
For example, some attributes maybe only be returned if current_user
is the
We use the scope to check if a given attribute should be serialized or not.
in for authorization purposes.
The object to be serialized is the +@post+ and the current user is passed
PostSerializer.new(@post, :scope => current_user).to_json
one may do in a controller:
it expects to object as arguments, a resource and options. For example,
control how a given object is going to be serialized. On initialization,
Provides a basic serializer implementation that allows you to easily
Active Model Serializer
def as_json(options=nil)
Returns a json representation of the serializable
def as_json(options=nil) options ||= {} if root = options.fetch(:root, @options.fetch(:root, _root)) @options[:hash] = hash = {} @options[:unique_values] = {} hash.merge!(root => serializable_hash) hash else serializable_hash end end
def associate(klass, attrs) #:nodoc:
def associate(klass, attrs) #:nodoc: options = attrs.extract_options! self._associations = _associations.dup attrs.each do |attr| unless method_defined?(attr) class_eval "def #{attr}() object.#{attr} end", __FILE__, __LINE__ end self._associations[attr] = klass.refine(attr, options) end end
def attribute(attr, options={})
def attribute(attr, options={}) self._attributes = _attributes.merge(attr => options[:key] || attr) unless method_defined?(attr) class_eval "def #{attr}() object.read_attribute_for_serialization(:#{attr}) end", __FILE__, __LINE__ end end
def attributes(*attrs)
def attributes(*attrs) self._attributes = _attributes.dup attrs.each do |attr| attribute attr end end
def attributes
Returns a hash representation of the serializable
def attributes hash = {} _attributes.each do |name,key| hash[key] = read_attribute_for_serialization(name) end hash end
def embed(type, options={})
embed :ids, :include => true # Embed the association ids and include objects in the root
embed :ids # Embed only the association ids
embed :objects # Embed associations as full objects
Define how associations should be embedded.
def embed(type, options={}) self._embed = type self._root_embed = true if options[:include] end
def has_many(*attrs)
with the association name does not exist, the association name is
as a method which should return an array when invoked. If a method
The serializer object should implement the association name
Defines an association in the object should be rendered.
def has_many(*attrs) associate(Associations::HasMany, attrs) end
def has_one(*attrs)
with the association name does not exist, the association name is
as a method which should return an object when invoked. If a method
The serializer object should implement the association name
Defines an association in the object should be rendered.
def has_one(*attrs) associate(Associations::HasOne, attrs) end
def include!(name, options={})
def include!(name, options={}) # Make sure that if a special options[:hash] was passed in, we generate # a new unique values hash and don't clobber the original. If the hash # passed in is the same as the current options hash, use the current # unique values. # # TODO: Should passing in a Hash even be public API here? unique_values = if hash = options[:hash] if @options[:hash] == hash @options[:unique_values] ||= {} else {} end else hash = @options[:hash] @options[:unique_values] ||= {} end node = options[:node] value = options[:value] association_class = if klass = _associations[name] klass elsif value.respond_to?(:to_ary) Associations::HasMany else Associations::HasOne end association = association_class.new(name, self, options) if association.embed_ids? node[association.key] = association.serialize_ids if association.embed_in_root? merge_association hash, association.root, association.serialize_many, unique_values end elsif association.embed_objects? node[association.key] = association.serialize end end
def include_associations!(node)
def include_associations!(node) _associations.each do |attr, klass| opts = { :node => node } if options.include?(:include) || options.include?(:exclude) opts[:include] = included_association?(attr) end include! attr, opts end end
def included_association?(name)
def included_association?(name) if options.key?(:include) options[:include].include?(name) elsif options.key?(:exclude) !options[:exclude].include?(name) else true end end
def inherited(klass) #:nodoc:
def inherited(klass) #:nodoc: return if klass.anonymous? name = klass.name.demodulize.underscore.sub(/_serializer$/, '') klass.class_eval do alias_method name.to_sym, :object root name.to_sym unless self._root == false end end
def initialize(object, options={})
def initialize(object, options={}) @object, @options = object, options end
def instrument(name, payload = {}, &block)
Use ActiveSupport::Notifications to send events to external systems.
def instrument(name, payload = {}, &block) ActiveSupport::Notifications.instrument("#{name}.serializer", payload, &block) end
def merge_association(hash, key, value, unique_values)
avoids the need to scan through the Array looking for entries every time
a unique list of all of the objects that are already in the Array. This
In order to make this efficient, we store a :unique_values hash containing
of all tags for all comments of the post.
which has_many tags, the top-level :tags key will contain the merged list
content for all of the children. For instance, if a Post has_many comments,
In some cases, an Array of associations is built by merging the associated
def merge_association(hash, key, value, unique_values) if current_value = unique_values[key] current_value.merge! value hash[key] = current_value.to_a elsif value hash[key] = value unique_values[key] = OrderedSet.new(value) end end
def model_class
def model_class name.sub(/Serializer$/, '').constantize end
def root(name)
def root(name) self._root = name end
def schema
TODO: This is currently coupled to Active Record. We need to
to work.
methods on your custom models if you want the serializer's schema method
methods, provided by default by ActiveRecord. You can implement these
The schema method uses the +columns_hash+ and +reflect_on_association+
which is provided by +SerializerClass.model_class+.
This information is extracted from the serializer's model class,
{ :my_posts => { :has_many => :posts }
the hash looks like this:
end
has_many :posts, :key => :my_posts
class PostsSerializer < ActiveModel::Serializer
If :key is used:
{ :posts => { :has_many => :posts } }
The +associations+ hash looks like this:
{ :name => :string, :age => :integer }
The +attributes+ hash looks like this:
The schema hash has two keys: +attributes+ and +associations+.
can be used to generate clients for the serialized output.
Return a schema hash for the current serializer. This information
def schema klass = model_class columns = klass.columns_hash attrs = _attributes.inject({}) do |hash, (name,key)| column = columns[name.to_s] hash.merge key => column.type end associations = _associations.inject({}) do |hash, (attr,association_class)| association = association_class.new(attr, self) model_association = klass.reflect_on_association(association.name) hash.merge association.key => { model_association.macro => model_association.name } end { :attributes => attrs, :associations => associations } end
def serializable_hash
Returns a hash representation of the serializable
def serializable_hash instrument(:serialize, :serializer => self.class.name) do node = attributes instrument :associations do include_associations!(node) if _embed end node end end
def url_options
def url_options @options[:url_options] end