Sha256: 22e260f3455b510d69a94464833e6664ebc41ee51bacfb13dd5584cfdf21542c

Contents?: true

Size: 1.33 KB

Versions: 2

Compression:

Stored size: 1.33 KB

Contents

require 'json'
require 'volt'

module Volt
  # Renders responses for HttpController actions
  class HttpResponseRenderer
    @renderers = {}

    class << self
      attr_reader :renderers
    end

    # Register renderers.
    def self.register_renderer(name, content_type, proc)
      @renderers[name.to_sym] = { proc: proc, content_type: content_type }
    end

    # Default renderers for json and plain text
    register_renderer(:json, 'application/json', proc { |data| data.to_json })
    register_renderer(:text, 'text/plain', proc { |data| data.to_s })

    # Iterate through @renderes to find a matching renderer for the given
    # content and call the given proc.
    # Other params from the content are returned as additional headers
    # Returns an empty string if no renderer could be found
    def render(content)
      content = content.symbolize_keys
      self.class.renderers.keys.each do |renderer_name|
        if content.key?(renderer_name)
          renderer = self.class.renderers[renderer_name]
          to_render = content.delete(renderer_name)
          rendered = renderer[:proc].call(to_render)
          return [rendered, content.merge(content_type: renderer[:content_type])]
        end
      end

      # If we couldn't find a renderer - just render an empty string
      ['', content_type: 'text/plain']
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
volt-0.9.3.pre6 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.3.pre5 lib/volt/server/rack/http_response_renderer.rb