Sha256: f6443e96289d719e5e933e8097e6fa9754fd8fac1f38a661376b39bc99a8e807

Contents?: true

Size: 1.04 KB

Versions: 2

Compression:

Stored size: 1.04 KB

Contents

require "json"

class JsonSerializer
  def self.attribute(name, serializer = nil)
    attributes[name] ||= serializer
  end

  def self.attributes
    @attributes ||= {}
  end

  attr :object

  def initialize(object)
    @object = object
  end

  def to_json(options={})
    if root = options[:root]
      { root => serializable_object }.to_json
    else
      serializable_object.to_json
    end
  end

  protected

  def serializable_object
    if object.kind_of?(Enumerable)
      object.to_a.map { |item| self.class.new(item).attributes }
    else
      attributes
    end
  end

  def attributes
    self.class.attributes.each_with_object({}) do |(name, serializer), hash|
      data = self.class.method_defined?(name) ? self.send(name) : object.send(name)
      data = Utils.const(self.class, serializer).new(data).serializable_object if serializer
      hash[name] = data
    end
  end

  module Utils
    def self.const(context, name)
      case name
      when Symbol, String
        context.const_get(name)
      else name
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
json-serializer-0.0.5 lib/json-serializer.rb
json-serializer-0.0.4 lib/json-serializer.rb