Search code examples
ruby-on-railsrubyruby-on-rails-3activeresource

Complex attribute using ActiveResource in Rails 3.2.12


I'm trying to convert a webservice response into a object in my Rails application, I'm receiving the following json:

{
    "id": 1,
    "status": true,
    "password": "123",
    "userType": {
        "description": "description",
        "userTypeId": 1
    },
    "email": "[email protected]"
}

I want to convert the userType attribute in a UserType Ruby class like this:

class UserType
  attr_accessor :userTypeId, :description
end

I'm using ActiveResource to communicate with the webservice, I tried use the attribute method for convert the userType json attribute into UserType class but the attribute method doesn't accept complex types, only string, integer e etc...

How can I convert the userType (webservice response) into UserType Ruby Class?

Rails 3.2.12 and Ruby 1.9.3p194


Solution

  • You should be able to implement userType as an instance method.

    class MyResource < ActiveResource::Base
      self.site = "http://api.example.com/"
    
      def userType
        UserType.new(userTypeId: super.userTypeId, description: super.description) 
      end
    end
    

    This works because ActiveResource automatically creates a "getter" method for each of the keys in the attributes hash that you pass into the class constructor. When the called attribute method corresponds to a hash value, ActiveResource returns an instance of an automatically generated class MyResource::UserType, which respectively will respond to the userTypeId and the description methods. You can get hold of this instance by calling super within the overridden method, and passing the value of userTypeId and description to your own class.

    Edit: - Corrected class name

    PS: Have a look at the ActiveResource#load method for more details on how attribute getter methods get generated.