servant-ruby-0.2.0.0: Generate a Ruby client from a Servant API with Net::HTTP.

Copyright(c) Hardy Jones 2017
LicenseBSD3
Maintainerjones3.hardy@gmail.com
StabilityExperimental
Safe HaskellNone
LanguageHaskell2010

Servant.Ruby

Description

 

Synopsis

Documentation

data NameSpace Source #

The namespace for the generated class.

Constructors

NameSpace 

Fields

  • moduleNames :: [Text]

    The list of namespaces you'd like the class to appear in.

  • className :: Text

    The name of the class you'd like the API methods to appear in.

ruby :: (GenerateList NoContent (Foreign NoContent api), HasForeign NoTypes NoContent api) => NameSpace -> Proxy api -> Text Source #

Generate a Ruby class with methods for the Servant API.

Currently assumes the API accepts and returns JSON.

For example:

>>> Data.Text.IO.putStr $ ruby (NameSpace [] "Baz") (Proxy :: Proxy (Get '[JSON] ()))
require "json"
require "net/http"
require "uri"

class Baz
  def initialize(origin)
    @origin = URI(origin)
    @http = Net::HTTP.new(@origin.host, @origin.port)
  end

  def get()
    uri = URI("#{@origin}")

    req = Net::HTTP::Get.new(uri)

    @http.request(req)
  end
end

The class can be nested in a module namespace if you choose so.

>>> Data.Text.IO.putStr $ ruby (NameSpace ["Foo", "Bar"] "Baz") (Proxy :: Proxy (Get '[JSON] ()))
require "json"
require "net/http"
require "uri"

module Foo
  module Bar
    class Baz
      def initialize(origin)
        @origin = URI(origin)
        @http = Net::HTTP.new(@origin.host, @origin.port)
      end

      def get()
        uri = URI("#{@origin}")

        req = Net::HTTP::Get.new(uri)

        @http.request(req)
      end
    end
  end
end

Captures and query parameters are translated into required arguments, in that order.

The request body and headers are translated into keyword arguments, in that order.

>>> let api = Proxy :: Proxy ("foo" :> Capture "fooId" Int :> ReqBody '[JSON] () :> QueryParam "bar" Bool :> Header "Max-Forwards" Int :> Post '[JSON] ())
>>> Data.Text.IO.putStr $ ruby (NameSpace [] "Foo") api
require "json"
require "net/http"
require "uri"

class Foo
  def initialize(origin)
    @origin = URI(origin)
    @http = Net::HTTP.new(@origin.host, @origin.port)
  end

  def post_foo_by_foo_id(foo_id, bar, body:, max_forwards:)
    uri = URI("#{@origin}/foo/#{fooId}?bar=#{bar}")

    req = Net::HTTP::Post.new(uri)
    req["Content-Type"] = "application/json"
    req["Max-Forwards"] = max_forwards

    @http.request(req, body)
  end
end