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 explicitly

.data_array([{:id => 12}])                  
{
    "data": [{
          "id": 12
     }]
}
.data_hash({:id => 12})
{
    "data": {
          "id": 12
     }
}

or by defining block

.data_array { |data|
    data << {:id => 12}
}                                   
{
    "data": [{
        "id": 12
    }]
}
.data_hash { |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_array {|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 using builder private methods

_response                   # returns response hash
_errors                     # returns errors hash
_data                       # returns data hash
_initialized_data_array     # returns existing data array or initializes it with empty array
_initialized_data_hash      # returns existing data hash or initializes it with empty hash

For example you can add builder

module MyCustomBuilder

    def attribute(value)
        _initialized_data_array << {
            :attribute => 'value'
        }
        self
    end
end

by registering it in initializer

require 'fson/loader'

ActionDispatch::Callbacks.to_prepare do
  ::Fson::Loader::configure([MyCustomBuilder])
end

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