Skip to content

Instantly share code, notes, and snippets.

@tedgrubb
Last active December 10, 2019 17:18
Show Gist options
  • Save tedgrubb/5707295 to your computer and use it in GitHub Desktop.
Save tedgrubb/5707295 to your computer and use it in GitHub Desktop.
ActiveResource: Access to data and meta objects in JSON response.
{
"data": [
{"id": 7, "name": "Boston"},
{"id": 3, "name": "Chicago"},
{"id": 1, "name": "San Francisco"}
],
"meta": {
"errors": [],
"message": "",
"next": null,
"prev": null,
"status": 200
}
}
{
"data": {
"id": 1,
"name": "San Francisco"
},
"meta": {
"errors": [],
"message": "",
"status": 200
}
}
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
class YourCollectionParser << ActiveResource::Collection
attr_accessor :errors, :meta
def initialize(parsed = {})
@elements = parsed['data']
@meta = parsed['meta']
@errors = parsed['meta']['errors']
end
end
@marktran
Copy link

marktran commented Jun 4, 2013

Bandit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment