Sha256: 210e0c602078921f20bdd7fdac77301671723a6b34fad7dc9768002021088dfe

Contents?: true

Size: 870 Bytes

Versions: 9

Compression:

Stored size: 870 Bytes

Contents

# Add a formatter to grape that converts all snake case hash keys from ruby to camel case.
require 'camel_snake_keys'
require 'grape/formatter/json'
module IntrospectiveGrape
  module Formatter
    module CamelJson
      class << self
        def transform_to_camel_keys(object)
          # We only need to parse(object.to_json) like this if it isn't already
          # a native hash (or array of them), i.e. we have to parse Grape::Entities
          # and other formatter facades:
          unless (object.is_a?(Array) && object.first.is_a?(Hash)) || object.is_a?(Hash)
            object = JSON.parse(object.to_json) if object.respond_to?(:to_json)
          end
          CamelSnakeKeys.camel_keys(object)
        end

        def call(object, env)
          Grape::Formatter::Json.call(transform_to_camel_keys(object), env)
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
introspective_grape-0.4.3 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.4.2 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.4.1 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.4.0 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.3.9 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.3.7 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.3.6 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.3.5 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.3.3 lib/introspective_grape/formatter/camel_json.rb