Skip to content

Instantly share code, notes, and snippets.

@paul
Created July 6, 2010 05:50
Show Gist options
  • Save paul/465064 to your computer and use it in GitHub Desktop.
Save paul/465064 to your computer and use it in GitHub Desktop.
{
href: services_path,
id: services_url,
version: resources.max(:updated_at),
count: resources.size,
members: render(:rfj => resources)
}
require 'yajl'
module Jrb
class TemplateHandler < ActionView::Template::Handler
include ActionView::Template::Handlers::Compilable
ActionView::Template.register_template_handler(:jrb, self)
self.default_format = Mime::JSON
def compile(template)
template.source
end
end
::ActionController::Renderers.add(:rfj_collection) do |resources, options|
output = render("shared/collection", :locals => { :resources => resources })
output = Yajl::Encoder.encode(output, :pretty => true)
self.response_body = output
end
::ActionController::Renderers.add(:rfj) do |resource, options|
options[:partial] = resource
options.delete(:layout)
output = JrbPartialRenderer.new(self.view_context, options, nil).render
# If we got a set of resources, we're being rendered inside a collection,
# so just return the results and let the collection renderer handle the rest
return output if resource.is_a?(Array)
output = Yajl::Encoder.encode(output, :pretty => true)
self.response_body = output
end
class JrbPartialRenderer < ActionView::Partials::PartialRenderer
def render_collection
return nil if @collection.blank?
if @options.key?(:spacer_template)
spacer = find_template(@options[:spacer_template]).render(@view, @locals)
end
result = @template ? collection_with_template : collection_without_template
# skip forcing the result into a sting
#result.join(spacer).html_safe
end
def find_template(path=@path)
return path unless path.is_a?(String)
prefix = @view.controller_path unless path.include?(?/)
# Actually, pretend we're not a partial, so we don't use underscored templates
@view.find_template(path, prefix, false)
end
end
end
class ServicesController < ApplicationController
def index
@services = Service.all
render :rfj_collection => @services
end
def show
@service = Service.find(:first)
render :rfj => @service
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment