Greg Benedict

Thoughts on the web and creativity.

Outputting Custom Model Attributes With to_json

I’m working on a project where I need to convert a model attribute on the fly from XML to XHTML. However, when I tried to drop it out using to_json on the object array, it didn’t display! Here’s how you can output an attr_reader method.

Here is the info from the model:

class Section < ActiveRecord::Base

after_find #this forces it to run anytime a find is called (pre-building it)attr_reader :content

def content=(value)

@content = value

end

def content

@content

end

def after_find

xml = self.content_xml

xslt = XML::XSLT.new()
xslt.xml = REXML::Document.new( “<?xml version=\”1.0\”?><book>\r\n#{xml}</book>” )
xslt.xsl = REXML::Document.new( File.new( “#{RAILS_ROOT}/db/xslt/to_xhtml.xsl” ) )

out = xslt.serve()
xhtml = Hpricot.XML(out)

self.content = xhtml.at(“body”).innerHTML

end

end

If you put the returned section array into yaml – y(@section), you’ll see it doesn’t show up in the attributes, but in the methods. So in reality meth_reader would be a more accurate name — but I digress. :)

Now here is how you make it work. Note the :methods => :content option. That’s what I couldn’t figure out.

@section = Section.find(:all, :select => “section_number, content_xml”, :conditions => “translation_id = #{translation_id} and section_number > #{section_number}”, :o rder => ‘section_number’, :limit => 15)

respond_to { |format|

format.html {}
format.xml { render :x ml => @section.to_xml(:only => :section_number,:methods => :content) }
format.js { render :json => @section.to_json(:only => :section_number, :methods => :content) }

}

Disclaimer: This is based on Rails 2.0 RC1.