Sha256: c27e1448cddab1ee2d8cefe88ea8989cac1db2522dea671d26aee0bbea85763c

Contents?: true

Size: 1.27 KB

Versions: 2

Compression:

Stored size: 1.27 KB

Contents

require 'json'

module Grape
  module Formatter
    module Rabl
      class << self

        attr_reader :env
        attr_reader :endpoint

        def call(object, env)

          @env = env
          @endpoint = env['api.endpoint']

          if rablable?
            rabl do |template|
              engine = ::Tilt.new(view_path(template), {format: env['api.format'], view_path: env['api.tilt.root']})
              engine.render endpoint, {}
            end
          else
            Grape::Formatter::Json.call object, env
          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 rablable?
            !! endpoint.options[:route_options][:rabl]
          end

          def rabl
            template = endpoint.options[:route_options][:rabl]
            raise "missing rabl template" unless template
            set_view_root unless env['api.tilt.root']
            yield template
          end

          def set_view_root
            raise "Use Rack::Config to set 'api.tilt.root' in config.ru"
          end

      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
grape-rabl-0.2.2 lib/grape-rabl/formatter.rb
grape-rabl-0.2.1 lib/grape-rabl/formatter.rb