Skip to content

Instantly share code, notes, and snippets.

@kristjan
Created February 28, 2011 06:35
Show Gist options
  • Save kristjan/847011 to your computer and use it in GitHub Desktop.
Save kristjan/847011 to your computer and use it in GitHub Desktop.
DRYer XML/JSON response logic
module ApiFormats
API_FORMATS = %w[json xml].map(&:to_sym).freeze
def self.included(base)
base.send :private, :api_formats
end
def api_formats(format, data=nil, options={})
API_FORMATS.each do |encoding|
format.send(encoding) do
if block_given?
yield
else
render options.merge(encoding => data)
end
end
end
end
end

Instead of

respond_to do |format|
  format.html # show.html.erb
  format.xml  {render :xml  => @item}
  format.json {render :json => @item}
end

Use

respond_to do |format|
  format.html
  api_formats format, @item
end

Takes options

api_formats format, @item,                                     
  :status => :created, :location => @item

And blocks

api_formats(format) {head :ok}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment