trailblazer / roar-rails

Use Roar's representers in Rails.
http://roar.apotomo.de
MIT License
235 stars 65 forks source link

Collections are not wrapped with with the right root tag in XML #59

Open dtshepherd opened 10 years ago

dtshepherd commented 10 years ago

When serializing using XML, the root tag is incorrect. It is either or depending on the version of rails. I believe this ultimately tracks back to here: https://github.com/apotonick/representable/blob/master/lib/representable.rb#L58

The self.class.name does not properly track back to the model when it is a collection. A work-around for now is to place self.representation_wrap = :collection_name in the collection representer. Maybe this can be set by roar-rails, since I don't think representable is the right place to fix it.

dtshepherd commented 10 years ago

I have a patch that can work around this issue... Haven't tested with parsing though.

module Roar::Rails::ControllerAdditions
  def prepare_model_for(format, model, options)
    representer = representer_for(format, model, options)
    if representer.representable_attrs.wrap == true
      representer.representation_wrap = model.table_name.to_sym if format == :xml and detect_collection(model)
    end
    representer.prepare(model)
  end

  def detect_collection(model)
    return true if model.kind_of?(Array)
    return true if Object.const_defined?("ActiveRecord") and model.kind_of?(ActiveRecord::Relation)
  end
end

Need to restrict to relations only or things don't work right (no table_name)

dtshepherd commented 10 years ago

The above patch does not fix wrapping when the ":as =>" directive is used on a collection. The collection will use the self.class.name which is the original collection name, not the :as alias. Still looking for a fix for that.

apotonick commented 10 years ago

A test case/concrete example would be great. Thanks!

dtshepherd commented 10 years ago

Sure, I'll try to get you something soon.