Created
September 1, 2009 14:13
-
-
Save capitalist/179110 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
if defined?(ActiveResource) | |
# Makes activeresource properly encode records | |
class ActiveResource::Base | |
cattr_accessor :include_root_in_json, :instance_writer => false | |
def encode(options={}) | |
case self.class.format | |
when ActiveResource::Formats::XmlFormat | |
self.class.format.encode(attributes, {:root => self.class.element_name}.merge(options)) | |
when ActiveResource::Formats::JsonFormat | |
if ActiveResource::Base.include_root_in_json | |
self.class.format.encode({self.class.element_name => attributes}, options) | |
else | |
self.class.format.encode(attributes, options) | |
end | |
else | |
self.class.format.encode(attributes, options) | |
end | |
end | |
end | |
ActiveResource::Base.include_root_in_json = true | |
ActiveResource::Base.format = :json | |
class ActiveResource::Errors | |
def from_array(messages) | |
clear | |
humanized_attributes = @base.attributes.keys.inject({}) { |h, attr_name| h.update(attr_name.humanize => attr_name) } | |
messages.each do |message| | |
attr_message = humanized_attributes.keys.detect do |attr_name| | |
if message[0, attr_name.size + 1] == "#{attr_name} " | |
add humanized_attributes[attr_name], message[(attr_name.size + 1)..-1] | |
end | |
end | |
add_to_base message if attr_message.nil? | |
end | |
end | |
# Grabs errors from the json response. | |
def from_json(json) | |
array = ActiveSupport::JSON.decode(json)['errors'] rescue [] | |
from_array array | |
end | |
# Grabs errors from the XML response. | |
def from_xml(xml) | |
array = Array.wrap(Hash.from_xml(xml)['errors']['error']) rescue [] | |
from_array array | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment