apotonick/roar-rails — pull request #8 by nilclass (2012-02-23 12:28:29+00:00)
Title: Fixes & more

Hi there Nick!

I had a bunch of problems, some were solved by the attached commit.
Basically what brought me there was "undefined method to_hash", when only using the Roar::Representer::XML module. First I tried including *both* Roar::Representer::JSON and Roar::Representer::XML (in that order), that way to_hash is there (from Representable::JSON I suppose). The XML output wasn't as expected, though. Every object wrapped in a tag and the whole collection was called .
The name of the collection tag is correct, after applying the attached commit and *not* including Roar::Representer::JSON. Works for me. However, the collection tag ended up empty. So I started digging.

What I came up with at last, is this:

```ruby
module ArrayRepresenter
def to_xml(options={})
options = options.dup
options[:indent] ||= 2
options[:root] ||= if first.class.to_s != "Hash" && all? { |e| e.is_a?(first.class) }
underscored = ActiveSupport::Inflector.underscore(first.class.name)
ActiveSupport::Inflector.pluralize(underscored).tr('_', '-').tr('/', '_')
else
"objects"
end

doc = Nokogiri::XML::Document.new
doc.root = Nokogiri::XML::Element.new(options[:root], doc)
doc.root['type'] = 'array' unless options[:skip_types]
child_name = ActiveSupport::Inflector.singularize(options[:root])
each do |element|
doc.root.add_child(element.to_node(:wrap => child_name))
end
return doc.to_xml
end
end
```

It is roughly based on active_support/core_ext/array/conversion.rb, but uses Nokogiri to be compatible with to_node, instead of Builder::XmlMarkup/ActiveSupport::MiniXml (the purpose of which is totally lost on me...).

To use it I needed to put in the controller (I'm using inherited_resources by Jose Valim):

```ruby
private

def end_of_association_chain
super.extend(ArrayRepresenter)
end
```

I'm pretty sure this isn't at all how you intended this to be used.

To conclude: either a) I'm missing something or b) you were drunk when you wrote this. Tell me which :)

Take care.

Niklas

P.S.: Another side-node: when using the XML representer I get elements called like "user_id", when I would expect it to be "user-id" (that's what the default ActiveRecord::Base#to_xml generates). It's not really a big issue, but quite annoying when you're migrating from using plain to_xml to using representers. To keep the old version, I adjusted the ArrayRepresenter above and wrote another module:

```ruby
require 'roar/representer/xml'
module Roar::Representer::DashXML
def self.included(base)
base.send(:include, Roar::Representer::XML)
base.extend(ClassMethods)
end

module ClassMethods
def property(name, options={})
super(name, { :from => name.to_s.tr('_', '-') }.merge(options))
end
end
end

```