Class: Sinatra::RespondWith::Format

Inherits:
Object
  • Object
show all
Defined in:
lib/sinatra/respond_with.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Format

Returns a new instance of Format.



90
91
92
# File 'lib/sinatra/respond_with.rb', line 90

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object



121
122
123
124
# File 'lib/sinatra/respond_with.rb', line 121

def method_missing(meth, *args, &block)
  return super if args.any? or block.nil? or not @app.mime_type(meth)
  on(meth, &block)
end

Instance Method Details

#finish {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/sinatra/respond_with.rb', line 104

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[/^[^\/]+/]], @default].compact
  handlers.each do |block|
    if result = block.call(type)
      @app.content_type mime_type
      @app.halt result
    end
  end
  @app.halt 406
end

#on(type, &block) ⇒ Object



94
95
96
97
98
99
100
101
102
# File 'lib/sinatra/respond_with.rb', line 94

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