Skip to content

Instantly share code, notes, and snippets.

@paul
Created August 19, 2011 16:51
Show Gist options
  • Save paul/1157315 to your computer and use it in GitHub Desktop.
Save paul/1157315 to your computer and use it in GitHub Desktop.
require 'active_support/time_with_zone'
class ActiveSupport::TimeWithZone
def to_json(options = nil)
utc.xmlschema.to_json
end
end
module Jrb
EPOCH = Time.utc(2000, 1, 1).iso8601
PRETTY = !Rails.env.production?
class TemplateHandler
ActionView::Template.register_template_handler(:jrb, self)
def self.call(template)
template.source
#"Yajl::Encoder.encode(#{template.source.strip}, :pretty => !Rails.env.production?)"
end
end
::ActionController::Renderers.add(:jrb_collection) do |resources, options|
output = {
:href => request.url,
:item_count => resources.count,
:items => render(:jrb => resources)
}
output = Yajl::Encoder.encode(output, :pretty => PRETTY)
self.response_body = output
end
::ActionController::Renderers.add(:jrb) do |resource, options|
options[:partial] ||= resource
output = JrbPartialRenderer.new(self.lookup_context).render(self.view_context, options, nil)
# 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 [] if output.nil?
return output if output.is_a?(Array)
output = Yajl::Encoder.encode(output, :pretty => PRETTY)
self.response_body = output
end
# Overwrite a couple methods in the normal PartialRenderer so it doesn't automatically
# turn it into a string, and returns the generated Hash instead.
class JrbPartialRenderer < ActionView::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. everything above this is just like the original method
#result.join(spacer).html_safe
end
def find_template(path=@path, [email protected])
prefixes = path.include?(?/) ? [] : @lookup_context.prefixes
# Actually, pretend we're not a partial, so we don't use underscored templates
@lookup_context.find_template(path, prefixes, false, locals)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment