Sha256: f24680373f59873fa3db3fe6ab261e09f7bfb64330c966b5ef26c91468f21559

Contents?: true

Size: 1.06 KB

Versions: 3

Compression:

Stored size: 1.06 KB

Contents

module Grape
  module Formatter
    module SerializableHash
      class << self
        def call(object, env)
          return object if object.is_a?(String)
          return MultiJson.dump(serialize(object)) if serializable?(object)
          return object.to_json if object.respond_to?(:to_json)
          MultiJson.dump(object)
        end

        private

        def serializable?(object)
          object.respond_to?(:serializable_hash) || object.kind_of?(Array) && !object.map { |o| o.respond_to? :serializable_hash }.include?(false) || object.kind_of?(Hash)
        end

        def serialize(object)
          if object.respond_to? :serializable_hash
            object.serializable_hash
          elsif object.kind_of?(Array) && !object.map { |o| o.respond_to? :serializable_hash }.include?(false)
            object.map(&:serializable_hash)
          elsif object.kind_of?(Hash)
            object.inject({}) do |h, (k, v)|
              h[k] = serialize(v)
              h
            end
          else
            object
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
grape-0.11.0 lib/grape/formatter/serializable_hash.rb
grape-0.10.1 lib/grape/formatter/serializable_hash.rb
grape-0.10.0 lib/grape/formatter/serializable_hash.rb