views:

297

answers:

3

I'm trying to get a list of active record results to display as a plist for being consumed by the iphone. I'm using the plist gem v 3.0.

My model is called Post. And I want Post.all (or any array or Posts) to display correctly as a Plist.

I have it working fine for one Post instance: [http://pastie.org/580902][1]

that is correct, what I would expect. To get that behavior I had to do this:

class Post < ActiveRecord::Base
   def to_plist
     attributes.to_plist
   end
end

However, when I do a Post.all, I can't get it to display what I want. Here is what happens: http://pastie.org/580909

I get marshalling. I want output more like this: [http://pastie.org/580914][2]

I suppose I could just iterate the result set and append the plist strings. But seems ugly, I'm sure there is a more elegant way to do this.

I am rusty on Ruby right now, so the elegant way isn't obvious to me. Seems like I should be able to override ActiveRecord and make result-sets that pull back more than one record take the ActiveRecord::Base to_plist and make another to_plist implementation. In rails, this would go in environment.rb, right?

A: 

I took the easy way out:

private

  # pass in posts resultset from finds
  def posts_to_plist(posts)
    plist_array = []
    posts.each do |post|
      plist_array << post.attributes
    end
    plist_array.to_plist
  end

public

  # GET /posts
  # GET /posts.xml
  def index
    @posts = Post.all
    #@posts = [{:a=>"blah"}, {:b=>"blah2"}]

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => posts_to_plist(@posts) }
    end
  end
phil swenson
A: 

I found this page searching for the same answer. I think you have the right approach, though I'm also a newbie (on Rails) and not sure the right way to do it. I added this to application_helper.rb. Seems to work.

require 'plist'
module ApplicationHelper

  class ActiveRecord::Base
    public

    include Plist::Emit

    def to_plist 
      self.attribute_names.inject({}) do |attrs, name|
        value = self.read_attribute(name)
        if !value.nil?
          attrs[name] = value
        end
        attrs
      end
    end
  end

end
Ian Kershaw
+1  A: 

Check out my plistifier plugin http://github.com/jeena/plistifier

Jeena
This plugin is the bee's knees
Nick