Sha256: f419866295d7b9cb61a3f103a00c9276b9314460de219ff2a1943debd670e70a

Contents?: true

Size: 873 Bytes

Versions: 7

Compression:

Stored size: 873 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:
          has_hash = (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) && !has_hash
          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

7 entries across 7 versions & 1 rubygems

Version Path
introspective_grape-0.6.1 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.5.7 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.5.6 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.5.5 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.5.4 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.5.2 lib/introspective_grape/formatter/camel_json.rb
introspective_grape-0.5.0 lib/introspective_grape/formatter/camel_json.rb