Class: RackWarden::RespondWith::Format

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Format

Returns a new instance of Format.



93
94
95
# File 'lib/rack_warden/sinatra/respond_with.rb', line 93

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(method, *args, &block) ⇒ Object



139
140
141
142
# File 'lib/rack_warden/sinatra/respond_with.rb', line 139

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

Instance Method Details

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

Yields:

  • (_self)

Yield Parameters:



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/rack_warden/sinatra/respond_with.rb', line 113

def finish
  yield self if block_given?
  # WBR - adds format/extension of uri to front of mime-types.
  # You must capture the format string in the params with your route declaration.
  format_type = @app.settings.mime_types(@app.params['format'])[0]
  @app.logger.debug "RW respond_with.finish format_type (WBR): #{format_type}, #{format_type.class}"
  mime_type = format_type                   ||
  	@app.content_type                       ||
    @app.request.preferred_type(@map.keys)  ||
    @app.request.preferred_type             ||
    'text/html'
  type = mime_type.split(/\s*;\s*/, 2).first
  @app.logger.debug "RW respond_with.finish type: #{type}"
  @app.logger.debug "RW respond_with.finish @map: #{@map}"
  @app.logger.debug "RW respond_with.finish @default: #{@default}"
  @app.logger.debug "RW respond_with.finish @generic: #{@generic}"
  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



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/rack_warden/sinatra/respond_with.rb', line 97

def on(type, &block)
  # WBR
  @app.logger.debug "RW respond_with.on type: #{type}"
  @app.logger.debug "RW respond_with.on block: #{block}"
  @app.logger.debug "RW respond_with.on @app.params: #{@app.params}"
  @app.logger.debug "RW respond_with.on @app.settings.mime_types(type): #{@app.settings.mime_types(type)}"
  
  @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