Jeremy Durham

Ruby, Rails, and everything in between.

  • BlogThoughts
  • AboutAbout the Author
  • ContactGet in touch

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))
        else
          self.class.format.encode({ self.class.element_name => attributes })
      end
    end
  end
  
  module 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
  end
end

Just drop this in a file (I called mine active_resource_extension.rb) and require it via require ‘active_resource_extension’. Hope that helps someone!

No Comments

Posted Under Programming

0 Comments

Leave a comment

* = Required
  • Posts
  • Twitter
  • Flickr
 

There is no Holy ...

Technology

 

Google and Apple:...

Technology

 

Setting up Git an...

Technology

@mariusrugan awesome, glad I was able to be of some help

follow me on
twitter

125942640_a3dcc3f951_s125942637_c4524c7c88_s125942628_a682f8a639_s122144184_5f2dd86929_s122144182_1b01ded312_s122144181_893a82f1d3_s122144179_70465b00ff_s122102402_21e6174af6_s122102401_f6d9ebff55_s

Categories

  • Technology
  • Programming
  • Family
  • Travel

This site is using the Handgloves WordPress Theme
Designed & Developed by George Wiscombe

Subscribe via RSS