Skip to content

Commit

Permalink
Does not force every response to be an array
Browse files Browse the repository at this point in the history
  • Loading branch information
inf0rmer committed Apr 21, 2015
1 parent ba7c72a commit 1bf06d9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,25 @@ github.users.get('inf0rmer')
```

### Responses
At the moment Blanket only accepts JSON responses. Every request returns an array of `Blanket::Response`.
At the moment Blanket only accepts JSON responses. Every request returns a `Blanket::Response` instance, which parses the JSON internally and lets you access keys using dot syntax:

```ruby
user = github.users('inf0rmer').get

user.login
# => "inf0rmer"

user.url
# => "https://api.github.com/users/inf0rmer"

# It even works on nested keys
repo = github.repos('inf0rmer').get('blanket')

repo.owner.login
# => "inf0rmer"
```

If the response is an array, all `Enumerable` methods work as expected:

```ruby
repos = github.users('inf0rmer').repos.get
Expand Down
6 changes: 5 additions & 1 deletion lib/blanket/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ def method_missing(method, *args, &block)
end

def payload_from_json(json)
[json].flatten.map { |item| RecursiveOpenStruct.new item, recurse_over_arrays: true }
parsed = [json].flatten.map do |item|
RecursiveOpenStruct.new item, recurse_over_arrays: true
end

(parsed.count == 1) ? parsed.first : parsed
end

end
Expand Down
6 changes: 3 additions & 3 deletions spec/blanket/response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@
end

it "can access a surface property from a json string as a method" do
expect(response.first.title).to eq("Something")
expect(response.title).to eq("Something")
end

it "can access a deep property from a json string as a method" do
expect(response.first.desc.someKey).to eq("someValue")
expect(response.desc.someKey).to eq("someValue")
end

it "can access a deep property in an array from a json string as a method" do
expect(response.first.main_item.values[0].quantity).to eq(1)
expect(response.main_item.values[0].quantity).to eq(1)
end
end

Expand Down

0 comments on commit 1bf06d9

Please sign in to comment.