Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize With Options Configuration Blocks

I'm using serialize_with_options ( http://www.viget.com/extend/simple-apis-using-serializewithoptions/ ) in a rails project and have been using named blocks for rendering as per the example on the linked page:

class Speaker < ActiveRecord::Base
  # ...

  serialize_with_options do
    methods   :average_rating, :avatar_url
    except    :email, :claim_code
    includes  :talks
  end

  serialize_with_options :with_email do
    methods   :average_rating, :avatar_url
    except    :claim_code
    includes  :talks
  end

end

Then I can call the second block configuration with @speaker.to_xml(:with_email). This works well, however, I'd like to figure out how to call this block when I have an array of objects. For example, the following does not work:

@speakers = Speaker.all
@speakers.to_xml(:with_email)

Which returns a "TypeError: can't dup Symbol" error. This makes sense to me since Array hasn't been configured to use serialize_with_options. How can I get this tag to be passed on to the individual speaker objects when running .to_xml and render all speakers :with_email?

like image 987
Tron Avatar asked Jun 09 '11 18:06

Tron


1 Answers

In your above example, @speakers is a Array object. You need to implement / override the to_xml there . Then i should work:

class Array
    def to_xml (with_email)
        self.each do |element|
            element.to_xml(with_email)
        end
    end
end
like image 71
Roger Avatar answered Sep 22 '22 23:09

Roger