123456789_123456789_123456789_123456789_123456789_

Class: Sinatra::RespondWith::Format

Relationships & Source Files
Inherits: Object
Defined in: sinatra-contrib/lib/sinatra/respond_with.rb

Class Method Summary

Instance Method Summary

Constructor Details

.new(app) ⇒ Format

[ GitHub ]

  
# File 'sinatra-contrib/lib/sinatra/respond_with.rb', line 92

def initialize(app)
  @app = app
  @map = {}
  @generic = {}
  @default = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block)

[ GitHub ]

  
# File 'sinatra-contrib/lib/sinatra/respond_with.rb', line 126

def method_missing(method, *args, &block)
  return super if args.any? || block.nil? || !@app.mime_type(method)

  on(method, &block)
end

Instance Method Details

#finish {|_self| ... }

Yields:

  • (_self)

Yield Parameters:

  • _self (Format)

    the object that the method was called on

[ GitHub ]

  
# File 'sinatra-contrib/lib/sinatra/respond_with.rb', line 109

def finish
  yield self if block_given?
  mime_type = @app.content_type ||
              @app.request.preferred_type(@map.keys)  ||
              @app.request.preferred_type             ||
              'text/html'
  type = mime_type.split(/\s*;\s*/, 2).first
  handlers = [@map[type], @generic[type[%r{^[^/]+}]], @default].compact
  handlers.each do |block|
    if (result = block.call(type))
      @app.content_type mime_type
      @app.halt result
    end
  end
  @app.halt 500, 'Unknown template engine'
end

#on(type, &block)

[ GitHub ]

  
# File 'sinatra-contrib/lib/sinatra/respond_with.rb', line 99

def on(type, &block)
  @app.settings.mime_types(type).each do |mime|
    case mime
    when '*/*'            then @default     = block
    when %r{^([^/]+)/\*$} then @generic[$1] = block
    else                       @map[mime]   = block
    end
  end
end