February 09, 2010 20:35
Posted by Jeremy Durham
ActiveResource + Rails 2.3.5 + JSON
If you’ve ever worked with ActiveResource then you know how much of an unfinished product it feels like. I’ve recently been interfacing with some RESTful web services, and also building some internal web services.
I chose JSON because of my need to send serialized arrays to another Rails app as well as the obvious performance over using REXML; I was surprised to find that Rails 2.3.5 broke ActiveResource, and I couldn’t readily find a patch to fix the issue.
Here’s a simple “extension” I wrote today that seems to work:
module ActiveResource
class Base
def encode(options={})
case self.class.format
when ActiveResource::Formats[:xml]
self.class.format.encode(attributes, {:root => self.class.element_name}.merge(options))
elseself.class.format.encode({ self.class.element_name => attributes })
end end endmodule Formats
module JsonFormat
def decode(json)
data = ActiveSupport::JSON.decode(json)
if data.is_a?(Hash)
data
else data.flatten.inject([]) do |total, item|total << item.values.first
end end end end endendJust drop this in a file (I called mine active_resource_extension.rb) and require it via require ‘active_resource_extension’. Hope that helps someone!









0 Comments
Leave a comment