Sha256: 6c8a70e4861459209c7a70f64b216f4c91beb6a9d55d2ac73a14120fd9ce718e

Contents?: true

Size: 1.17 KB

Versions: 2

Compression:

Stored size: 1.17 KB

Contents

require 'tilt'
Rabl.register!

module Grape
  module Middleware
    class Formatter
      alias :old_after :after

      def after
        status, headers, bodies = *@app_response
        current_endpoint = env['api.endpoint']

        rabl(current_endpoint) do |template|
          engine = ::Tilt.new(view_path(template))
          rendered = engine.render(current_endpoint, {})
          Rack::Response.new(rendered, status, headers).to_a
        end
      end

      private

      def view_path(template)
        if template.split(".")[-1] == "rabl"
          File.join(env['api.tilt.root'], template)
        else
          File.join(env['api.tilt.root'], (template + ".rabl"))
        end
      end

      def rabl(endpoint)
        if template = rablable?(endpoint)
          yield template
        else
          old_after
        end
      end

      def rablable?(endpoint)
        if template = endpoint.options[:route_options][:rabl]
          set_view_root unless env['api.tilt.root']
          template
        else
          false
        end
      end
  
      def set_view_root
        raise "Use Rack::Config to set 'api.tilt.root' in config.ru"
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
grape-rabl-0.0.4 lib/grape-rabl/formatter.rb
grape-rabl-0.0.3 lib/grape-rabl/formatter.rb