Module: Sinatra::RespondTo::Helpers

Defined in:
lib/sinatra/respond_to.rb

Instance Method Summary collapse

Instance Method Details

#charset(val = nil) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
# File 'lib/sinatra/respond_to.rb', line 176

def charset(val=nil)
  fail "Content-Type must be set in order to specify a charset" if response['Content-Type'].nil?

  if response['Content-Type'] =~ /charset=[^;]+/
    response['Content-Type'].sub!(/charset=[^;]+/, (val == '' && '') || "charset=#{val}")
  else
    response['Content-Type'] += ";charset=#{val}"
  end unless val.nil?

  response['Content-Type'][/charset=([^;]+)/, 1]
end

#format(val = nil) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/sinatra/respond_to.rb', line 155

def format(val=nil)
  unless val.nil?
    mime_type = media_type(val)
    fail "Unknown media type #{val}\nTry registering the extension with a mime type" if mime_type.nil?

    @format = val.to_sym
    response['Content-Type'].sub!(/^[^;]+/, mime_type)
  end

  @format
end

#respond_to {|wants| ... } ⇒ Object

Yields:

  • (wants)

Raises:



188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/sinatra/respond_to.rb', line 188

def respond_to(&block)
  wants = {}
  def wants.method_missing(type, *args, &handler)
    Sinatra::Base.send(:fail, "Unknown media type for respond_to: #{type}\nTry registering the extension with a mime type") if Sinatra::Base.media_type(type).nil?
    self[type] = handler
  end

  yield wants

  raise UnhandledFormat  if wants[format].nil?
  wants[format].call
end

#static_file?(path) ⇒ Boolean

This is mostly just a helper so request.path_info isn’t changed when serving files from the public directory

Returns:

  • (Boolean)


169
170
171
172
173
174
# File 'lib/sinatra/respond_to.rb', line 169

def static_file?(path)
  public_dir = File.expand_path(options.public)
  path = File.expand_path(File.join(public_dir, unescape(path)))

  path[0, public_dir.length] == public_dir && File.file?(path)
end