Skip to content

Instantly share code, notes, and snippets.

@capitalist
Created September 1, 2009 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save capitalist/179110 to your computer and use it in GitHub Desktop.
Save capitalist/179110 to your computer and use it in GitHub Desktop.
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