To explore the meta programming abilities of ruby programming language, I worked upon building an internal DSL for making http requests. To further understand the concept of internal DSL refer to https://martinfowler.com/bliki/InternalDslStyle.html.

I call this package Mock and it provides basic functionalities for working with HTTP requests. Currently supports get, post & delete verbs and can be easily extended to all the other verbs as well. Allows for setting cookies, headers, query & params and allow processing json responses with ease.

All the properties set in a single mock instance can be reused throughout the block or can be modified for individual requests as well. Custom logic can be easily embedded in the actions and response can be dealt with as well

Usage

Following methods are provided to set the http attributes

  • set_query
  • set_param - performs parameter substitution
  • set_cookies
  • set_body
  • set_headers
  • response
  • json - parses the response into json if header set for json

Block can be built out of http verbs

Mock.http do
   # these configs will be shared across all the http actions
   set_cookies 'id_token', 'XXXXXX'
   set_headers 'Host', 'build-failed-successfully.com'
   set_headers 'Content-Type', 'application/json'

   # configs specified in a specific action will only be limited
   # to that action
   get "http://localhost:4000/api/{version}/user/top" do
      set_query :limit, 10
      set_query :order, :asc
      set_params :version, :v2

      json
   end

   post "http://localhost:4000/api/{version}/refresh_streak_data" do
      set_params :version, :v2
      set_body {:data => 100, :message => :ok}

      response
   end

   delete "http://localhost:4000/api/{version}/users/{user_id}" do
      get_user_id = -> { some logic to get user id}

      set_params :user_id, get_user_id.call
      set_params :version, :v1

      response
   end
end