Last active
December 10, 2019 17:18
-
-
Save tedgrubb/5707295 to your computer and use it in GitHub Desktop.
ActiveResource: Access to data and meta objects in JSON response.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"data": [ | |
{"id": 7, "name": "Boston"}, | |
{"id": 3, "name": "Chicago"}, | |
{"id": 1, "name": "San Francisco"} | |
], | |
"meta": { | |
"errors": [], | |
"message": "", | |
"next": null, | |
"prev": null, | |
"status": 200 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"data": { | |
"id": 1, | |
"name": "San Francisco" | |
}, | |
"meta": { | |
"errors": [], | |
"message": "", | |
"status": 200 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class YourBaseResource < ActiveResource::Base | |
attr_accessor :errors, :meta | |
self.site = 'localhost:3000' | |
self.format = :json | |
self.collection_parser = YourCollectionParser | |
def initialize(attributes = {}, persisted = false) | |
# YourCollectionParser assigns these values to the collection | |
# Here we add access to meta and errors on single resource | |
if attributes.has_key?('meta') | |
@meta = attributes['meta'] | |
@errors = attributes['meta']['errors'] | |
attributes = attributes['data'] | |
end | |
@attributes = {}.with_indifferent_access | |
@prefix_options = {} | |
@persisted = persisted | |
load(attributes, false, persisted) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class YourCollectionParser << ActiveResource::Collection | |
attr_accessor :errors, :meta | |
def initialize(parsed = {}) | |
@elements = parsed['data'] | |
@meta = parsed['meta'] | |
@errors = parsed['meta']['errors'] | |
end | |
end |
marktran
commented
Jun 4, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment