nesquena / rabl

General ruby templating with json, bson, xml, plist and msgpack support
http://blog.codepath.com/2011/06/27/building-a-platform-api-on-rails/
MIT License
3.65k stars 335 forks source link

Doesn't work with array input #96

Closed volkanunsal closed 13 years ago

volkanunsal commented 13 years ago

My usecase is simple. I fetch a geocoded array of objects and render them as a json template. I tried using rabl for the first time today, and it returns empty arrays. Here is my code.

#user_controller.rb
@result = Address.zip_lookup(zip)

#zip_lookup.json.rabl
collection @result => :places

#@result looks like this:

[{"quality"=>60, "latitude"=>"40.771562", "longitude"=>"-73.924623", "offsetlat"=>"40.771562", "offsetlon"=>"-73.924623", "radius"=>1400, "boundingbox"=>{"north"=>"40.781609", "south"=>"40.763569", "east"=>"-73.914307", "west"=>"-73.937889"}, "name"=>"", "line1"=>"", "line2"=>"Astoria, NY  11102", "line3"=>"", "line4"=>"United States", "cross"=>"", "house"=>"", "street"=>"", "xstreet"=>"", "unittype"=>"", "unit"=>"", "postal"=>"11102", "neighborhood"=>"Long Island City|Queens", "city"=>"Astoria", "county"=>"Queens County", "state"=>"New York", "country"=>"United States", "countrycode"=>"US", "statecode"=>"NY", "countycode"=>"", "timezone"=>"America/New_York", "areacode"=>"212", "uzip"=>"11102", "hash"=>"", "woeid"=>12761712, "woetype"=>11}]

And the output is:

            {

                -
                places: [
                    -
                    {
                        place: { }
                    }
                ]

            }
nesquena commented 13 years ago

Am I correct in assuming that you are trying to use array of hashes as the object? I don't see you specifying any output in the rabl file as to what attributes you want displayed either. Something like

#zip_lookup.json.rabl
collection @result => :places

attributes :quality, :latitude, :longitude

Also, RABL doesn't really work for simple hashes in this way. RABL was intended to be used with ORM records (AR, Mongoid) or in the git version any object that supports "dot" notation for attributes. A hash is not intended to work as an object but you could make it work anyways with RABL since its fairly flexible:

object false # skip objects (hash isn't supported as an object)

# create a "places" node
node :places do
  # setup a { place : { ...data... } } json array
  @result.map { |data| { :place => data } }
end

as an example.