Description

Fson is a fluent builder for simple JSON API responses

Build Status Dependency Status Code Climate Test Coverage

Installation

Add this line to your application's Gemfile:

gem 'fson'

for Rails projects also

rails g fson:install

Usage

Create response builder

Fson::Response.new()                # {}

with given status

Fson::Response.new('failure')       # {"status": "failure"}

or use one of predefined factory methods

Fson::Response.success              # {"status": "success"}
Fson::Response.error                # {"status": "error"}
Fson::Response.fail                 # {"status": "fail"}

then add some data by passing hash

.data({:id => 12})                  
{
    "data": {
          "id": 12
     }
}

or defining block

.data { |data|
    data[:id] = 12
}                                   
{
    "data": {
        "id": 12
    }
}

optionally add errors

.add_error('not authorized') { |e| 
    e[:code] = 401
}.add_error('null pointer exception')
{ 
    "errors": [
        {
            "message": "not authorized",
            "code": 401
        },
        {
            "message": "null pointer exception"
        }
    ]
}

and finally get JSON with

.as_json

Example

Builder chain

Fson::Response.fail.data {|data| data[:id] = 12}.add_error('not authorized').as_json

will return

{
    "status": "fail", 
    "data": {
        "id": 12
    },
    "errors": [
        {
            "message": "not authorized"
        }
    ]
}

More builder methods

.success()          # sets status to :success
.error()            # sets status to :error
.fail()             # sets status to :fail

.status('failure')  # sets status

Custom builders

You can add custom builder methods operating on response hash objects

@_response      # top level response hash
@_data          # data hash
@_errors        # errors hash

For example you can add builder

module MyCustomBuilder

    def attribute(value)
        @_data[:attribute] = value
        self
    end
end

by registering it in initializer

require 'fson/loader'

::Fson::Loader::configure([MyCustomBuilder])

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request