Sha256: 27b43f63ffe3b63d8e1d82021fa042f2c7eb7796c1bab70ca4c617e912664ed6

Contents?: true

Size: 1.32 KB

Versions: 17

Compression:

Stored size: 1.32 KB

Contents

require 'json'
require 'volt'

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

    def self.renderers
      @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 fromt he 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

17 entries across 17 versions & 1 rubygems

Version Path
volt-0.9.1 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.1.pre5 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.1.pre4 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.1.pre3 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.1.pre2 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.1.pre1 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.0 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.0.pre7 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.0.pre6 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.0.pre5 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.0.pre4 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.0.pre3 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.0.pre2 lib/volt/server/rack/http_response_renderer.rb
volt-0.9.0.pre1 lib/volt/server/rack/http_response_renderer.rb
volt-0.8.27.beta9 lib/volt/server/rack/http_response_renderer.rb
volt-0.8.27.beta8 lib/volt/server/rack/http_response_renderer.rb
volt-0.8.27.beta7 lib/volt/server/rack/http_response_renderer.rb