Sha256: 3fdaf0a7deb69f7d211bdc657ba34ad4353e12ea65a76d4e4348cf39681533a7

Contents?: true

Size: 1.04 KB

Versions: 13

Compression:

Stored size: 1.04 KB

Contents

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

        private

        def serializable?(object)
          object.respond_to?(:serializable_hash) || object.is_a?(Array) && object.all? { |o| o.respond_to? :serializable_hash } || object.is_a?(Hash)
        end

        def serialize(object)
          if object.respond_to? :serializable_hash
            object.serializable_hash
          elsif object.is_a?(Array) && object.all? { |o| o.respond_to? :serializable_hash }
            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

13 entries across 13 versions & 2 rubygems

Version Path
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/grape-1.2.5/lib/grape/formatter/serializable_hash.rb
grape-extra_validators-1.0.0 vendor/bundle/ruby/2.4.0/gems/grape-1.2.5/lib/grape/formatter/serializable_hash.rb
grape-1.2.5 lib/grape/formatter/serializable_hash.rb
grape-1.2.4 lib/grape/formatter/serializable_hash.rb
grape-1.2.3 lib/grape/formatter/serializable_hash.rb
grape-1.2.2 lib/grape/formatter/serializable_hash.rb
grape-1.2.1 lib/grape/formatter/serializable_hash.rb
grape-1.2.0 lib/grape/formatter/serializable_hash.rb
grape-1.1.0 lib/grape/formatter/serializable_hash.rb
grape-1.0.3 lib/grape/formatter/serializable_hash.rb
grape-1.0.2 lib/grape/formatter/serializable_hash.rb
grape-1.0.1 lib/grape/formatter/serializable_hash.rb
grape-1.0.0 lib/grape/formatter/serializable_hash.rb