-
Notifications
You must be signed in to change notification settings - Fork 2
Parsers
Kacper Walanus edited this page Feb 27, 2015
·
11 revisions
Callapi provides following parsers:
Callapi::Call::Parser::Json
Callapi::Call::Parser::Json::AsObject
Callapi::Call::Parser::Plain
Default is Callapi::Call::Parser::Json
.
##### Callapi::Call::Parser::Json `Callapi::Call::Parser::Json` converts JSON to `Hash`. If the API response for `/notes/12` is
{ "id": 2, "title": "Pick-up posters from post-office" }
then #data
method will return Hash
(or Array of Hashes):
get_notes_by_id_call(id: 12).data['id'] #=> 2
##### Callapi::Call::Parser::Json::AsObject `Callapi::Call::Parser::Json::AsObject` converts JSON to an object called `DeepStruct` (very similar to [`OpenStruct`](http://www.ruby-doc.org/stdlib-2.0/libdoc/ostruct/rdoc/OpenStruct.html)): ```ruby get_notes_by_id_call(id: 12).data.title #=> "Pick-up posters from post-office" ```
##### Callapi::Call::Parser::Plain `Callapi::Call::Parser::Plain` does not parse at all: ```ruby get_notes_by_id_call(id: 12).data #=> '{ "id": 2, "title": "Pick-up posters from post-office" }' ```
### Setting parsers Default parser for all calls can be set in configuration: ```ruby Callapi::Config.configure do |config| config.default_response_parser = Callapi::Call::Parser::Json::AsObject end ```
Default parser for specific calls can be set in routes:
Callapi::Routes.draw do
get :users, parser: Callapi::Call::Parser::Json::AsObject
get :version, parser: Callapi::Call::Parser::Plain
end
Parser can be also set for each call instance separately:
get_notes_call.
with_response_parser(Callapi::Call::Parser::Json::AsObject).data #=> [#<DeepStruct id=1, title="Jogging in park">]
get_notes_call.
with_response_parser(Callapi::Call::Parser::Plain).data #=> "[{\n \"id\": 1, \"title\": \"Jogging in park\"\n}]"
Or set and changed for the same instance as many time as you want:
call = get_notes_call
call.
with_response_parser(Callapi::Call::Parser::Json::AsObject).data #=> [#<DeepStruct id=1, title="Jogging in park">]
call.reload # DO NOT FORGET TO CLEAR CACHE!
call.
with_response_parser(Callapi::Call::Parser::Plain).data #=> "[{\n \"id\": 1, \"title\": \"Jogging in park\"\n}]"