to_xml with filtering
December 9th, 2007
Quick tips
If you're using respond_to in your application to expose records in xml...
class WidgetsController
def index
@widgets = current_account.widgets
respond_to do |format|
format.html
format.xml { render :xml => @widgets }
end
end
def show
@widget = current_account.widgets.find params[:id]
respond_to do |format|
format.html
format.xml { render :xml => @widget }
end
end
...
end
... and are wishing to eliminate meaningless (for the user) columns in the output (like account_id)...
<?xml version="1.0" encoding="UTF-8"?>
<widget>
<account-id type="integer">123</account-id>
<name>foo</name>
</widget>
you can easily drop the following in config/initializers:
active_record_ext.rb
class ActiveRecord::Base
def to_xml_with_filtering(options={})
defaults = { :except => :account_id }
to_xml_without_filtering defaults.merge(options)
end
alias_method_chain :to_xml, :filtering
end
and all your objects will filter the default columns.


Commenting is closed for this article.