Sha256: f2179204ae0f290b4d992343e35e7a7ab411590b18210be7bb3e677abaac194c

Contents?: true

Size: 1000 Bytes

Versions: 4

Compression:

Stored size: 1000 Bytes

Contents

require "json"

class Tynn
  # Public: Adds helper methods for json generation.
  #
  # Examples
  #
  #   require "tynn"
  #   require "tynn/json"
  #
  #   Tynn.plugin(Tynn::JSON)
  #
  module JSON
    CONTENT_TYPE = "application/json".freeze

    module InstanceMethods
      # Public: Calls +to_json+ on +data+ and writes the generated \JSON
      # object into the response body. Also, It automatically sets the
      # +Content-Type+ header to +application/json+.
      #
      # data - Any object that responds to +to_json+.
      #
      # Examples
      #
      #   Tynn.define do
      #     on("hash") do
      #       json(foo: "bar")
      #     end
      #
      #     on("array") do
      #       json([1, 2, 3])
      #     end
      #
      #     on("to_json") do
      #       json(Model.first)
      #     end
      #   end
      #
      def json(data)
        res.headers[Rack::CONTENT_TYPE] = Tynn::JSON::CONTENT_TYPE

        res.write(data.to_json)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
tynn-1.4.0 lib/tynn/json.rb
tynn-1.3.0 lib/tynn/json.rb
tynn-1.2.0 lib/tynn/json.rb
tynn-1.1.0 lib/tynn/json.rb