Sha256: 811061dc56f312dbd53548a7ac3815a5532bc3e09a77b3a45cd0ec0af08cb31e

Contents?: true

Size: 1.06 KB

Versions: 6

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.is_a?(Array) && !object.map { |o| o.respond_to? :serializable_hash }.include?(false) || object.is_a?(Hash)
        end

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

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
grape-0.18.0 lib/grape/formatter/serializable_hash.rb
grape-0.17.0 lib/grape/formatter/serializable_hash.rb
grape-0.16.2 lib/grape/formatter/serializable_hash.rb
grape-0.16.1 lib/grape/formatter/serializable_hash.rb
grape-0.15.0 lib/grape/formatter/serializable_hash.rb
grape-0.14.0 lib/grape/formatter/serializable_hash.rb