Sha256: fbde86fa99a4ec903b995e15840529e664c99390a2d0a680c4ae82f2a4a358a0

Contents?: true

Size: 1.02 KB

Versions: 12

Compression:

Stored size: 1.02 KB

Contents

require 'active_support/core_ext/object/json'

module ActiveModel
  # Enable classes to Classes including this module to serialize themselves by implementing a serialize method and an options method.
  #
  # Example:
  #
  #     require 'active_model_serializers'
  #
  #     class MySerializer
  #       include ActiveModel::Serializable
  #
  #       def initialize
  #         @options = {}
  #       end
  #
  #       attr_reader :options
  #
  #       def serialize
  #         { a: 1 }
  #       end
  #     end
  #
  #     puts MySerializer.new.to_json
  module Serializable
    def as_json(args={})
      if root = args[:root] || options[:root]
        options[:hash] = hash = {}
        options[:unique_values] = {}

        hash.merge!(root => serialize)
        include_meta hash
        hash
      else
        serialize
      end
    end

    private

    def include_meta(hash)
      hash[meta_key] = options[:meta] if options.has_key?(:meta)
    end

    def meta_key
      options[:meta_key].try(:to_sym) || :meta
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
gpi-active_model_serializers-0.8.5 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.5.alpha1 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.4 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.4.alpha5 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.4.alpha4 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.4.alpha3 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.4.alpha2 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.4.alpha1 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.3.rc1 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.3.alpha2 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.3.alpha1 lib/active_model/serializable.rb
gpi-active_model_serializers-0.8.2 lib/active_model/serializable.rb