Sha256: 2f96f367cd01e887e8de9c5ea5593d4739cecc4e8cf2a799e4d157a4cdbdf99f

Contents?: true

Size: 1.13 KB

Versions: 20

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

require "awrence"
require "multi_json"
require "sinatra/base"

module Sinatra
  module JSON
    class << self
      def encode(object)
        ::MultiJson.dump(object)
      end
    end

    def json(object, options = {})
      object = object.to_camelback_keys

      content_type resolve_content_type(options)
      resolve_encoder_action object, resolve_encoder(options)
    end

    private

    def resolve_content_type(options = {})
      options[:content_type] || settings.json_content_type
    end

    def resolve_encoder(options = {})
      options[:json_encoder] || settings.json_encoder
    end

    def resolve_encoder_action(object, encoder)
      [:encode, :generate].each do |method|
        return encoder.send(method, object) if encoder.respond_to? method
      end

      if encoder.is_a? Symbol
        object.__send__(encoder)
      else
        fail "#{encoder} does not respond to #generate nor #encode"
      end
    end
  end

  Base.set :json_encoder do
    ::MultiJson
  end

  Base.set :json_content_type, :json

  # Load the JSON helpers in modular style automatically
  Base.helpers JSON
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
mihari-3.9.0 lib/mihari/web/helpers/json.rb
mihari-3.8.1 lib/mihari/web/helpers/json.rb
mihari-3.8.0 lib/mihari/web/helpers/json.rb
mihari-3.7.2 lib/mihari/web/helpers/json.rb
mihari-3.7.1 lib/mihari/web/helpers/json.rb
mihari-3.7.0 lib/mihari/web/helpers/json.rb
mihari-3.6.1 lib/mihari/web/helpers/json.rb
mihari-3.6.0 lib/mihari/web/helpers/json.rb
mihari-3.5.0 lib/mihari/web/helpers/json.rb
mihari-3.4.1 lib/mihari/web/helpers/json.rb
mihari-3.4.0 lib/mihari/web/helpers/json.rb
mihari-3.3.0 lib/mihari/web/helpers/json.rb
mihari-3.2.0 lib/mihari/web/helpers/json.rb
mihari-3.1.0 lib/mihari/web/helpers/json.rb
mihari-3.0.1 lib/mihari/web/helpers/json.rb
mihari-3.0.0 lib/mihari/web/helpers/json.rb
mihari-2.4.0 lib/mihari/web/helpers/json.rb
mihari-2.3.1 lib/mihari/web/helpers/json.rb
mihari-2.3.0 lib/mihari/web/helpers/json.rb
mihari-2.2.1 lib/mihari/web/helpers/json.rb