bialy-dataset / coderank /units /sinatra.jsonl
paintedwolf-ai's picture
Release open1-b5-e4-bialy
24918f7 verified
Raw History Blame Contribute Delete
475 kB
{"repo":"sinatra","file":"Rakefile","line":10,"symbol":"source_version","kind":"method","lang":"ruby","code":"def source_version\n @source_version ||= File.read(File.expand_path('VERSION', __dir__)).strip\nend"}
{"repo":"sinatra","file":"Rakefile","line":14,"symbol":"prev_feature","kind":"method","lang":"ruby","code":"def prev_feature\n source_version.gsub(/^(\\d\\.)(\\d+)\\..*$/) { $1 + ($2.to_i - 1).to_s }\nend"}
{"repo":"sinatra","file":"Rakefile","line":18,"symbol":"prev_version","kind":"method","lang":"ruby","code":"def prev_version\n return \"#{prev_feature}.0\" if source_version.end_with? '.0'\n\n source_version.gsub(/\\d+$/) { |s| s.to_i - 1 }\nend"}
{"repo":"sinatra","file":"Rakefile","line":118,"symbol":"link","kind":"method","lang":"ruby","code":"def self.link(title)\n title.downcase.gsub(/(?!-)\\W /, '-').gsub(' ', '-').gsub(/(?!-)\\W/, '')\n end"}
{"repo":"sinatra","file":"Rakefile","line":138,"symbol":"package","kind":"method","lang":"ruby","code":"def package(gem, ext = '')\n \"pkg/#{gem}-#{source_version}\" + ext\n end"}
{"repo":"sinatra","file":"examples/stream.ru","line":12,"symbol":"Stream","kind":"class","lang":"ruby","code":"class Stream < Sinatra::Base\n get '/' do\n content_type :txt\n\n stream do |out|\n out << \"It's gonna be legen -\\n\"\n sleep 0.5\n out << \" (wait for it) \\n\"\n sleep 1\n out << \"- dary!\\n\"\n end\n end\nend"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":28,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # The request object. See Rack::Request for more info:\n # https://rubydoc.info/github/rack/rack/main/Rack/Request\n class Request < Rack::Request\n HEADER_PARAM = /\\s*[\\w.]+=(?:[\\w.]+|\"(?:[^\"\\\\]|\\\\.)*\")?\\s*/.freeze\n HEADER_VALUE_WITH_PARAMS = %r{(?:(?:\\w+|\\*)/(?:\\w+(?:\\.|-|\\+)?|\\*)*)\\s*(?:;#{HEADER_PARAM})*}.freeze\n\n # Returns an array of acceptable media types for the response\n def accept\n @env['sinatra.accept'] ||= if @env.include?('HTTP_ACCEPT') && (@env['HTTP_ACCEPT'].to_s != '')\n @env['HTTP_ACCEPT']\n .to_s\n .scan(HEADER_VALUE_WITH_PARAMS)\n .map! { |e| AcceptEntry.new(e) }\n .sort\n else\n [AcceptEntry.new('*/*')]\n end\n end\n\n def accept?(type)\n preferred_type(type).to_s.include?(type)\n end\n\n def preferred_type(*types)\n return accept.first if types.empty?\n\n types.flatten!\n return types.first if accept.empty?\n\n accept.detect do |accept_header"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":31,"symbol":"Request","kind":"class","lang":"ruby","doc":"The request object. See Rack::Request for more info: https://rubydoc.info/github/rack/rack/main/Rack/Request","code":"class Request < Rack::Request\n HEADER_PARAM = /\\s*[\\w.]+=(?:[\\w.]+|\"(?:[^\"\\\\]|\\\\.)*\")?\\s*/.freeze\n HEADER_VALUE_WITH_PARAMS = %r{(?:(?:\\w+|\\*)/(?:\\w+(?:\\.|-|\\+)?|\\*)*)\\s*(?:;#{HEADER_PARAM})*}.freeze\n\n # Returns an array of acceptable media types for the response\n def accept\n @env['sinatra.accept'] ||= if @env.include?('HTTP_ACCEPT') && (@env['HTTP_ACCEPT'].to_s != '')\n @env['HTTP_ACCEPT']\n .to_s\n .scan(HEADER_VALUE_WITH_PARAMS)\n .map! { |e| AcceptEntry.new(e) }\n .sort\n else\n [AcceptEntry.new('*/*')]\n end\n end\n\n def accept?(type)\n preferred_type(type).to_s.include?(type)\n end\n\n def preferred_type(*types)\n return accept.first if types.empty?\n\n types.flatten!\n return types.first if accept.empty?\n\n accept.detect do |accept_header|\n type = types.detect { |t| MimeTypeEntry.new(t).accepts?(accept_header) }\n return type if type\n end\n end\n\n "}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":36,"symbol":"accept","kind":"method","lang":"ruby","doc":"Returns an array of acceptable media types for the response","code":"def accept\n @env['sinatra.accept'] ||= if @env.include?('HTTP_ACCEPT') && (@env['HTTP_ACCEPT'].to_s != '')\n @env['HTTP_ACCEPT']\n .to_s\n .scan(HEADER_VALUE_WITH_PARAMS)\n .map! { |e| AcceptEntry.new(e) }\n .sort\n else\n [AcceptEntry.new('*/*')]\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":48,"symbol":"accept?","kind":"method","lang":"ruby","code":"def accept?(type)\n preferred_type(type).to_s.include?(type)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":52,"symbol":"preferred_type","kind":"method","lang":"ruby","code":"def preferred_type(*types)\n return accept.first if types.empty?\n\n types.flatten!\n return types.first if accept.empty?\n\n accept.detect do |accept_header|\n type = types.detect { |t| MimeTypeEntry.new(t).accepts?(accept_header) }\n return type if type\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":66,"symbol":"forwarded?","kind":"method","lang":"ruby","code":"def forwarded?\n !forwarded_authority.nil?\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":70,"symbol":"safe?","kind":"method","lang":"ruby","code":"def safe?\n get? || head? || options? || trace?\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":74,"symbol":"idempotent?","kind":"method","lang":"ruby","code":"def idempotent?\n safe? || put? || delete? || link? || unlink?\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":78,"symbol":"link?","kind":"method","lang":"ruby","code":"def link?\n request_method == 'LINK'\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":82,"symbol":"unlink?","kind":"method","lang":"ruby","code":"def unlink?\n request_method == 'UNLINK'\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":86,"symbol":"params","kind":"method","lang":"ruby","code":"def params\n super\n rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e\n raise BadRequest, \"Invalid query parameters: #{Rack::Utils.escape_html(e.message)}\"\n rescue EOFError => e\n raise BadRequest, \"Invalid multipart/form-data: #{Rack::Utils.escape_html(e.message)}\"\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":94,"symbol":"AcceptEntry","kind":"class","lang":"ruby","code":"class AcceptEntry\n attr_accessor :params\n attr_reader :entry\n\n def initialize(entry)\n params = entry.scan(HEADER_PARAM).map! do |s|\n key, value = s.strip.split('=', 2)\n value = value[1..-2].gsub(/\\\\(.)/, '\\1') if value.start_with?('\"')\n [key, value]\n end\n\n @entry = entry\n @type = entry[/[^;]+/].delete(' ')\n @params = params.to_h\n @q = @params.delete('q') { 1.0 }.to_f\n end\n\n def <=>(other)\n other.priority <=> priority\n end\n\n def priority\n # We sort in descending order; better matches should be higher.\n [@q, -@type.count('*'), @params.size]\n end\n\n def to_str\n @type\n end\n\n def to_s(full = false)\n full ? entry : to_str\n end\n\n def respond_to?(*args)\n super || to_str.respond_to?(*args)\n end\n\n def method_missing(*args, &block)\n to_str.send(*args, &block)\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":98,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(entry)\n params = entry.scan(HEADER_PARAM).map! do |s|\n key, value = s.strip.split('=', 2)\n value = value[1..-2].gsub(/\\\\(.)/, '\\1') if value.start_with?('\"')\n [key, value]\n end\n\n @entry = entry\n @type = entry[/[^;]+/].delete(' ')\n @params = params.to_h\n @q = @params.delete('q') { 1.0 }.to_f\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":115,"symbol":"priority","kind":"method","lang":"ruby","code":"def priority\n # We sort in descending order; better matches should be higher.\n [@q, -@type.count('*'), @params.size]\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":120,"symbol":"to_str","kind":"method","lang":"ruby","code":"def to_str\n @type\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":124,"symbol":"to_s","kind":"method","lang":"ruby","code":"def to_s(full = false)\n full ? entry : to_str\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":128,"symbol":"respond_to?","kind":"method","lang":"ruby","code":"def respond_to?(*args)\n super || to_str.respond_to?(*args)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":132,"symbol":"method_missing","kind":"method","lang":"ruby","code":"def method_missing(*args, &block)\n to_str.send(*args, &block)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":137,"symbol":"MimeTypeEntry","kind":"class","lang":"ruby","code":"class MimeTypeEntry\n attr_reader :params\n\n def initialize(entry)\n params = entry.scan(HEADER_PARAM).map! do |s|\n key, value = s.strip.split('=', 2)\n value = value[1..-2].gsub(/\\\\(.)/, '\\1') if value.start_with?('\"')\n [key, value]\n end\n\n @type = entry[/[^;]+/].delete(' ')\n @params = params.to_h\n end\n\n def accepts?(entry)\n File.fnmatch(entry, self) && matches_params?(entry.params)\n end\n\n def to_str\n @type\n end\n\n def matches_params?(params)\n return true if @params.empty?\n\n params.all? { |k, v| !@params.key?(k) || @params[k] == v }\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":140,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(entry)\n params = entry.scan(HEADER_PARAM).map! do |s|\n key, value = s.strip.split('=', 2)\n value = value[1..-2].gsub(/\\\\(.)/, '\\1') if value.start_with?('\"')\n [key, value]\n end\n\n @type = entry[/[^;]+/].delete(' ')\n @params = params.to_h\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":151,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(entry)\n File.fnmatch(entry, self) && matches_params?(entry.params)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":155,"symbol":"to_str","kind":"method","lang":"ruby","code":"def to_str\n @type\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":159,"symbol":"matches_params?","kind":"method","lang":"ruby","code":"def matches_params?(params)\n return true if @params.empty?\n\n params.all? { |k, v| !@params.key?(k) || @params[k] == v }\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":171,"symbol":"Response","kind":"class","lang":"ruby","doc":"The response object. See Rack::Response and Rack::Response::Helpers for more info: https://rubydoc.info/github/rack/rack/main/Rack/Response https://rubydoc.info/github/rack/rack/main/Rack/Response/Helpers","code":"class Response < Rack::Response\n DROP_BODY_RESPONSES = [204, 304].freeze\n\n def body=(value)\n value = value.body while Rack::Response === value\n @body = String === value ? [value.to_str] : value\n end\n\n def each\n block_given? ? super : enum_for(:each)\n end\n\n def finish\n result = body\n\n if drop_content_info?\n headers.delete 'content-length'\n headers.delete 'content-type'\n end\n\n if drop_body?\n close\n result = []\n end\n\n if calculate_content_length?\n # if some other code has already set content-length, don't muck with it\n # currently, this would be the static file-handler\n headers['content-length'] = body.map(&:bytesize).reduce(0, :+).to_s\n end\n\n [status, headers, result]\n end\n\n private\n\n def calculate_content_length?\n headers['content-type'] && !headers['content-length'] && (Array === body)\n end\n\n def drop_content_info?\n informational? || drop_body?\n end\n\n def drop_body?\n DROP_BODY_RESPONSES.include?(status)\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":179,"symbol":"each","kind":"method","lang":"ruby","code":"def each\n block_given? ? super : enum_for(:each)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":183,"symbol":"finish","kind":"method","lang":"ruby","code":"def finish\n result = body\n\n if drop_content_info?\n headers.delete 'content-length'\n headers.delete 'content-type'\n end\n\n if drop_body?\n close\n result = []\n end\n\n if calculate_content_length?\n # if some other code has already set content-length, don't muck with it\n # currently, this would be the static file-handler\n headers['content-length'] = body.map(&:bytesize).reduce(0, :+).to_s\n end\n\n [status, headers, result]\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":207,"symbol":"calculate_content_length?","kind":"method","lang":"ruby","code":"def calculate_content_length?\n headers['content-type'] && !headers['content-length'] && (Array === body)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":211,"symbol":"drop_content_info?","kind":"method","lang":"ruby","code":"def drop_content_info?\n informational? || drop_body?\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":215,"symbol":"drop_body?","kind":"method","lang":"ruby","code":"def drop_body?\n DROP_BODY_RESPONSES.include?(status)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":225,"symbol":"ExtendedRack","kind":"class","lang":"ruby","doc":"Some Rack handlers implement an extended body object protocol, however, some middleware (namely Rack::Lint) will break it by not mirroring the methods in question. This middleware will detect an extended body object and will make sure it reaches the handler directly. We do this here, so our middleware and middleware set up by the app will still be able to run.","code":"class ExtendedRack < Struct.new(:app)\n def call(env)\n result = app.call(env)\n callback = env['async.callback']\n return result unless callback && async?(*result)\n\n after_response { callback.call result }\n setup_close(env, *result)\n throw :async\n end\n\n private\n\n def setup_close(env, _status, _headers, body)\n return unless body.respond_to?(:close) && env.include?('async.close')\n\n env['async.close'].callback { body.close }\n env['async.close'].errback { body.close }\n end\n\n def after_response(&block)\n raise NotImplementedError, 'only supports EventMachine at the moment' unless defined? EventMachine\n\n EventMachine.next_tick(&block)\n end\n\n def async?(status, _headers, body)\n return true if status == -1\n\n body.respond_to?(:callback) && body.respond_to?(:errback)\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":226,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n result = app.call(env)\n callback = env['async.callback']\n return result unless callback && async?(*result)\n\n after_response { callback.call result }\n setup_close(env, *result)\n throw :async\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":238,"symbol":"setup_close","kind":"method","lang":"ruby","code":"def setup_close(env, _status, _headers, body)\n return unless body.respond_to?(:close) && env.include?('async.close')\n\n env['async.close'].callback { body.close }\n env['async.close'].errback { body.close }\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":245,"symbol":"after_response","kind":"method","lang":"ruby","code":"def after_response(&block)\n raise NotImplementedError, 'only supports EventMachine at the moment' unless defined? EventMachine\n\n EventMachine.next_tick(&block)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":251,"symbol":"async?","kind":"method","lang":"ruby","code":"def async?(status, _headers, body)\n return true if status == -1\n\n body.respond_to?(:callback) && body.respond_to?(:errback)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":260,"symbol":"CommonLogger","kind":"class","lang":"ruby","doc":"Behaves exactly like Rack::CommonLogger with the notable exception that it does nothing, if another CommonLogger is already in the middleware chain.","code":"class CommonLogger < Rack::CommonLogger\n def call(env)\n env['sinatra.commonlogger'] ? @app.call(env) : super\n end\n\n superclass.class_eval do\n alias_method :call_without_check, :call unless method_defined? :call_without_check\n def call(env)\n env['sinatra.commonlogger'] = true\n call_without_check(env)\n end\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":261,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n env['sinatra.commonlogger'] ? @app.call(env) : super\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":267,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n env['sinatra.commonlogger'] = true\n call_without_check(env)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":274,"symbol":"Error","kind":"class","lang":"ruby","code":"class Error < StandardError # :nodoc:\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":277,"symbol":"BadRequest","kind":"class","lang":"ruby","code":"class BadRequest < Error # :nodoc:\n def http_status; 400 end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":278,"symbol":"http_status","kind":"method","lang":"ruby","code":"def http_status; 400 end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":281,"symbol":"NotFound","kind":"class","lang":"ruby","code":"class NotFound < Error # :nodoc:\n def http_status; 404 end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":282,"symbol":"http_status","kind":"method","lang":"ruby","code":"def http_status; 404 end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":286,"symbol":"Helpers","kind":"module","lang":"ruby","doc":"Methods available to routes, before/after filters, and views.","code":"module Helpers\n # Set or retrieve the response status code.\n def status(value = nil)\n response.status = Rack::Utils.status_code(value) if value\n response.status\n end\n\n # Set or retrieve the response body. When a block is given,\n # evaluation is deferred until the body is read with #each.\n def body(value = nil, &block)\n if block_given?\n def block.each; yield(call) end\n response.body = block\n elsif value\n unless request.head? || value.is_a?(Rack::Files::BaseIterator) || value.is_a?(Stream)\n headers.delete 'content-length'\n end\n response.body = value\n else\n response.body\n end\n end\n\n # Halt processing and redirect to the URI provided.\n def redirect(uri, *args)\n http_version = env['SERVER_PROTOCOL']\n if (http_version == 'HTTP/1.1') && (env['REQUEST_METHOD'] != 'GET')\n status 303\n else\n status 302\n end\n\n # According to RFC 2616 section 14.30, \"the field value consists of a\n # single absolute URI\"\n response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?)\n halt(*args)\n end\n\n # Generate"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":288,"symbol":"status","kind":"method","lang":"ruby","doc":"Set or retrieve the response status code.","code":"def status(value = nil)\n response.status = Rack::Utils.status_code(value) if value\n response.status\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":295,"symbol":"body","kind":"method","lang":"ruby","doc":"Set or retrieve the response body. When a block is given, evaluation is deferred until the body is read with #each.","code":"def body(value = nil, &block)\n if block_given?\n def block.each; yield(call) end\n response.body = block\n elsif value\n unless request.head? || value.is_a?(Rack::Files::BaseIterator) || value.is_a?(Stream)\n headers.delete 'content-length'\n end\n response.body = value\n else\n response.body\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":297,"symbol":"each","kind":"method","lang":"ruby","code":"def block.each; yield(call) end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":310,"symbol":"redirect","kind":"method","lang":"ruby","doc":"Halt processing and redirect to the URI provided.","code":"def redirect(uri, *args)\n http_version = env['SERVER_PROTOCOL']\n if (http_version == 'HTTP/1.1') && (env['REQUEST_METHOD'] != 'GET')\n status 303\n else\n status 302\n end\n\n # According to RFC 2616 section 14.30, \"the field value consists of a\n # single absolute URI\"\n response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?)\n halt(*args)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":326,"symbol":"uri","kind":"method","lang":"ruby","doc":"Generates the absolute URI for a given path in the app. Takes Rack routers and reverse proxies into account.","code":"def uri(addr = nil, absolute = true, add_script_name = true)\n return addr if addr.to_s =~ /\\A[a-z][a-z0-9+.\\-]*:/i\n\n uri = [host = String.new]\n if absolute\n host << \"http#{'s' if request.secure?}://\"\n host << if request.forwarded? || (request.port != (request.secure? ? 443 : 80))\n request.host_with_port\n else\n request.host\n end\n end\n uri << request.script_name.to_s if add_script_name\n uri << (addr || request.path_info).to_s\n File.join uri\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":347,"symbol":"error","kind":"method","lang":"ruby","doc":"Halt processing and return the error status provided.","code":"def error(code, body = nil)\n if code.respond_to? :to_str\n body = code.to_str\n code = 500\n end\n response.body = body unless body.nil?\n halt code\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":357,"symbol":"not_found","kind":"method","lang":"ruby","doc":"Halt processing and return a 404 Not Found.","code":"def not_found(body = nil)\n error 404, body\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":362,"symbol":"headers","kind":"method","lang":"ruby","doc":"Set multiple response headers with Hash.","code":"def headers(hash = nil)\n response.headers.merge! hash if hash\n response.headers\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":368,"symbol":"session","kind":"method","lang":"ruby","doc":"Access the underlying Rack session.","code":"def session\n request.session\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":373,"symbol":"logger","kind":"method","lang":"ruby","doc":"Access shared logger object.","code":"def logger\n request.logger\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":378,"symbol":"mime_type","kind":"method","lang":"ruby","doc":"Look up a media type by file extension in Rack's mime registry.","code":"def mime_type(type)\n Base.mime_type(type)\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":384,"symbol":"content_type","kind":"method","lang":"ruby","doc":"Set the content-type of the response body given a media type or file extension.","code":"def content_type(type = nil, params = {})\n return response['content-type'] unless type\n\n default = params.delete :default\n mime_type = mime_type(type) || default\n raise format('Unknown media type: %p', type) if mime_type.nil?\n\n mime_type = mime_type.dup\n unless params.include?(:charset) || settings.add_charset.all? { |p| !(p === mime_type) }\n params[:charset] = params.delete('charset') || settings.default_encoding\n end\n params.delete :charset if mime_type.include? 'charset'\n unless params.empty?\n mime_type << ';'\n mime_type << params.map do |key, val|\n val = val.inspect if val.to_s =~ /[\";,]/\n \"#{key}=#{val}\"\n end.join(';')\n end\n response['content-type'] = mime_type\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":415,"symbol":"attachment","kind":"method","lang":"ruby","doc":"Set the Content-Disposition to \"attachment\" with the specified filename, instructing the user agents to prompt to save.","code":"def attachment(filename = nil, disposition = :attachment)\n response['Content-Disposition'] = disposition.to_s.dup\n return unless filename\n\n params = format('; filename=\"%s\"', File.basename(filename).gsub(/[\"\\r\\n]/, MULTIPART_FORM_DATA_REPLACEMENT_TABLE))\n response['Content-Disposition'] << params\n ext = File.extname(filename)\n content_type(ext) unless response['content-type'] || ext.empty?\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":426,"symbol":"send_file","kind":"method","lang":"ruby","doc":"Use the contents of the file at +path+ as the response body.","code":"def send_file(path, opts = {})\n if opts[:type] || !response['content-type']\n content_type opts[:type] || File.extname(path), default: 'application/octet-stream'\n end\n\n disposition = opts[:disposition]\n filename = opts[:filename]\n disposition = :attachment if disposition.nil? && filename\n filename = path if filename.nil?\n attachment(filename, disposition) if disposition\n\n last_modified opts[:last_modified] if opts[:last_modified]\n\n file = Rack::Files.new(File.dirname(settings.app_file))\n result = file.serving(request, path)\n\n result[1].each { |k, v| headers[k] ||= v }\n headers['content-length'] = result[1]['content-length']\n opts[:status] &&= Integer(opts[:status])\n halt (opts[:status] || result[0]), result[2]\n rescue Errno::ENOENT\n not_found\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":458,"symbol":"Stream","kind":"class","lang":"ruby","doc":"Three things really matter: The front and back block (back being the block generating content, front the one sending it to the client) and the scheduler, integrating with whatever concurrency feature the Rack handler is using. Scheduler has to respond to defer and schedule.","code":"class Stream\n def self.schedule(*) yield end\n def self.defer(*) yield end\n\n def initialize(scheduler = self.class, keep_open = false, &back)\n @back = back.to_proc\n @scheduler = scheduler\n @keep_open = keep_open\n @callbacks = []\n @closed = false\n end\n\n def close\n return if closed?\n\n @closed = true\n @scheduler.schedule { @callbacks.each { |c| c.call } }\n end\n\n def each(&front)\n @front = front\n @scheduler.defer do\n begin\n @back.call(self)\n rescue Exception => e\n @scheduler.schedule { raise e }\n ensure\n close unless @keep_open\n end\n end\n end\n\n def <<(data)\n @scheduler.schedule { @front.call(data.to_s) }\n self\n end\n\n def callback(&block)\n return yield if closed?\n\n @callbacks << block\n end\n\n alias errback callback\n\n def closed?\n @closed\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":459,"symbol":"schedule","kind":"method","lang":"ruby","code":"def self.schedule(*) yield end"}
{"repo":"sinatra","file":"lib/sinatra/base.rb","line":460,"symbol":"defer","kind":"method","lang":"ruby","code":"def self.defer(*) yield end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":3,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # A poor man's ActiveSupport::HashWithIndifferentAccess, with all the Rails-y\n # stuff removed.\n #\n # Implements a hash where keys <tt>:foo</tt> and <tt>\"foo\"</tt> are\n # considered to be the same.\n #\n # rgb = Sinatra::IndifferentHash.new\n #\n # rgb[:black] = '#000000' # symbol assignment\n # rgb[:black] # => '#000000' # symbol retrieval\n # rgb['black'] # => '#000000' # string retrieval\n #\n # rgb['white'] = '#FFFFFF' # string assignment\n # rgb[:white] # => '#FFFFFF' # symbol retrieval\n # rgb['white'] # => '#FFFFFF' # string retrieval\n #\n # Internally, symbols are mapped to strings when used as keys in the entire\n # writing interface (calling e.g. <tt>[]=</tt>, <tt>merge</tt>). This mapping\n # belongs to the public interface. For example, given:\n #\n # hash = Sinatra::IndifferentHash.new\n # hash[:a] = 1\n #\n # You are guaranteed that the key is returned as a string:\n #\n # hash.keys # => [\"a\"]\n #\n # Technically other types of keys are accepted:\n #\n # hash = Sinatra::IndifferentHash\n # hash[:a] = 1\n # hash[0] = 0\n # hash # => { \"a\"=>1, 0=>0 }\n #\n # But this class is intended for use cases where strings"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":41,"symbol":"IndifferentHash","kind":"class","lang":"ruby","doc":"hash[0] = 0 hash # => { \"a\"=>1, 0=>0 } But this class is intended for use cases where strings or symbols are the expected keys and it is convenient to understand both as the same. For example the +params+ hash in Sinatra.","code":"class IndifferentHash < Hash\n def self.[](*args)\n new.merge!(Hash[*args])\n end\n\n def default(*args)\n args.map!(&method(:convert_key))\n\n super(*args)\n end\n\n def default=(value)\n super(convert_value(value))\n end\n\n def assoc(key)\n super(convert_key(key))\n end\n\n def rassoc(value)\n super(convert_value(value))\n end\n\n def fetch(key, *args)\n args.map!(&method(:convert_value))\n\n super(convert_key(key), *args)\n end\n\n def [](key)\n super(convert_key(key))\n end\n\n def []=(key, value)\n super(convert_key(key), convert_value(value))\n end\n\n alias store []=\n\n def key(value)\n super(convert_value(value))\n end\n\n def key?(key)\n super(convert_key(key))\n end\n\n alias has_key? key?\n alias include? key?\n alias member? key?\n\n def value?(value)\n super(convert_value(value))\n end\n\n alias has_value? value?\n\n def delete(key)\n super(convert_key(key))\n end\n\n # Added in Ruby 2.3\n def dig(key, *other_keys)\n super(convert_key(key), *other_keys)\n end\n\n def fetch_values(*keys)\n keys.map!(&method(:convert_key))\n\n super(*keys)\n end\n\n def"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":46,"symbol":"default","kind":"method","lang":"ruby","code":"def default(*args)\n args.map!(&method(:convert_key))\n\n super(*args)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":56,"symbol":"assoc","kind":"method","lang":"ruby","code":"def assoc(key)\n super(convert_key(key))\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":60,"symbol":"rassoc","kind":"method","lang":"ruby","code":"def rassoc(value)\n super(convert_value(value))\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":64,"symbol":"fetch","kind":"method","lang":"ruby","code":"def fetch(key, *args)\n args.map!(&method(:convert_value))\n\n super(convert_key(key), *args)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":80,"symbol":"key","kind":"method","lang":"ruby","code":"def key(value)\n super(convert_value(value))\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":84,"symbol":"key?","kind":"method","lang":"ruby","code":"def key?(key)\n super(convert_key(key))\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":92,"symbol":"value?","kind":"method","lang":"ruby","code":"def value?(value)\n super(convert_value(value))\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":98,"symbol":"delete","kind":"method","lang":"ruby","code":"def delete(key)\n super(convert_key(key))\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":103,"symbol":"dig","kind":"method","lang":"ruby","doc":"Added in Ruby 2.3","code":"def dig(key, *other_keys)\n super(convert_key(key), *other_keys)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":107,"symbol":"fetch_values","kind":"method","lang":"ruby","code":"def fetch_values(*keys)\n keys.map!(&method(:convert_key))\n\n super(*keys)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":113,"symbol":"slice","kind":"method","lang":"ruby","code":"def slice(*keys)\n keys.map!(&method(:convert_key))\n\n self.class[super(*keys)]\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":119,"symbol":"values_at","kind":"method","lang":"ruby","code":"def values_at(*keys)\n keys.map!(&method(:convert_key))\n\n super(*keys)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":125,"symbol":"merge!","kind":"method","lang":"ruby","code":"def merge!(*other_hashes)\n other_hashes.each do |other_hash|\n if other_hash.is_a?(self.class)\n super(other_hash)\n else\n other_hash.each_pair do |key, value|\n key = convert_key(key)\n value = yield(key, self[key], value) if block_given? && key?(key)\n self[key] = convert_value(value)\n end\n end\n end\n\n self\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":143,"symbol":"merge","kind":"method","lang":"ruby","code":"def merge(*other_hashes, &block)\n dup.merge!(*other_hashes, &block)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":147,"symbol":"replace","kind":"method","lang":"ruby","code":"def replace(other_hash)\n super(other_hash.is_a?(self.class) ? other_hash : self.class[other_hash])\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":151,"symbol":"transform_values","kind":"method","lang":"ruby","code":"def transform_values(&block)\n dup.transform_values!(&block)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":155,"symbol":"transform_values!","kind":"method","lang":"ruby","code":"def transform_values!\n super\n super(&method(:convert_value))\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":160,"symbol":"transform_keys","kind":"method","lang":"ruby","code":"def transform_keys(&block)\n dup.transform_keys!(&block)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":164,"symbol":"transform_keys!","kind":"method","lang":"ruby","code":"def transform_keys!\n super\n super(&method(:convert_key))\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":169,"symbol":"select","kind":"method","lang":"ruby","code":"def select(*args, &block)\n return to_enum(:select) unless block_given?\n\n dup.tap { |hash| hash.select!(*args, &block) }\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":175,"symbol":"reject","kind":"method","lang":"ruby","code":"def reject(*args, &block)\n return to_enum(:reject) unless block_given?\n\n dup.tap { |hash| hash.reject!(*args, &block) }\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":181,"symbol":"compact","kind":"method","lang":"ruby","code":"def compact\n dup.tap(&:compact!)\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":185,"symbol":"except","kind":"method","lang":"ruby","code":"def except(*keys)\n keys.map!(&method(:convert_key))\n\n self.class[super(*keys)]\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":193,"symbol":"convert_key","kind":"method","lang":"ruby","code":"def convert_key(key)\n key.is_a?(Symbol) ? key.to_s : key\n end"}
{"repo":"sinatra","file":"lib/sinatra/indifferent_hash.rb","line":197,"symbol":"convert_value","kind":"method","lang":"ruby","code":"def convert_value(value)\n case value\n when Hash\n value.is_a?(self.class) ? value : self.class[value]\n when Array\n value.map(&method(:convert_value))\n else\n value\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/main.rb","line":3,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n PARAMS_CONFIG = {}\n\n if ARGV.any?\n require 'optparse'\n parser = OptionParser.new do |op|\n op.on('-p port', 'set the port (default is 4567)') { |val| PARAMS_CONFIG[:port] = Integer(val) }\n op.on('-s server', 'specify rack server/handler') { |val| PARAMS_CONFIG[:server] = val }\n op.on('-q', 'turn on quiet mode (default is off)') { PARAMS_CONFIG[:quiet] = true }\n op.on('-x', 'turn on the mutex lock (default is off)') { PARAMS_CONFIG[:lock] = true }\n op.on('-e env', 'set the environment (default is development)') do |val|\n ENV['RACK_ENV'] = val\n PARAMS_CONFIG[:environment] = val.to_sym\n end\n op.on('-o addr', \"set the host (default is (env == 'development' ? 'localhost' : '0.0.0.0'))\") do |val|\n PARAMS_CONFIG[:bind] = val\n end\n end\n begin\n parser.parse!(ARGV.dup)\n rescue StandardError => e\n PARAMS_CONFIG[:optparse_error] = e\n end\n end\n\n require 'sinatra/base'\n\n class Application < Base\n # we assume that the first file that requires 'sinatra' is the\n # app_file. all other path related options are ca"}
{"repo":"sinatra","file":"lib/sinatra/main.rb","line":30,"symbol":"Application","kind":"class","lang":"ruby","code":"class Application < Base\n # we assume that the first file that requires 'sinatra' is the\n # app_file. all other path related options are calculated based\n # on this path by default.\n set :app_file, caller_files.first || $0\n\n set :run, proc { File.expand_path($0) == File.expand_path(app_file) }\n\n if run? && ARGV.any?\n error = PARAMS_CONFIG.delete(:optparse_error)\n raise error if error\n\n PARAMS_CONFIG.each { |k, v| set k, v }\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/middleware/logger.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n module Middleware\n class Logger\n def initialize(app, level = ::Logger::INFO)\n @app, @level = app, level\n end\n\n def call(env)\n logger = ::Logger.new(env[Rack::RACK_ERRORS])\n logger.level = @level\n\n env[Rack::RACK_LOGGER] = logger\n @app.call(env)\n end\n end\n end\nend"}
{"repo":"sinatra","file":"lib/sinatra/middleware/logger.rb","line":6,"symbol":"Middleware","kind":"module","lang":"ruby","code":"module Middleware\n class Logger\n def initialize(app, level = ::Logger::INFO)\n @app, @level = app, level\n end\n\n def call(env)\n logger = ::Logger.new(env[Rack::RACK_ERRORS])\n logger.level = @level\n\n env[Rack::RACK_LOGGER] = logger\n @app.call(env)\n end\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/middleware/logger.rb","line":7,"symbol":"Logger","kind":"class","lang":"ruby","code":"class Logger\n def initialize(app, level = ::Logger::INFO)\n @app, @level = app, level\n end\n\n def call(env)\n logger = ::Logger.new(env[Rack::RACK_ERRORS])\n logger.level = @level\n\n env[Rack::RACK_LOGGER] = logger\n @app.call(env)\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/middleware/logger.rb","line":8,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app, level = ::Logger::INFO)\n @app, @level = app, level\n end"}
{"repo":"sinatra","file":"lib/sinatra/middleware/logger.rb","line":12,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n logger = ::Logger.new(env[Rack::RACK_ERRORS])\n logger.level = @level\n\n env[Rack::RACK_LOGGER] = logger\n @app.call(env)\n end"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # Sinatra::ShowExceptions catches all exceptions raised from the app it\n # wraps. It shows a useful backtrace with the sourcefile and clickable\n # context, the whole Rack environment and the request data.\n #\n # Be careful when you use this on public-facing sites as it could reveal\n # information helpful to attackers.\n class ShowExceptions < Rack::ShowExceptions\n @@eats_errors = Object.new\n def @@eats_errors.flush(*) end\n\n def @@eats_errors.puts(*) end\n\n def initialize(app)\n @app = app\n end\n\n def call(env)\n @app.call(env)\n rescue Exception => e\n errors = env['rack.errors']\n env['rack.errors'] = @@eats_errors\n\n if prefers_plain_text?(env)\n content_type = 'text/plain'\n body = dump_exception(e)\n else\n content_type = 'text/html'\n body = pretty(env, e)\n end\n\n env['rack.errors'] = errors\n\n [\n 500,\n {\n 'content-type' => content_type,\n 'content-length' => body.bytesize.to_s\n },\n [body]\n ]\n end\n\n def template\n TEMPLATE\n end\n\n private\n\n def bad_request?(exception)\n Sinatra::BadRequest === exception\n "}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":12,"symbol":"ShowExceptions","kind":"class","lang":"ruby","doc":"Sinatra::ShowExceptions catches all exceptions raised from the app it wraps. It shows a useful backtrace with the sourcefile and clickable context, the whole Rack environment and the request data. Be careful when you use this on public-facing sites as it could reveal information helpful to attackers.","code":"class ShowExceptions < Rack::ShowExceptions\n @@eats_errors = Object.new\n def @@eats_errors.flush(*) end\n\n def @@eats_errors.puts(*) end\n\n def initialize(app)\n @app = app\n end\n\n def call(env)\n @app.call(env)\n rescue Exception => e\n errors = env['rack.errors']\n env['rack.errors'] = @@eats_errors\n\n if prefers_plain_text?(env)\n content_type = 'text/plain'\n body = dump_exception(e)\n else\n content_type = 'text/html'\n body = pretty(env, e)\n end\n\n env['rack.errors'] = errors\n\n [\n 500,\n {\n 'content-type' => content_type,\n 'content-length' => body.bytesize.to_s\n },\n [body]\n ]\n end\n\n def template\n TEMPLATE\n end\n\n private\n\n def bad_request?(exception)\n Sinatra::BadRequest === exception\n end\n\n def prefers_plain_text?(env)\n Request.new(env).preferred_type('text/plain', 'text/html') != 'text/html' &&\n [/curl/].index { |item| item =~ env['HTTP_USER_AGENT'] }\n end\n\n def frame_class(frame)\n if frame.filename =~ %r{lib/sinatra.*\\.rb}\n 'framework'\n elsif (defined?(Gem) && frame.filename.include"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":14,"symbol":"flush","kind":"method","lang":"ruby","code":"def @@eats_errors.flush(*) end"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":16,"symbol":"puts","kind":"method","lang":"ruby","code":"def @@eats_errors.puts(*) end"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":18,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app)\n @app = app\n end"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":22,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n @app.call(env)\n rescue Exception => e\n errors = env['rack.errors']\n env['rack.errors'] = @@eats_errors\n\n if prefers_plain_text?(env)\n content_type = 'text/plain'\n body = dump_exception(e)\n else\n content_type = 'text/html'\n body = pretty(env, e)\n end\n\n env['rack.errors'] = errors\n\n [\n 500,\n {\n 'content-type' => content_type,\n 'content-length' => body.bytesize.to_s\n },\n [body]\n ]\n end"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":48,"symbol":"template","kind":"method","lang":"ruby","code":"def template\n TEMPLATE\n end"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":54,"symbol":"bad_request?","kind":"method","lang":"ruby","code":"def bad_request?(exception)\n Sinatra::BadRequest === exception\n end"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":58,"symbol":"prefers_plain_text?","kind":"method","lang":"ruby","code":"def prefers_plain_text?(env)\n Request.new(env).preferred_type('text/plain', 'text/html') != 'text/html' &&\n [/curl/].index { |item| item =~ env['HTTP_USER_AGENT'] }\n end"}
{"repo":"sinatra","file":"lib/sinatra/show_exceptions.rb","line":63,"symbol":"frame_class","kind":"method","lang":"ruby","code":"def frame_class(frame)\n if frame.filename =~ %r{lib/sinatra.*\\.rb}\n 'framework'\n elsif (defined?(Gem) && frame.filename.include?(Gem.dir)) ||\n frame.filename =~ %r{/bin/(\\w+)\\z}\n 'system'\n else\n 'app'\n end\n end"}
{"repo":"sinatra","file":"lib/sinatra/version.rb","line":3,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n VERSION = '4.2.1'\nend"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":8,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery\n #\n # This middleware only accepts requests other than <tt>GET</tt>,\n # <tt>HEAD</tt>, <tt>OPTIONS</tt>, <tt>TRACE</tt> if their given access\n # token matches the token included in the session.\n #\n # It checks the <tt>X-CSRF-Token</tt> header and the <tt>POST</tt> form\n # data.\n #\n # It is not OOTB-compatible with the {rack-csrf}[https://rubygems.org/gems/rack_csrf] gem.\n # For that, the following patch needs to be applied:\n #\n # Rack::Protection::AuthenticityToken.default_options(key: \"csrf.token\", authenticity_param: \"_csrf\")\n #\n # == Options\n #\n # [<tt>:authenticity_param</tt>] the name of the param that should contain\n # the token on a request. Default value:\n # <tt>\"authenticity_token\"</tt>\n #\n # [<tt>:key</tt>] the name of the param that should contain\n # the token in the session. Default value: <tt>:csrf</tt>\n #\n # [<tt>:allow_if</tt>] a proc for "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":9,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery\n #\n # This middleware only accepts requests other than <tt>GET</tt>,\n # <tt>HEAD</tt>, <tt>OPTIONS</tt>, <tt>TRACE</tt> if their given access\n # token matches the token included in the session.\n #\n # It checks the <tt>X-CSRF-Token</tt> header and the <tt>POST</tt> form\n # data.\n #\n # It is not OOTB-compatible with the {rack-csrf}[https://rubygems.org/gems/rack_csrf] gem.\n # For that, the following patch needs to be applied:\n #\n # Rack::Protection::AuthenticityToken.default_options(key: \"csrf.token\", authenticity_param: \"_csrf\")\n #\n # == Options\n #\n # [<tt>:authenticity_param</tt>] the name of the param that should contain\n # the token on a request. Default value:\n # <tt>\"authenticity_token\"</tt>\n #\n # [<tt>:key</tt>] the name of the param that should contain\n # the token in the session. Default value: <tt>:csrf</tt>\n #\n # [<tt>:allow_if</tt>] a proc for custom allow/d"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":102,"symbol":"AuthenticityToken","kind":"class","lang":"ruby","doc":"== Example: Customize which POST parameter holds the token To customize the authenticity parameter for form data, use the <tt>:authenticity_param</tt> option: use Rack::Protection::AuthenticityToken, authenticity_param: 'your_token_param_name'","code":"class AuthenticityToken < Base\n TOKEN_LENGTH = 32\n\n default_options authenticity_param: 'authenticity_token',\n key: :csrf,\n allow_if: nil\n\n # Access the token from the given session. Useful for building a\n # form that should include the current authenticity token.\n def self.token(session, path: nil, method: :post)\n new(nil).mask_authenticity_token(session, path: path, method: method)\n end\n\n def self.random_token\n SecureRandom.urlsafe_base64(TOKEN_LENGTH, padding: false)\n end\n\n def accepts?(env)\n session = session(env)\n set_token(session)\n\n safe?(env) ||\n valid_token?(env, env['HTTP_X_CSRF_TOKEN']) ||\n valid_token?(env, Request.new(env).params[options[:authenticity_param]]) ||\n options[:allow_if]&.call(env)\n rescue StandardError\n false\n end\n\n def mask_authenticity_token(session, path: nil, method: :post)\n set_token(session)\n\n token = if path && method\n per_form_token(session, path, method)\n else\n global_token(session)\n end\n\n mask_"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":111,"symbol":"token","kind":"method","lang":"ruby","doc":"Access the token from the given session. Useful for building a form that should include the current authenticity token.","code":"def self.token(session, path: nil, method: :post)\n new(nil).mask_authenticity_token(session, path: path, method: method)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":115,"symbol":"random_token","kind":"method","lang":"ruby","code":"def self.random_token\n SecureRandom.urlsafe_base64(TOKEN_LENGTH, padding: false)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":119,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n session = session(env)\n set_token(session)\n\n safe?(env) ||\n valid_token?(env, env['HTTP_X_CSRF_TOKEN']) ||\n valid_token?(env, Request.new(env).params[options[:authenticity_param]]) ||\n options[:allow_if]&.call(env)\n rescue StandardError\n false\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":131,"symbol":"mask_authenticity_token","kind":"method","lang":"ruby","code":"def mask_authenticity_token(session, path: nil, method: :post)\n set_token(session)\n\n token = if path && method\n per_form_token(session, path, method)\n else\n global_token(session)\n end\n\n mask_token(token)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":148,"symbol":"set_token","kind":"method","lang":"ruby","code":"def set_token(session)\n session[options[:key]] ||= self.class.random_token\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":154,"symbol":"valid_token?","kind":"method","lang":"ruby","doc":"Checks the client's masked token to see if it matches the session token.","code":"def valid_token?(env, token)\n return false if token.nil? || !token.is_a?(String) || token.empty?\n\n session = session(env)\n\n begin\n token = decode_token(token)\n rescue ArgumentError # encoded_masked_token is invalid Base64\n return false\n end\n\n # See if it's actually a masked token or not. We should be able\n # to handle any unmasked tokens that we've issued without error.\n\n if unmasked_token?(token)\n compare_with_real_token(token, session)\n elsif masked_token?(token)\n token = unmask_token(token)\n\n compare_with_global_token(token, session) ||\n compare_with_real_token(token, session) ||\n compare_with_per_form_token(token, session, Request.new(env))\n else\n false # Token is malformed\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":184,"symbol":"mask_token","kind":"method","lang":"ruby","doc":"Creates a masked version of the authenticity token that varies on each request. The masking is used to mitigate SSL attacks like BREACH.","code":"def mask_token(token)\n one_time_pad = SecureRandom.random_bytes(token.length)\n encrypted_token = xor_byte_strings(one_time_pad, token)\n masked_token = one_time_pad + encrypted_token\n encode_token(masked_token)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":192,"symbol":"unmask_token","kind":"method","lang":"ruby","doc":"Essentially the inverse of +mask_token+.","code":"def unmask_token(masked_token)\n # Split the token into the one-time pad and the encrypted\n # value and decrypt it\n token_length = masked_token.length / 2\n one_time_pad = masked_token[0...token_length]\n encrypted_token = masked_token[token_length..]\n xor_byte_strings(one_time_pad, encrypted_token)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":201,"symbol":"unmasked_token?","kind":"method","lang":"ruby","code":"def unmasked_token?(token)\n token.length == TOKEN_LENGTH\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":205,"symbol":"masked_token?","kind":"method","lang":"ruby","code":"def masked_token?(token)\n token.length == TOKEN_LENGTH * 2\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":209,"symbol":"compare_with_real_token","kind":"method","lang":"ruby","code":"def compare_with_real_token(token, session)\n secure_compare(token, real_token(session))\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":213,"symbol":"compare_with_global_token","kind":"method","lang":"ruby","code":"def compare_with_global_token(token, session)\n secure_compare(token, global_token(session))\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":217,"symbol":"compare_with_per_form_token","kind":"method","lang":"ruby","code":"def compare_with_per_form_token(token, session, request)\n secure_compare(token,\n per_form_token(session, request.path.chomp('/'), request.request_method))\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":222,"symbol":"real_token","kind":"method","lang":"ruby","code":"def real_token(session)\n decode_token(session[options[:key]])\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":226,"symbol":"global_token","kind":"method","lang":"ruby","code":"def global_token(session)\n token_hmac(session, GLOBAL_TOKEN_IDENTIFIER)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":230,"symbol":"per_form_token","kind":"method","lang":"ruby","code":"def per_form_token(session, path, method)\n token_hmac(session, \"#{path}##{method.downcase}\")\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":234,"symbol":"encode_token","kind":"method","lang":"ruby","code":"def encode_token(token)\n Base64.urlsafe_encode64(token)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":238,"symbol":"decode_token","kind":"method","lang":"ruby","code":"def decode_token(token)\n Base64.urlsafe_decode64(token)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":242,"symbol":"token_hmac","kind":"method","lang":"ruby","code":"def token_hmac(session, identifier)\n OpenSSL::HMAC.digest(\n OpenSSL::Digest.new('SHA256'),\n real_token(session),\n identifier\n )\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/authenticity_token.rb","line":250,"symbol":"xor_byte_strings","kind":"method","lang":"ruby","code":"def xor_byte_strings(s1, s2)\n s2 = s2.dup\n size = s1.bytesize\n i = 0\n while i < size\n s2.setbyte(i, s1.getbyte(i) ^ s2.getbyte(i))\n i += 1\n end\n s2\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":9,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Base class for middlewares provided by rack-protection.\n #\n # == Options\n #\n # These may be given to any subclass, however they may affect different subclasses differently.\n #\n # [<tt>:reaction</tt>] - name of a method of the class that will be used to respond when the\n # middleware rejects the response. Default behavior is to use #default_reaction.\n # [<tt>:logging</tt>] - if true, debug and warning statements are sent to the logger.\n # [<tt>:message</tt>] - if set, this is the message sent when a request is rejected via <tt>deny</tt>.\n # See DEFAULT_OPTIONS.\n # [<tt>:session_key</tt>] - string to use as the key into <tt>env</tt> where the current\n # session is stored. See DEFAULT_OPTIONS.\n # [<tt>:status</tt>] - HTTP status to use when a request is rejected via <tt>deny</tt>.\n # See DEFAULT_OPTIONS.\n # [<tt>:report_key</tt>] - key set in <tt>env</tt> if the request has been denied\n # and <tt>:reaction</tt> is set to <tt>:report</tt> (see #report). See DEFAULT_OPTIONS.\n #"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":10,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Base class for middlewares provided by rack-protection.\n #\n # == Options\n #\n # These may be given to any subclass, however they may affect different subclasses differently.\n #\n # [<tt>:reaction</tt>] - name of a method of the class that will be used to respond when the\n # middleware rejects the response. Default behavior is to use #default_reaction.\n # [<tt>:logging</tt>] - if true, debug and warning statements are sent to the logger.\n # [<tt>:message</tt>] - if set, this is the message sent when a request is rejected via <tt>deny</tt>.\n # See DEFAULT_OPTIONS.\n # [<tt>:session_key</tt>] - string to use as the key into <tt>env</tt> where the current\n # session is stored. See DEFAULT_OPTIONS.\n # [<tt>:status</tt>] - HTTP status to use when a request is rejected via <tt>deny</tt>.\n # See DEFAULT_OPTIONS.\n # [<tt>:report_key</tt>] - key set in <tt>env</tt> if the request has been denied\n # and <tt>:reaction</tt> is set to <tt>:report</tt> (see #report). See DEFAULT_OPTIONS.\n # [<tt>:html_ty"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":32,"symbol":"Base","kind":"class","lang":"ruby","doc":"See DEFAULT_OPTIONS. [<tt>:report_key</tt>] - key set in <tt>env</tt> if the request has been denied and <tt>:reaction</tt> is set to <tt>:report</tt> (see #report). See DEFAULT_OPTIONS. [<tt>:html_types</tt>] - Array of strings containing content types that are consider HTML for the purposes of this gem. See DEFAULT_OPTIONS.","code":"class Base\n DEFAULT_OPTIONS = {\n reaction: :default_reaction, logging: true,\n message: 'Forbidden', encryptor: Digest::SHA1,\n session_key: 'rack.session', status: 403,\n allow_empty_referrer: true,\n report_key: 'protection.failed',\n html_types: %w[text/html application/xhtml text/xml application/xml]\n }\n\n attr_reader :app, :options\n\n # Used by subclasses to declare default values for options they require.\n # These defaults are merged onto the DEFAULT_OPTIONS provided by this class.\n def self.default_options(options)\n define_method(:default_options) { super().merge(options) }\n end\n\n # Used by subclasses to declare default reaction when a request is rejected.\n # This replaces the default provided by this class.\n # See #default_reaction.\n def self.default_reaction(reaction)\n alias_method(:default_reaction, reaction)\n end\n\n def default_options\n DEFAULT_OPTIONS\n end\n\n def initialize(app, options = {})\n @app = app\n @options = default_options.merge(options)\n end\n\n def safe?(env)\n %w[GET HEAD OPTIONS TRACE].include? env['REQ"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":46,"symbol":"default_options","kind":"method","lang":"ruby","doc":"Used by subclasses to declare default values for options they require. These defaults are merged onto the DEFAULT_OPTIONS provided by this class.","code":"def self.default_options(options)\n define_method(:default_options) { super().merge(options) }\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":53,"symbol":"default_reaction","kind":"method","lang":"ruby","doc":"Used by subclasses to declare default reaction when a request is rejected. This replaces the default provided by this class. See #default_reaction.","code":"def self.default_reaction(reaction)\n alias_method(:default_reaction, reaction)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":57,"symbol":"default_options","kind":"method","lang":"ruby","code":"def default_options\n DEFAULT_OPTIONS\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":61,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app, options = {})\n @app = app\n @options = default_options.merge(options)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":66,"symbol":"safe?","kind":"method","lang":"ruby","code":"def safe?(env)\n %w[GET HEAD OPTIONS TRACE].include? env['REQUEST_METHOD']\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":70,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n raise NotImplementedError, \"#{self.class} implementation pending\"\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":74,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n unless accepts? env\n instrument env\n result = react env\n end\n result or app.call(env)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":82,"symbol":"react","kind":"method","lang":"ruby","code":"def react(env)\n result = send(options[:reaction], env)\n result if (Array === result) && (result.size == 3)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":87,"symbol":"debug","kind":"method","lang":"ruby","code":"def debug(env, message)\n return unless options[:logging]\n\n l = options[:logger] || env['rack.logger'] || ::Logger.new(env['rack.errors'])\n l.debug(message)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":94,"symbol":"warn","kind":"method","lang":"ruby","code":"def warn(env, message)\n return unless options[:logging]\n\n l = options[:logger] || env['rack.logger'] || ::Logger.new(env['rack.errors'])\n l.warn(message)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":101,"symbol":"instrument","kind":"method","lang":"ruby","code":"def instrument(env)\n return unless (i = options[:instrumenter])\n\n env['rack.protection.attack'] = self.class.name.split('::').last.downcase\n i.instrument('rack.protection', env)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":110,"symbol":"deny","kind":"method","lang":"ruby","doc":"Deny the request. Sends a content type of \"text/plain\" using the status and message set in the options.","code":"def deny(env)\n warn env, \"attack prevented by #{self.class}\"\n [options[:status], { 'content-type' => 'text/plain' }, [options[:message]]]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":119,"symbol":"report","kind":"method","lang":"ruby","doc":"When used as a reaction (with option <tt>reaction: :report</tt>), any rejected request will be allowed through, and a warning is omitted (note that warnings will not be shown if the <tt>:logging</tt> option has been set to false).","code":"def report(env)\n warn env, \"attack reported by #{self.class}\"\n env[options[:report_key]] = true\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":124,"symbol":"session?","kind":"method","lang":"ruby","code":"def session?(env)\n env.include? options[:session_key]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":128,"symbol":"session","kind":"method","lang":"ruby","code":"def session(env)\n return env[options[:session_key]] if session? env\n\n raise \"you need to set up a session middleware *before* #{self.class}\"\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":134,"symbol":"drop_session","kind":"method","lang":"ruby","code":"def drop_session(env)\n return unless session? env\n\n session(env).clear\n\n return if [\"1\", \"true\"].include?(ENV[\"RACK_PROTECTION_SILENCE_DROP_SESSION_WARNING\"])\n\n warn env, \"session dropped by #{self.class}\"\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":144,"symbol":"referrer","kind":"method","lang":"ruby","code":"def referrer(env)\n ref = env['HTTP_REFERER'].to_s\n return if !options[:allow_empty_referrer] && ref.empty?\n\n URI.parse(ref).host || Request.new(env).host\n rescue URI::InvalidURIError\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":152,"symbol":"origin","kind":"method","lang":"ruby","code":"def origin(env)\n env['HTTP_ORIGIN'] || env['HTTP_X_ORIGIN']\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":156,"symbol":"random_string","kind":"method","lang":"ruby","code":"def random_string(secure = defined? SecureRandom)\n secure ? SecureRandom.hex(16) : '%032x' % rand((2**128) - 1)\n rescue NotImplementedError\n random_string false\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":162,"symbol":"encrypt","kind":"method","lang":"ruby","code":"def encrypt(value)\n options[:encryptor].hexdigest value.to_s\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":166,"symbol":"secure_compare","kind":"method","lang":"ruby","code":"def secure_compare(a, b)\n Rack::Utils.secure_compare(a.to_s, b.to_s)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/base.rb","line":172,"symbol":"html?","kind":"method","lang":"ruby","code":"def html?(headers)\n return false unless (header = headers.detect { |k, _v| k.downcase == 'content-type' })\n\n options[:html_types].include? header.last[%r{^\\w+/\\w+}]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/content_security_policy.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: XSS and others\n # Supported browsers:: Firefox 23+, Safari 7+, Chrome 25+, Opera 15+\n #\n # Sets the 'content-security-policy' or the 'content-security-policy-report-only' header, based on options provided.\n #\n # Description:: Content Security Policy, is a mechanism web applications\n # can use to mitigate a broad class of content injection\n # vulnerabilities, such as cross-site scripting (XSS).\n # Content Security Policy is a declarative policy that lets\n # the authors (or server administrators) of a web application\n # inform the client about the sources from which the\n # application expects to load resources.\n #\n # More info:: * W3C CSP Level 1 : https://www.w3.org/TR/CSP1/ (deprecated)\n # * W3C CSP Level 2 : https://www.w3.org/TR/CSP2/ (current)\n # * W3C CSP Level 3 : https://www.w3.org/TR/CSP3/ (draft)\n # * https://developer.mozilla.org/en-US/docs/Web/Security/CSP\n # * http://caniuse.com/#search=ContentSecurityPolicy\n # "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/content_security_policy.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: XSS and others\n # Supported browsers:: Firefox 23+, Safari 7+, Chrome 25+, Opera 15+\n #\n # Sets the 'content-security-policy' or the 'content-security-policy-report-only' header, based on options provided.\n #\n # Description:: Content Security Policy, is a mechanism web applications\n # can use to mitigate a broad class of content injection\n # vulnerabilities, such as cross-site scripting (XSS).\n # Content Security Policy is a declarative policy that lets\n # the authors (or server administrators) of a web application\n # inform the client about the sources from which the\n # application expects to load resources.\n #\n # More info:: * W3C CSP Level 1 : https://www.w3.org/TR/CSP1/ (deprecated)\n # * W3C CSP Level 2 : https://www.w3.org/TR/CSP2/ (current)\n # * W3C CSP Level 3 : https://www.w3.org/TR/CSP3/ (draft)\n # * https://developer.mozilla.org/en-US/docs/Web/Security/CSP\n # * http://caniuse.com/#search=ContentSecurityPolicy\n # * "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/content_security_policy.rb","line":65,"symbol":"ContentSecurityPolicy","kind":"class","lang":"ruby","doc":"value to <tt>true</tt> to ensure they are set. See NO_ARG_DIRECTIVES. Note that <tt>'self'</tt> and <tt>'none'</tt> require single quotes and this middleware will not add them. For example, to disallow <tt>iframe</tt>s, you would need to use <tt>frame_src: \"'none'\"</tt>.","code":"class ContentSecurityPolicy < Base\n default_options default_src: \"'self'\", report_only: false\n\n DIRECTIVES = %i[base_uri child_src connect_src default_src\n font_src form_action frame_ancestors frame_src\n img_src manifest_src media_src object_src\n plugin_types referrer reflected_xss report_to\n report_uri require_sri_for sandbox script_src\n style_src worker_src webrtc_src navigate_to\n prefetch_src].freeze\n\n NO_ARG_DIRECTIVES = %i[block_all_mixed_content disown_opener\n upgrade_insecure_requests].freeze\n\n def csp_policy\n directives = []\n\n DIRECTIVES.each do |d|\n if options.key?(d)\n directives << \"#{d.to_s.sub(/_/, '-')} #{options[d]}\"\n end\n end\n\n # Set these key values to boolean 'true' to include in policy\n NO_ARG_DIRECTIVES.each do |d|\n if options.key?(d) && options[d].is_a?(TrueClass)\n directives << d.to_s.tr('_', '-')\n end\n end\n\n directives.compact.sort.join('; ')\n end\n\n def call(env)\n sta"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/content_security_policy.rb","line":79,"symbol":"csp_policy","kind":"method","lang":"ruby","code":"def csp_policy\n directives = []\n\n DIRECTIVES.each do |d|\n if options.key?(d)\n directives << \"#{d.to_s.sub(/_/, '-')} #{options[d]}\"\n end\n end\n\n # Set these key values to boolean 'true' to include in policy\n NO_ARG_DIRECTIVES.each do |d|\n if options.key?(d) && options[d].is_a?(TrueClass)\n directives << d.to_s.tr('_', '-')\n end\n end\n\n directives.compact.sort.join('; ')\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/content_security_policy.rb","line":98,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n header = options[:report_only] ? 'content-security-policy-report-only' : 'content-security-policy'\n headers[header] ||= csp_policy if html? headers\n [status, headers, body]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":6,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: Cookie Tossing\n # Supported browsers:: all\n # More infos:: https://github.com/blog/1466-yummy-cookies-across-domains\n #\n # Does not accept HTTP requests if the\n # {Cookie header}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cookie] \n # contains more than one session cookie. This does not protect against a cookie overflow attack.\n #\n # == Options\n #\n # [<tt>:session_key</tt>] The name of the session cookie (default: 'rack.session')\n #\n # [Rack::Protection::Base options] any option supported by Rack::Protection::Base.\n #\n # == Example: Default session key\n #\n # use Rack::Protection::CookieTossing\n #\n # == Example: Custom session key\n #\n # use Rack::Session::Cookie, key: \"custom.session\"\n # use Rack::Protection::CookieTossing, session_key: \"custom.session\"\n class CookieTossing < Base\n default_reaction :deny\n\n def call(env)\n status, headers, body = super\n response = Rack::Response.new(body, status, headers)\n request = Rack::Request.new(env)\n remove_bad_cookies(request, response)\n "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":7,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: Cookie Tossing\n # Supported browsers:: all\n # More infos:: https://github.com/blog/1466-yummy-cookies-across-domains\n #\n # Does not accept HTTP requests if the\n # {Cookie header}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cookie] \n # contains more than one session cookie. This does not protect against a cookie overflow attack.\n #\n # == Options\n #\n # [<tt>:session_key</tt>] The name of the session cookie (default: 'rack.session')\n #\n # [Rack::Protection::Base options] any option supported by Rack::Protection::Base.\n #\n # == Example: Default session key\n #\n # use Rack::Protection::CookieTossing\n #\n # == Example: Custom session key\n #\n # use Rack::Session::Cookie, key: \"custom.session\"\n # use Rack::Protection::CookieTossing, session_key: \"custom.session\"\n class CookieTossing < Base\n default_reaction :deny\n\n def call(env)\n status, headers, body = super\n response = Rack::Response.new(body, status, headers)\n request = Rack::Request.new(env)\n remove_bad_cookies(request, response)\n response."}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":31,"symbol":"CookieTossing","kind":"class","lang":"ruby","doc":"use Rack::Protection::CookieTossing == Example: Custom session key use Rack::Session::Cookie, key: \"custom.session\" use Rack::Protection::CookieTossing, session_key: \"custom.session\"","code":"class CookieTossing < Base\n default_reaction :deny\n\n def call(env)\n status, headers, body = super\n response = Rack::Response.new(body, status, headers)\n request = Rack::Request.new(env)\n remove_bad_cookies(request, response)\n response.finish\n end\n\n def accepts?(env)\n cookie_header = env['HTTP_COOKIE']\n cookies = Rack::Utils.parse_query(cookie_header, ';,') { |s| s }\n cookies.each do |k, v|\n if (k == session_key && Array(v).size > 1) ||\n (k != session_key && Rack::Utils.unescape(k) == session_key)\n bad_cookies << k\n end\n end\n bad_cookies.empty?\n end\n\n def remove_bad_cookies(request, response)\n return if bad_cookies.empty?\n\n paths = cookie_paths(request.path)\n bad_cookies.each do |name|\n paths.each { |path| response.set_cookie name, empty_cookie(request.host, path) }\n end\n end\n\n def redirect(env)\n request = Request.new(env)\n warn env, \"attack prevented by #{self.class}\"\n [302, { 'content-type' => 'text/html', 'location' => request.path }, []]\n end\n\n def bad_cookies\n "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":34,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = super\n response = Rack::Response.new(body, status, headers)\n request = Rack::Request.new(env)\n remove_bad_cookies(request, response)\n response.finish\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":42,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n cookie_header = env['HTTP_COOKIE']\n cookies = Rack::Utils.parse_query(cookie_header, ';,') { |s| s }\n cookies.each do |k, v|\n if (k == session_key && Array(v).size > 1) ||\n (k != session_key && Rack::Utils.unescape(k) == session_key)\n bad_cookies << k\n end\n end\n bad_cookies.empty?\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":54,"symbol":"remove_bad_cookies","kind":"method","lang":"ruby","code":"def remove_bad_cookies(request, response)\n return if bad_cookies.empty?\n\n paths = cookie_paths(request.path)\n bad_cookies.each do |name|\n paths.each { |path| response.set_cookie name, empty_cookie(request.host, path) }\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":63,"symbol":"redirect","kind":"method","lang":"ruby","code":"def redirect(env)\n request = Request.new(env)\n warn env, \"attack prevented by #{self.class}\"\n [302, { 'content-type' => 'text/html', 'location' => request.path }, []]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":69,"symbol":"bad_cookies","kind":"method","lang":"ruby","code":"def bad_cookies\n @bad_cookies ||= []\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":73,"symbol":"cookie_paths","kind":"method","lang":"ruby","code":"def cookie_paths(path)\n path = '/' if path.to_s.empty?\n paths = []\n Pathname.new(path).descend { |p| paths << p.to_s }\n paths\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":80,"symbol":"empty_cookie","kind":"method","lang":"ruby","code":"def empty_cookie(host, path)\n { value: '', domain: host, path: path, expires: Time.at(0) }\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/cookie_tossing.rb","line":84,"symbol":"session_key","kind":"method","lang":"ruby","code":"def session_key\n @session_key ||= options[:session_key]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":12,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: XSS\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_scripting\n #\n # Automatically escapes <tt>Rack::Request#params</tt> so they can be embedded in HTML\n # or JavaScript without any further issues.\n #\n # == Options\n #\n # [<tt>:escape</tt>] What escaping modes to use. Should be Symbol or Array of Symbols of one of the following:\n # <tt>:html</tt>:: escape HTML\n # <tt>:url</tt>:: escape URLs\n # <tt>:javascript</tt>:: escape JavaScript (requires the <tt>escape_utils</tt>\n # gem or a custom <tt>:escaper</tt>).\n #\n # Default is <tt>:html</tt>.\n #\n # [<tt>:escaper</tt>] Object to use for escaping. It must respond to the following methods:\n # <tt>#escape_url</tt>:: if <tt>:escape</tt> is or contains <tt>:url</tt>\n # <tt>#escape_html</tt>:: if <tt>:escape</tt> is or contains <tt>:html</tt>\n # <tt>#escape_javascript</tt>:: if <tt>:escape</tt> is or c"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":13,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: XSS\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_scripting\n #\n # Automatically escapes <tt>Rack::Request#params</tt> so they can be embedded in HTML\n # or JavaScript without any further issues.\n #\n # == Options\n #\n # [<tt>:escape</tt>] What escaping modes to use. Should be Symbol or Array of Symbols of one of the following:\n # <tt>:html</tt>:: escape HTML\n # <tt>:url</tt>:: escape URLs\n # <tt>:javascript</tt>:: escape JavaScript (requires the <tt>escape_utils</tt>\n # gem or a custom <tt>:escaper</tt>).\n #\n # Default is <tt>:html</tt>.\n #\n # [<tt>:escaper</tt>] Object to use for escaping. It must respond to the following methods:\n # <tt>#escape_url</tt>:: if <tt>:escape</tt> is or contains <tt>:url</tt>\n # <tt>#escape_html</tt>:: if <tt>:escape</tt> is or contains <tt>:html</tt>\n # <tt>#escape_javascript</tt>:: if <tt>:escape</tt> is or contains <tt>:j"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":70,"symbol":"EscapedParams","kind":"class","lang":"ruby","doc":"# your custom code here end end use Rack::Protection::EscapedParams, escape: [:html, :url, :javascript], escaper: MyEscaper","code":"class EscapedParams < Base\n extend Rack::Utils\n\n class << self\n alias escape_url escape\n public :escape_html\n end\n\n default_options escape: :html,\n escaper: defined?(EscapeUtils) ? EscapeUtils : self\n\n def initialize(*)\n super\n\n modes = Array options[:escape]\n @escaper = options[:escaper]\n @html = modes.include? :html\n @javascript = modes.include? :javascript\n @url = modes.include? :url\n\n return unless @javascript && (!@escaper.respond_to? :escape_javascript)\n\n raise('Use EscapeUtils for JavaScript escaping.')\n end\n\n def call(env)\n request = Request.new(env)\n get_was = handle(request.GET)\n post_was = begin\n handle(request.POST)\n rescue StandardError\n nil\n end\n app.call env\n ensure\n request.GET.replace get_was if get_was\n request.POST.replace post_was if post_was\n end\n\n def handle(hash)\n was = hash.dup\n hash.replace escape(hash)\n was\n end\n\n def escape(object)\n case object\n when Hash then escape_hash("}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":81,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(*)\n super\n\n modes = Array options[:escape]\n @escaper = options[:escaper]\n @html = modes.include? :html\n @javascript = modes.include? :javascript\n @url = modes.include? :url\n\n return unless @javascript && (!@escaper.respond_to? :escape_javascript)\n\n raise('Use EscapeUtils for JavaScript escaping.')\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":95,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n request = Request.new(env)\n get_was = handle(request.GET)\n post_was = begin\n handle(request.POST)\n rescue StandardError\n nil\n end\n app.call env\n ensure\n request.GET.replace get_was if get_was\n request.POST.replace post_was if post_was\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":109,"symbol":"handle","kind":"method","lang":"ruby","code":"def handle(hash)\n was = hash.dup\n hash.replace escape(hash)\n was\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":115,"symbol":"escape","kind":"method","lang":"ruby","code":"def escape(object)\n case object\n when Hash then escape_hash(object)\n when Array then object.map { |o| escape(o) }\n when String then escape_string(object)\n when Tempfile then object\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":124,"symbol":"escape_hash","kind":"method","lang":"ruby","code":"def escape_hash(hash)\n hash = hash.dup\n hash.each { |k, v| hash[k] = escape(v) }\n hash\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/escaped_params.rb","line":130,"symbol":"escape_string","kind":"method","lang":"ruby","code":"def escape_string(str)\n str = @escaper.escape_url(str) if @url\n str = @escaper.escape_html(str) if @html\n str = @escaper.escape_javascript(str) if @javascript\n str\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/form_token.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery\n #\n # Only accepts submitted forms if a given access token matches the token\n # included in the session. Does not expect such a token from Ajax request.\n #\n # This middleware is not used when using the Rack::Protection collection,\n # since it might be a security issue, depending on your application\n #\n # Compatible with rack-csrf.\n class FormToken < AuthenticityToken\n def accepts?(env)\n env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' or super\n end\n end\n end\nend"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/form_token.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery\n #\n # Only accepts submitted forms if a given access token matches the token\n # included in the session. Does not expect such a token from Ajax request.\n #\n # This middleware is not used when using the Rack::Protection collection,\n # since it might be a security issue, depending on your application\n #\n # Compatible with rack-csrf.\n class FormToken < AuthenticityToken\n def accepts?(env)\n env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' or super\n end\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/form_token.rb","line":19,"symbol":"FormToken","kind":"class","lang":"ruby","doc":"included in the session. Does not expect such a token from Ajax request. This middleware is not used when using the Rack::Protection collection, since it might be a security issue, depending on your application Compatible with rack-csrf.","code":"class FormToken < AuthenticityToken\n def accepts?(env)\n env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' or super\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/form_token.rb","line":20,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' or super\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/frame_options.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: Clickjacking\n # Supported browsers:: * Chrome 26 and later\n # * Edge 12 and later\n # * Safari 5.1 and later\n # * Mobile Safari 7 and later\n # * Firefox 4 and later\n # * Internet Explorer 8 and later\n # * See full details at https://caniuse.com/mdn-http_headers_content-security-policy_frame-ancestors\n # More info:: * https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Frame-Options\n # * https://caniuse.com/x-frame-options\n #\n # Sets X-Frame-Options header to tell the browser avoid embedding the page\n # in a frame. Note that in modern browsers, the preferred approach is to use the\n # {frame-ancestors directive}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/frame-ancestors]\n # in your content security policy.\n #\n # Notes:\n #\n # * This middleware won't do anything for non-HTML responses.\n # * If your app sets <tt>X-Frame-Options</tt> header, this mi"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/frame_options.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: Clickjacking\n # Supported browsers:: * Chrome 26 and later\n # * Edge 12 and later\n # * Safari 5.1 and later\n # * Mobile Safari 7 and later\n # * Firefox 4 and later\n # * Internet Explorer 8 and later\n # * See full details at https://caniuse.com/mdn-http_headers_content-security-policy_frame-ancestors\n # More info:: * https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Frame-Options\n # * https://caniuse.com/x-frame-options\n #\n # Sets X-Frame-Options header to tell the browser avoid embedding the page\n # in a frame. Note that in modern browsers, the preferred approach is to use the\n # {frame-ancestors directive}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/frame-ancestors]\n # in your content security policy.\n #\n # Notes:\n #\n # * This middleware won't do anything for non-HTML responses.\n # * If your app sets <tt>X-Frame-Options</tt> header, this middleware will "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/frame_options.rb","line":49,"symbol":"FrameOptions","kind":"class","lang":"ruby","doc":"use Rack::Protection::FrameOptions == Example: Deny embedding # Embedding is not allowed use Rack::Protection::FrameOptions, frame_options: :deny","code":"class FrameOptions < Base\n default_options frame_options: :sameorigin\n\n def frame_options\n @frame_options ||= begin\n frame_options = options[:frame_options]\n frame_options = options[:frame_options].to_s.upcase unless frame_options.respond_to? :to_str\n frame_options.to_str\n end\n end\n\n def call(env)\n status, headers, body = @app.call(env)\n headers['x-frame-options'] ||= frame_options if html? headers\n [status, headers, body]\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/frame_options.rb","line":52,"symbol":"frame_options","kind":"method","lang":"ruby","code":"def frame_options\n @frame_options ||= begin\n frame_options = options[:frame_options]\n frame_options = options[:frame_options].to_s.upcase unless frame_options.respond_to? :to_str\n frame_options.to_str\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/frame_options.rb","line":60,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n headers['x-frame-options'] ||= frame_options if html? headers\n [status, headers, body]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":6,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: DNS rebinding and other Host header attacks\n # Supported browsers:: all\n # More info:: * https://en.wikipedia.org/wiki/DNS_rebinding\n # * https://portswigger.net/web-security/host-header\n #\n # Blocks HTTP requests with an unrecognized hostname in any of the following\n # HTTP headers: Host, X-Forwarded-Host, Forwarded, based on\n # {<tt>Request#forwarded_authority</tt>}[https://rubydoc.info/github/rack/rack/Rack/Request/Helpers#forwarded_authority-instance_method] and\n # {<tt>Request#host_authority</tt>}[https://rubydoc.info/github/rack/rack/Rack%2FRequest%2FHelpers:host_authority].\n #\n # == Options\n #\n # [<tt>:permitted_hosts</tt>] an Array of hosts to allow. Elements can be as follows:\n # [<tt>String</tt> not starting with a dot] a hostname that must be a case-insensitive\n # match to allow the request.\n # [<tt>String</tt> starting with a dot] allow matches from the entire domain, including\n # "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":7,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: DNS rebinding and other Host header attacks\n # Supported browsers:: all\n # More info:: * https://en.wikipedia.org/wiki/DNS_rebinding\n # * https://portswigger.net/web-security/host-header\n #\n # Blocks HTTP requests with an unrecognized hostname in any of the following\n # HTTP headers: Host, X-Forwarded-Host, Forwarded, based on\n # {<tt>Request#forwarded_authority</tt>}[https://rubydoc.info/github/rack/rack/Rack/Request/Helpers#forwarded_authority-instance_method] and\n # {<tt>Request#host_authority</tt>}[https://rubydoc.info/github/rack/rack/Rack%2FRequest%2FHelpers:host_authority].\n #\n # == Options\n #\n # [<tt>:permitted_hosts</tt>] an Array of hosts to allow. Elements can be as follows:\n # [<tt>String</tt> not starting with a dot] a hostname that must be a case-insensitive\n # match to allow the request.\n # [<tt>String</tt> starting with a dot] allow matches from the entire domain, including\n # "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":49,"symbol":"HostAuthorization","kind":"class","lang":"ruby","doc":"== Example: Allow an IP range use Rack::Protection::HostAuthorization, permitted_hosts: [ IPAddr.new(\"192.168.2.0/16\") ] The `:allow_if` option can also be set to a proc to use custom allow/deny logic.","code":"class HostAuthorization < Base\n DOT = '.'\n PORT_REGEXP = /:\\d+\\z/.freeze\n SUBDOMAINS = /[a-z0-9\\-.]+/.freeze\n private_constant :DOT,\n :PORT_REGEXP,\n :SUBDOMAINS\n default_reaction :deny\n default_options allow_if: nil,\n message: 'Host not permitted'\n\n def initialize(*)\n super\n @permitted_hosts = []\n @domain_hosts = []\n @ip_hosts = []\n @all_permitted_hosts = Array(options[:permitted_hosts])\n\n @all_permitted_hosts.each do |host|\n case host\n when String\n if host.start_with?(DOT)\n domain = host[1..-1]\n @permitted_hosts << domain.downcase\n @domain_hosts << /\\A#{SUBDOMAINS}#{Regexp.escape(domain)}\\z/i\n else\n @permitted_hosts << host.downcase\n end\n when IPAddr then @ip_hosts << host\n end\n end\n end\n\n def accepts?(env)\n return true if options[:allow_if]&.call(env)\n return true if @all_permitted_hosts.empty?\n\n request = Request.new(env)\n origin_host = extract_host(request.host_authority)\n "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":60,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(*)\n super\n @permitted_hosts = []\n @domain_hosts = []\n @ip_hosts = []\n @all_permitted_hosts = Array(options[:permitted_hosts])\n\n @all_permitted_hosts.each do |host|\n case host\n when String\n if host.start_with?(DOT)\n domain = host[1..-1]\n @permitted_hosts << domain.downcase\n @domain_hosts << /\\A#{SUBDOMAINS}#{Regexp.escape(domain)}\\z/i\n else\n @permitted_hosts << host.downcase\n end\n when IPAddr then @ip_hosts << host\n end\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":82,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n return true if options[:allow_if]&.call(env)\n return true if @all_permitted_hosts.empty?\n\n request = Request.new(env)\n origin_host = extract_host(request.host_authority)\n forwarded_host = extract_host(request.forwarded_authority)\n\n debug env, \"#{self.class} \" \\\n \"@all_permitted_hosts=#{@all_permitted_hosts.inspect} \" \\\n \"@permitted_hosts=#{@permitted_hosts.inspect} \" \\\n \"@domain_hosts=#{@domain_hosts.inspect} \" \\\n \"@ip_hosts=#{@ip_hosts.inspect} \" \\\n \"origin_host=#{origin_host.inspect} \" \\\n \"forwarded_host=#{forwarded_host.inspect}\"\n\n if host_permitted?(origin_host)\n if forwarded_host.nil?\n true\n else\n host_permitted?(forwarded_host)\n end\n else\n false\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":111,"symbol":"extract_host","kind":"method","lang":"ruby","code":"def extract_host(authority)\n authority.to_s.split(PORT_REGEXP).first&.downcase\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":115,"symbol":"host_permitted?","kind":"method","lang":"ruby","code":"def host_permitted?(host)\n exact_match?(host) || domain_match?(host) || ip_match?(host)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":119,"symbol":"exact_match?","kind":"method","lang":"ruby","code":"def exact_match?(host)\n @permitted_hosts.include?(host)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":123,"symbol":"domain_match?","kind":"method","lang":"ruby","code":"def domain_match?(host)\n return false if host.nil?\n return false if host.start_with?(DOT)\n\n @domain_hosts.any? { |domain_host| host.match?(domain_host) }\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/host_authorization.rb","line":130,"symbol":"ip_match?","kind":"method","lang":"ruby","code":"def ip_match?(host)\n @ip_hosts.any? { |ip_host| ip_host.include?(host) }\n rescue IPAddr::InvalidAddressError\n false\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/http_origin.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: Google Chrome 4, Safari 3.1, Firefox 70, Edge 70 and later.\n # See https://caniuse.com/mdn-http_headers_origin, for a complete list.\n # More infos:: * http://en.wikipedia.org/wiki/Cross-site_request_forgery\n # * http://tools.ietf.org/html/draft-abarth-origin\n # * https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin\n #\n # Rejects any {unsafe request}[https://httpwg.org/specs/rfc9110.html#safe.methods]\n # whose Origin HTTP header does match one of the origins given to <tt>:permitted_origins</tt>.\n # Note that if the Origin is the same as the request host, the request is always allowed.\n # Similarly, if there is not Origin header for an unsafe request, it is always denied.\n #\n # == Options\n #\n # [<tt>:permitted_origins</tt>] A String or Array of Strings representing the *additional* allowed origins for\n # an unsafe request. The values must be exact matches for the \n # value provided in the Orig"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/http_origin.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: Google Chrome 4, Safari 3.1, Firefox 70, Edge 70 and later.\n # See https://caniuse.com/mdn-http_headers_origin, for a complete list.\n # More infos:: * http://en.wikipedia.org/wiki/Cross-site_request_forgery\n # * http://tools.ietf.org/html/draft-abarth-origin\n # * https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin\n #\n # Rejects any {unsafe request}[https://httpwg.org/specs/rfc9110.html#safe.methods]\n # whose Origin HTTP header does match one of the origins given to <tt>:permitted_origins</tt>.\n # Note that if the Origin is the same as the request host, the request is always allowed.\n # Similarly, if there is not Origin header for an unsafe request, it is always denied.\n #\n # == Options\n #\n # [<tt>:permitted_origins</tt>] A String or Array of Strings representing the *additional* allowed origins for\n # an unsafe request. The values must be exact matches for the \n # value provided in the Origin header. Ge"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/http_origin.rb","line":41,"symbol":"HttpOrigin","kind":"class","lang":"ruby","doc":"== Example: Including your local dev environment use Rack::Protection, permitted_origins: [\"http://localhost:3000\", \"http://127.0.0.1:3000\"]","code":"class HttpOrigin < Base\n DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 }\n default_reaction :deny\n default_options allow_if: nil\n\n def base_url(env)\n request = Rack::Request.new(env)\n port = \":#{request.port}\" unless request.port == DEFAULT_PORTS[request.scheme]\n \"#{request.scheme}://#{request.host}#{port}\"\n end\n\n def accepts?(env)\n return true if safe? env\n return true unless (origin = env['HTTP_ORIGIN'])\n return true if base_url(env) == origin\n return true if options[:allow_if]&.call(env)\n\n permitted_origins = options[:permitted_origins]\n Array(permitted_origins).include? origin\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/http_origin.rb","line":46,"symbol":"base_url","kind":"method","lang":"ruby","code":"def base_url(env)\n request = Rack::Request.new(env)\n port = \":#{request.port}\" unless request.port == DEFAULT_PORTS[request.scheme]\n \"#{request.scheme}://#{request.host}#{port}\"\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/http_origin.rb","line":52,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n return true if safe? env\n return true unless (origin = env['HTTP_ORIGIN'])\n return true if base_url(env) == origin\n return true if options[:allow_if]&.call(env)\n\n permitted_origins = options[:permitted_origins]\n Array(permitted_origins).include? origin\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/ip_spoofing.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: IP spoofing\n # Supported browsers:: all\n # More infos:: http://blog.c22.cc/2011/04/22/surveymonkey-ip-spoofing/\n #\n # Detect (some) IP spoofing attacks.\n class IPSpoofing < Base\n default_reaction :deny\n\n def accepts?(env)\n return true unless env.include? 'HTTP_X_FORWARDED_FOR'\n\n ips = env['HTTP_X_FORWARDED_FOR'].split(',').map(&:strip)\n return false if env.include?('HTTP_CLIENT_IP') && (!ips.include? env['HTTP_CLIENT_IP'])\n return false if env.include?('HTTP_X_REAL_IP') && (!ips.include? env['HTTP_X_REAL_IP'])\n\n true\n end\n end\n end\nend"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/ip_spoofing.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: IP spoofing\n # Supported browsers:: all\n # More infos:: http://blog.c22.cc/2011/04/22/surveymonkey-ip-spoofing/\n #\n # Detect (some) IP spoofing attacks.\n class IPSpoofing < Base\n default_reaction :deny\n\n def accepts?(env)\n return true unless env.include? 'HTTP_X_FORWARDED_FOR'\n\n ips = env['HTTP_X_FORWARDED_FOR'].split(',').map(&:strip)\n return false if env.include?('HTTP_CLIENT_IP') && (!ips.include? env['HTTP_CLIENT_IP'])\n return false if env.include?('HTTP_X_REAL_IP') && (!ips.include? env['HTTP_X_REAL_IP'])\n\n true\n end\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/ip_spoofing.rb","line":13,"symbol":"IPSpoofing","kind":"class","lang":"ruby","doc":"# Prevented attack:: IP spoofing Supported browsers:: all More infos:: http://blog.c22.cc/2011/04/22/surveymonkey-ip-spoofing/ Detect (some) IP spoofing attacks.","code":"class IPSpoofing < Base\n default_reaction :deny\n\n def accepts?(env)\n return true unless env.include? 'HTTP_X_FORWARDED_FOR'\n\n ips = env['HTTP_X_FORWARDED_FOR'].split(',').map(&:strip)\n return false if env.include?('HTTP_CLIENT_IP') && (!ips.include? env['HTTP_CLIENT_IP'])\n return false if env.include?('HTTP_X_REAL_IP') && (!ips.include? env['HTTP_X_REAL_IP'])\n\n true\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/ip_spoofing.rb","line":16,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n return true unless env.include? 'HTTP_X_FORWARDED_FOR'\n\n ips = env['HTTP_X_FORWARDED_FOR'].split(',').map(&:strip)\n return false if env.include?('HTTP_CLIENT_IP') && (!ips.include? env['HTTP_CLIENT_IP'])\n return false if env.include?('HTTP_X_REAL_IP') && (!ips.include? env['HTTP_X_REAL_IP'])\n\n true\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/json_csrf.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://flask.pocoo.org/docs/0.10/security/#json-security\n # http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx\n #\n # JSON GET APIs are vulnerable to being embedded as JavaScript when the\n # Array prototype has been patched to track data. Checks the referrer\n # even on GET requests if the content type is JSON.\n #\n # If request includes Origin HTTP header, defers to HttpOrigin to determine\n # if the request is safe. Please refer to the documentation for more info.\n #\n # The `:allow_if` option can be set to a proc to use custom allow/deny logic.\n class JsonCsrf < Base\n default_options allow_if: nil\n\n alias react deny\n\n def call(env)\n request = Request.new(env)\n status, headers, body = app.call(env)\n\n if has_vector?(request, headers)\n warn env, \"attack prevented by #{self.class}\"\n\n react_and_close(env, body) or [status, headers, body]\n else\n [status, headers, body]\n end\n end\n\n "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/json_csrf.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://flask.pocoo.org/docs/0.10/security/#json-security\n # http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx\n #\n # JSON GET APIs are vulnerable to being embedded as JavaScript when the\n # Array prototype has been patched to track data. Checks the referrer\n # even on GET requests if the content type is JSON.\n #\n # If request includes Origin HTTP header, defers to HttpOrigin to determine\n # if the request is safe. Please refer to the documentation for more info.\n #\n # The `:allow_if` option can be set to a proc to use custom allow/deny logic.\n class JsonCsrf < Base\n default_options allow_if: nil\n\n alias react deny\n\n def call(env)\n request = Request.new(env)\n status, headers, body = app.call(env)\n\n if has_vector?(request, headers)\n warn env, \"attack prevented by #{self.class}\"\n\n react_and_close(env, body) or [status, headers, body]\n else\n [status, headers, body]\n end\n end\n\n def has_vecto"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/json_csrf.rb","line":21,"symbol":"JsonCsrf","kind":"class","lang":"ruby","doc":"even on GET requests if the content type is JSON. If request includes Origin HTTP header, defers to HttpOrigin to determine if the request is safe. Please refer to the documentation for more info. The `:allow_if` option can be set to a proc to use custom allow/deny logic.","code":"class JsonCsrf < Base\n default_options allow_if: nil\n\n alias react deny\n\n def call(env)\n request = Request.new(env)\n status, headers, body = app.call(env)\n\n if has_vector?(request, headers)\n warn env, \"attack prevented by #{self.class}\"\n\n react_and_close(env, body) or [status, headers, body]\n else\n [status, headers, body]\n end\n end\n\n def has_vector?(request, headers)\n return false if request.xhr?\n return false if options[:allow_if]&.call(request.env)\n return false unless headers['content-type'].to_s.split(';', 2).first =~ %r{^\\s*application/json\\s*$}\n\n origin(request.env).nil? and referrer(request.env) != request.host\n end\n\n def react_and_close(env, body)\n reaction = react(env)\n\n close_body(body) if reaction\n\n reaction\n end\n\n def close_body(body)\n body.close if body.respond_to?(:close)\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/json_csrf.rb","line":26,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n request = Request.new(env)\n status, headers, body = app.call(env)\n\n if has_vector?(request, headers)\n warn env, \"attack prevented by #{self.class}\"\n\n react_and_close(env, body) or [status, headers, body]\n else\n [status, headers, body]\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/json_csrf.rb","line":39,"symbol":"has_vector?","kind":"method","lang":"ruby","code":"def has_vector?(request, headers)\n return false if request.xhr?\n return false if options[:allow_if]&.call(request.env)\n return false unless headers['content-type'].to_s.split(';', 2).first =~ %r{^\\s*application/json\\s*$}\n\n origin(request.env).nil? and referrer(request.env) != request.host\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/json_csrf.rb","line":47,"symbol":"react_and_close","kind":"method","lang":"ruby","code":"def react_and_close(env, body)\n reaction = react(env)\n\n close_body(body) if reaction\n\n reaction\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/json_csrf.rb","line":55,"symbol":"close_body","kind":"method","lang":"ruby","code":"def close_body(body)\n body.close if body.respond_to?(:close)\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/path_traversal.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: Directory traversal\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Directory_traversal\n #\n # Unescapes '/' and '.', expands +path_info+.\n # Thus <tt>GET /foo/%2e%2e%2fbar</tt> becomes <tt>GET /bar</tt>.\n class PathTraversal < Base\n def call(env)\n path_was = env['PATH_INFO']\n env['PATH_INFO'] = cleanup path_was if path_was && !path_was.empty?\n app.call env\n ensure\n env['PATH_INFO'] = path_was\n end\n\n def cleanup(path)\n encoding = path.encoding\n dot = '.'.encode(encoding)\n slash = '/'.encode(encoding)\n backslash = '\\\\'.encode(encoding)\n\n parts = []\n unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash).gsub(/%5c/i, backslash)\n unescaped = unescaped.gsub(backslash, slash)\n\n unescaped.split(slash).each do |part|\n next if part.empty? || (part == dot)\n\n part == '..' ? parts.pop : parts << part\n end\n\n cleaned = slash + parts.join(slash)\n cleaned << slash if parts.any? && unescaped =~ (%r{/\\.{0,2}$})\n cleaned\n "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/path_traversal.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: Directory traversal\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Directory_traversal\n #\n # Unescapes '/' and '.', expands +path_info+.\n # Thus <tt>GET /foo/%2e%2e%2fbar</tt> becomes <tt>GET /bar</tt>.\n class PathTraversal < Base\n def call(env)\n path_was = env['PATH_INFO']\n env['PATH_INFO'] = cleanup path_was if path_was && !path_was.empty?\n app.call env\n ensure\n env['PATH_INFO'] = path_was\n end\n\n def cleanup(path)\n encoding = path.encoding\n dot = '.'.encode(encoding)\n slash = '/'.encode(encoding)\n backslash = '\\\\'.encode(encoding)\n\n parts = []\n unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash).gsub(/%5c/i, backslash)\n unescaped = unescaped.gsub(backslash, slash)\n\n unescaped.split(slash).each do |part|\n next if part.empty? || (part == dot)\n\n part == '..' ? parts.pop : parts << part\n end\n\n cleaned = slash + parts.join(slash)\n cleaned << slash if parts.any? && unescaped =~ (%r{/\\.{0,2}$})\n cleaned\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/path_traversal.rb","line":14,"symbol":"PathTraversal","kind":"class","lang":"ruby","doc":"Prevented attack:: Directory traversal Supported browsers:: all More infos:: http://en.wikipedia.org/wiki/Directory_traversal Unescapes '/' and '.', expands +path_info+. Thus <tt>GET /foo/%2e%2e%2fbar</tt> becomes <tt>GET /bar</tt>.","code":"class PathTraversal < Base\n def call(env)\n path_was = env['PATH_INFO']\n env['PATH_INFO'] = cleanup path_was if path_was && !path_was.empty?\n app.call env\n ensure\n env['PATH_INFO'] = path_was\n end\n\n def cleanup(path)\n encoding = path.encoding\n dot = '.'.encode(encoding)\n slash = '/'.encode(encoding)\n backslash = '\\\\'.encode(encoding)\n\n parts = []\n unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash).gsub(/%5c/i, backslash)\n unescaped = unescaped.gsub(backslash, slash)\n\n unescaped.split(slash).each do |part|\n next if part.empty? || (part == dot)\n\n part == '..' ? parts.pop : parts << part\n end\n\n cleaned = slash + parts.join(slash)\n cleaned << slash if parts.any? && unescaped =~ (%r{/\\.{0,2}$})\n cleaned\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/path_traversal.rb","line":15,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n path_was = env['PATH_INFO']\n env['PATH_INFO'] = cleanup path_was if path_was && !path_was.empty?\n app.call env\n ensure\n env['PATH_INFO'] = path_was\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/path_traversal.rb","line":23,"symbol":"cleanup","kind":"method","lang":"ruby","code":"def cleanup(path)\n encoding = path.encoding\n dot = '.'.encode(encoding)\n slash = '/'.encode(encoding)\n backslash = '\\\\'.encode(encoding)\n\n parts = []\n unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash).gsub(/%5c/i, backslash)\n unescaped = unescaped.gsub(backslash, slash)\n\n unescaped.split(slash).each do |part|\n next if part.empty? || (part == dot)\n\n part == '..' ? parts.pop : parts << part\n end\n\n cleaned = slash + parts.join(slash)\n cleaned << slash if parts.any? && unescaped =~ (%r{/\\.{0,2}$})\n cleaned\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/referrer_policy.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: Secret leakage, third party tracking\n # Supported browsers:: Most modern browsers from 2018 onwards. See https://caniuse.com/#search=referrer-policy for\n # specifics.\n # More info:: * https://www.w3.org/TR/referrer-policy/\n # * https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns\n #\n # Sets the {Referrer-Policy}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referrer-Policy]\n # header to tell the browser to limit the Referer header.\n #\n # == Options\n # \n # [<tt>:referrer_policy</tt>] The policy to use as a String. Default is 'strict-origin-when-cross-origin' (which,\n # despite being the browser's default, is still set explicitly when \n # this middleware is used). Note that this option has no effect if an upstream\n # middleware (or your app) has set the Referrer-Policy header.\n class ReferrerPolicy < Base\n default_options referrer_policy: 'strict-origin-when-cross-orig"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/referrer_policy.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: Secret leakage, third party tracking\n # Supported browsers:: Most modern browsers from 2018 onwards. See https://caniuse.com/#search=referrer-policy for\n # specifics.\n # More info:: * https://www.w3.org/TR/referrer-policy/\n # * https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns\n #\n # Sets the {Referrer-Policy}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referrer-Policy]\n # header to tell the browser to limit the Referer header.\n #\n # == Options\n # \n # [<tt>:referrer_policy</tt>] The policy to use as a String. Default is 'strict-origin-when-cross-origin' (which,\n # despite being the browser's default, is still set explicitly when \n # this middleware is used). Note that this option has no effect if an upstream\n # middleware (or your app) has set the Referrer-Policy header.\n class ReferrerPolicy < Base\n default_options referrer_policy: 'strict-origin-when-cross-origin'\n\n def"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/referrer_policy.rb","line":23,"symbol":"ReferrerPolicy","kind":"class","lang":"ruby","doc":"== Options [<tt>:referrer_policy</tt>] The policy to use as a String. Default is 'strict-origin-when-cross-origin' (which, despite being the browser's default, is still set explicitly when this middleware is used). Note that this option has no effect if an upstream middleware (or your app) has set the Referrer-Policy header.","code":"class ReferrerPolicy < Base\n default_options referrer_policy: 'strict-origin-when-cross-origin'\n\n def call(env)\n status, headers, body = @app.call(env)\n headers['referrer-policy'] ||= options[:referrer_policy]\n [status, headers, body]\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/referrer_policy.rb","line":26,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n headers['referrer-policy'] ||= options[:referrer_policy]\n [status, headers, body]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/remote_referrer.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery\n #\n # Does not accept unsafe HTTP requests if the Referer [sic] header is set to\n # a different host.\n class RemoteReferrer < Base\n default_reaction :deny\n\n def accepts?(env)\n safe?(env) or referrer(env) == Request.new(env).host\n end\n end\n end\nend"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/remote_referrer.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery\n #\n # Does not accept unsafe HTTP requests if the Referer [sic] header is set to\n # a different host.\n class RemoteReferrer < Base\n default_reaction :deny\n\n def accepts?(env)\n safe?(env) or referrer(env) == Request.new(env).host\n end\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/remote_referrer.rb","line":14,"symbol":"RemoteReferrer","kind":"class","lang":"ruby","doc":"Prevented attack:: CSRF Supported browsers:: all More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery Does not accept unsafe HTTP requests if the Referer [sic] header is set to a different host.","code":"class RemoteReferrer < Base\n default_reaction :deny\n\n def accepts?(env)\n safe?(env) or referrer(env) == Request.new(env).host\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/remote_referrer.rb","line":17,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n safe?(env) or referrer(env) == Request.new(env).host\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/remote_token.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery\n #\n # Only accepts unsafe HTTP requests if a given access token matches the token\n # included in the session *or* the request comes from the same origin.\n #\n # Compatible with rack-csrf.\n class RemoteToken < AuthenticityToken\n default_reaction :deny\n\n def accepts?(env)\n super or referrer(env) == Request.new(env).host\n end\n end\n end\nend"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/remote_token.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: CSRF\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery\n #\n # Only accepts unsafe HTTP requests if a given access token matches the token\n # included in the session *or* the request comes from the same origin.\n #\n # Compatible with rack-csrf.\n class RemoteToken < AuthenticityToken\n default_reaction :deny\n\n def accepts?(env)\n super or referrer(env) == Request.new(env).host\n end\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/remote_token.rb","line":16,"symbol":"RemoteToken","kind":"class","lang":"ruby","doc":"More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery Only accepts unsafe HTTP requests if a given access token matches the token included in the session *or* the request comes from the same origin. Compatible with rack-csrf.","code":"class RemoteToken < AuthenticityToken\n default_reaction :deny\n\n def accepts?(env)\n super or referrer(env) == Request.new(env).host\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/remote_token.rb","line":19,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n super or referrer(env) == Request.new(env).host\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/session_hijacking.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: Session Hijacking\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Session_hijacking\n #\n # Tracks request properties like the user agent in the session and empties\n # the session if those properties change. This essentially prevents attacks\n # from Firesheep. Since all headers taken into consideration can be\n # spoofed, too, this will not prevent determined hijacking attempts.\n class SessionHijacking < Base\n default_reaction :drop_session\n default_options tracking_key: :tracking,\n track: %w[HTTP_USER_AGENT]\n\n def accepts?(env)\n session = session env\n key = options[:tracking_key]\n if session.include? key\n session[key].all? { |k, v| v == encode(env[k]) }\n else\n session[key] = {}\n options[:track].each { |k| session[key][k] = encode(env[k]) }\n end\n end\n\n def encode(value)\n value.to_s.downcase\n end\n end\n end\nend"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/session_hijacking.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: Session Hijacking\n # Supported browsers:: all\n # More infos:: http://en.wikipedia.org/wiki/Session_hijacking\n #\n # Tracks request properties like the user agent in the session and empties\n # the session if those properties change. This essentially prevents attacks\n # from Firesheep. Since all headers taken into consideration can be\n # spoofed, too, this will not prevent determined hijacking attempts.\n class SessionHijacking < Base\n default_reaction :drop_session\n default_options tracking_key: :tracking,\n track: %w[HTTP_USER_AGENT]\n\n def accepts?(env)\n session = session env\n key = options[:tracking_key]\n if session.include? key\n session[key].all? { |k, v| v == encode(env[k]) }\n else\n session[key] = {}\n options[:track].each { |k| session[key][k] = encode(env[k]) }\n end\n end\n\n def encode(value)\n value.to_s.downcase\n end\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/session_hijacking.rb","line":16,"symbol":"SessionHijacking","kind":"class","lang":"ruby","doc":"More infos:: http://en.wikipedia.org/wiki/Session_hijacking Tracks request properties like the user agent in the session and empties the session if those properties change. This essentially prevents attacks from Firesheep. Since all headers taken into consideration can be spoofed, too, this will not prevent determined hijacking attempts.","code":"class SessionHijacking < Base\n default_reaction :drop_session\n default_options tracking_key: :tracking,\n track: %w[HTTP_USER_AGENT]\n\n def accepts?(env)\n session = session env\n key = options[:tracking_key]\n if session.include? key\n session[key].all? { |k, v| v == encode(env[k]) }\n else\n session[key] = {}\n options[:track].each { |k| session[key][k] = encode(env[k]) }\n end\n end\n\n def encode(value)\n value.to_s.downcase\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/session_hijacking.rb","line":21,"symbol":"accepts?","kind":"method","lang":"ruby","code":"def accepts?(env)\n session = session env\n key = options[:tracking_key]\n if session.include? key\n session[key].all? { |k, v| v == encode(env[k]) }\n else\n session[key] = {}\n options[:track].each { |k| session[key][k] = encode(env[k]) }\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/session_hijacking.rb","line":32,"symbol":"encode","kind":"method","lang":"ruby","code":"def encode(value)\n value.to_s.downcase\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/strict_transport.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: Protects against against protocol downgrade attacks and cookie hijacking.\n # Supported browsers:: All modern browsers. See https://caniuse.com/stricttransportsecurity\n # More info:: https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\n #\n # Sets the {Strict-Transport-Security}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Strict-Transport-Security]\n # http header. This headers tells the browser that HTTP requests will be upgraded to HTTPS.\n # It also prevents HTTPS click through prompts on browsers.\n #\n # Note that if an upstream middleware sets the Strict-Transport-Security header, this middleware will not overwrite\n # it and thus have no effect.\n #\n # == Options\n #\n # [<tt>:max_age</tt>] Time, in seconds, that the browser should remember the requirement to use HTTPS. Default is\n # one year.\n # [<tt>:include_subdomains</tt>] If true, all present and future subdomains should also use HTTPS. Default is false.\n # [<tt>:preload</tt>] Allow this domain to be included in browsers HSTS preload list. Default is false.\n"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/strict_transport.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: Protects against against protocol downgrade attacks and cookie hijacking.\n # Supported browsers:: All modern browsers. See https://caniuse.com/stricttransportsecurity\n # More info:: https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\n #\n # Sets the {Strict-Transport-Security}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Strict-Transport-Security]\n # http header. This headers tells the browser that HTTP requests will be upgraded to HTTPS.\n # It also prevents HTTPS click through prompts on browsers.\n #\n # Note that if an upstream middleware sets the Strict-Transport-Security header, this middleware will not overwrite\n # it and thus have no effect.\n #\n # == Options\n #\n # [<tt>:max_age</tt>] Time, in seconds, that the browser should remember the requirement to use HTTPS. Default is\n # one year.\n # [<tt>:include_subdomains</tt>] If true, all present and future subdomains should also use HTTPS. Default is false.\n # [<tt>:preload</tt>] Allow this domain to be included in browsers HSTS preload list. Default is false.\n # "}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/strict_transport.rb","line":26,"symbol":"StrictTransport","kind":"class","lang":"ruby","doc":"[<tt>:max_age</tt>] Time, in seconds, that the browser should remember the requirement to use HTTPS. Default is one year. [<tt>:include_subdomains</tt>] If true, all present and future subdomains should also use HTTPS. Default is false. [<tt>:preload</tt>] Allow this domain to be included in browsers HSTS preload list. Default is false. See https://hstspreload.org/","code":"class StrictTransport < Base\n default_options max_age: 31_536_000, include_subdomains: false, preload: false\n\n def strict_transport\n @strict_transport ||= begin\n strict_transport = \"max-age=#{options[:max_age]}\"\n strict_transport += '; includeSubDomains' if options[:include_subdomains]\n strict_transport += '; preload' if options[:preload]\n strict_transport.to_str\n end\n end\n\n def call(env)\n status, headers, body = @app.call(env)\n headers['strict-transport-security'] ||= strict_transport\n [status, headers, body]\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/strict_transport.rb","line":29,"symbol":"strict_transport","kind":"method","lang":"ruby","code":"def strict_transport\n @strict_transport ||= begin\n strict_transport = \"max-age=#{options[:max_age]}\"\n strict_transport += '; includeSubDomains' if options[:include_subdomains]\n strict_transport += '; preload' if options[:preload]\n strict_transport.to_str\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/strict_transport.rb","line":38,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n headers['strict-transport-security'] ||= strict_transport\n [status, headers, body]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/version.rb","line":3,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n VERSION = '4.2.1'\n end\nend"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/version.rb","line":4,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n VERSION = '4.2.1'\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/xss_header.rb","line":5,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n ##\n # Prevented attack:: Non-permanent XSS\n # Supported browsers:: Internet Explorer 8+ and Chrome\n # More infos:: http://blogs.msdn.com/b/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx\n #\n # Sets X-XSS-Protection header to tell the browser to block attacks.\n #\n # Options:\n # xss_mode:: How the browser should prevent the attack (default: :block)\n class XSSHeader < Base\n default_options xss_mode: :block, nosniff: true\n\n def call(env)\n status, headers, body = @app.call(env)\n headers['x-xss-protection'] ||= \"1; mode=#{options[:xss_mode]}\" if html? headers\n headers['x-content-type-options'] ||= 'nosniff' if options[:nosniff]\n [status, headers, body]\n end\n end\n end\nend"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/xss_header.rb","line":6,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n ##\n # Prevented attack:: Non-permanent XSS\n # Supported browsers:: Internet Explorer 8+ and Chrome\n # More infos:: http://blogs.msdn.com/b/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx\n #\n # Sets X-XSS-Protection header to tell the browser to block attacks.\n #\n # Options:\n # xss_mode:: How the browser should prevent the attack (default: :block)\n class XSSHeader < Base\n default_options xss_mode: :block, nosniff: true\n\n def call(env)\n status, headers, body = @app.call(env)\n headers['x-xss-protection'] ||= \"1; mode=#{options[:xss_mode]}\" if html? headers\n headers['x-content-type-options'] ||= 'nosniff' if options[:nosniff]\n [status, headers, body]\n end\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/xss_header.rb","line":16,"symbol":"XSSHeader","kind":"class","lang":"ruby","doc":"More infos:: http://blogs.msdn.com/b/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx Sets X-XSS-Protection header to tell the browser to block attacks. Options: xss_mode:: How the browser should prevent the attack (default: :block)","code":"class XSSHeader < Base\n default_options xss_mode: :block, nosniff: true\n\n def call(env)\n status, headers, body = @app.call(env)\n headers['x-xss-protection'] ||= \"1; mode=#{options[:xss_mode]}\" if html? headers\n headers['x-content-type-options'] ||= 'nosniff' if options[:nosniff]\n [status, headers, body]\n end\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection/xss_header.rb","line":19,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n headers['x-xss-protection'] ||= \"1; mode=#{options[:xss_mode]}\" if html? headers\n headers['x-content-type-options'] ||= 'nosniff' if options[:nosniff]\n [status, headers, body]\n end"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection.rb","line":6,"symbol":"Rack","kind":"module","lang":"ruby","code":"module Rack\n module Protection\n autoload :AuthenticityToken, 'rack/protection/authenticity_token'\n autoload :Base, 'rack/protection/base'\n autoload :CookieTossing, 'rack/protection/cookie_tossing'\n autoload :ContentSecurityPolicy, 'rack/protection/content_security_policy'\n autoload :EscapedParams, 'rack/protection/escaped_params'\n autoload :FormToken, 'rack/protection/form_token'\n autoload :FrameOptions, 'rack/protection/frame_options'\n autoload :HostAuthorization, 'rack/protection/host_authorization'\n autoload :HttpOrigin, 'rack/protection/http_origin'\n autoload :IPSpoofing, 'rack/protection/ip_spoofing'\n autoload :JsonCsrf, 'rack/protection/json_csrf'\n autoload :PathTraversal, 'rack/protection/path_traversal'\n autoload :ReferrerPolicy, 'rack/protection/referrer_policy'\n autoload :RemoteReferrer, 'rack/protection/remote_referrer'\n autoload :RemoteToken, 'rack/protection/remote_token'\n autoload :SessionHijacking, 'rack/protection/session_hijacking'\n autoload :StrictTransport, 'rack/protection/"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection.rb","line":7,"symbol":"Protection","kind":"module","lang":"ruby","code":"module Protection\n autoload :AuthenticityToken, 'rack/protection/authenticity_token'\n autoload :Base, 'rack/protection/base'\n autoload :CookieTossing, 'rack/protection/cookie_tossing'\n autoload :ContentSecurityPolicy, 'rack/protection/content_security_policy'\n autoload :EscapedParams, 'rack/protection/escaped_params'\n autoload :FormToken, 'rack/protection/form_token'\n autoload :FrameOptions, 'rack/protection/frame_options'\n autoload :HostAuthorization, 'rack/protection/host_authorization'\n autoload :HttpOrigin, 'rack/protection/http_origin'\n autoload :IPSpoofing, 'rack/protection/ip_spoofing'\n autoload :JsonCsrf, 'rack/protection/json_csrf'\n autoload :PathTraversal, 'rack/protection/path_traversal'\n autoload :ReferrerPolicy, 'rack/protection/referrer_policy'\n autoload :RemoteReferrer, 'rack/protection/remote_referrer'\n autoload :RemoteToken, 'rack/protection/remote_token'\n autoload :SessionHijacking, 'rack/protection/session_hijacking'\n autoload :StrictTransport, 'rack/protection/strict_transpo"}
{"repo":"sinatra","file":"rack-protection/lib/rack/protection.rb","line":27,"symbol":"new","kind":"method","lang":"ruby","code":"def self.new(app, options = {})\n except = Array options[:except]\n use_these = Array options[:use]\n\n if options.fetch(:without_session, false)\n except += %i[remote_token]\n end\n\n Rack::Builder.new do\n # Off by default, unless added\n use ::Rack::Protection::AuthenticityToken, options if use_these.include? :authenticity_token\n use ::Rack::Protection::ContentSecurityPolicy, options if use_these.include? :content_security_policy\n use ::Rack::Protection::CookieTossing, options if use_these.include? :cookie_tossing\n use ::Rack::Protection::EscapedParams, options if use_these.include? :escaped_params\n use ::Rack::Protection::FormToken, options if use_these.include? :form_token\n use ::Rack::Protection::ReferrerPolicy, options if use_these.include? :referrer_policy\n use ::Rack::Protection::RemoteReferrer, options if use_these.include? :remote_referrer\n use ::Rack::Protection::SessionHijacking, options if use_these.include? :session_hijacking\n use ::Rack::Protection::StrictTransport, options if use_these.include? :strict_transport\n\n "}
{"repo":"sinatra","file":"rack-protection/spec/lib/rack/protection/host_authorization_spec.rb","line":8,"symbol":"assert_response","kind":"method","lang":"ruby","code":"def assert_response(outcome:, headers:, last_response:)\n fail_message = \"Expected outcome '#{outcome}' for headers '#{headers}' \" \\\n \"last_response.status '#{last_response.status}'\"\n\n case outcome\n when :allowed\n expect(last_response).to be_ok, fail_message\n when :stopped\n expect(last_response.status).to eq(403), fail_message\n expect(last_response.body).to eq('Host not permitted'), fail_message\n end\n end"}
{"repo":"sinatra","file":"rack-protection/spec/lib/rack/protection/json_csrf_spec.rb","line":6,"symbol":"DummyAppWithBody","kind":"module","lang":"ruby","code":"module DummyAppWithBody\n module Closeable\n def close\n @closed = true\n end\n\n def closed?\n @closed\n end\n end\n\n def self.body\n @body ||= begin\n body = ['ok']\n body.extend(Closeable)\n body\n end\n end\n\n def self.call(env)\n Thread.current[:last_env] = env\n [200, { 'content-type' => 'application/json' }, body]\n end\n end"}
{"repo":"sinatra","file":"rack-protection/spec/lib/rack/protection/json_csrf_spec.rb","line":7,"symbol":"Closeable","kind":"module","lang":"ruby","code":"module Closeable\n def close\n @closed = true\n end\n\n def closed?\n @closed\n end\n end"}
{"repo":"sinatra","file":"rack-protection/spec/lib/rack/protection/json_csrf_spec.rb","line":8,"symbol":"close","kind":"method","lang":"ruby","code":"def close\n @closed = true\n end"}
{"repo":"sinatra","file":"rack-protection/spec/lib/rack/protection/json_csrf_spec.rb","line":12,"symbol":"closed?","kind":"method","lang":"ruby","code":"def closed?\n @closed\n end"}
{"repo":"sinatra","file":"rack-protection/spec/lib/rack/protection/json_csrf_spec.rb","line":17,"symbol":"body","kind":"method","lang":"ruby","code":"def self.body\n @body ||= begin\n body = ['ok']\n body.extend(Closeable)\n body\n end\n end"}
{"repo":"sinatra","file":"rack-protection/spec/lib/rack/protection/json_csrf_spec.rb","line":25,"symbol":"call","kind":"method","lang":"ruby","code":"def self.call(env)\n Thread.current[:last_env] = env\n [200, { 'content-type' => 'application/json' }, body]\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/dummy_app.rb","line":3,"symbol":"DummyApp","kind":"module","lang":"ruby","code":"module DummyApp\n def self.call(env)\n Thread.current[:last_env] = env\n body = (env['REQUEST_METHOD'] == 'HEAD' ? '' : 'ok')\n [200, { 'content-type' => env['wants'] || 'text/plain' }, [body]]\n end\nend"}
{"repo":"sinatra","file":"rack-protection/spec/support/dummy_app.rb","line":4,"symbol":"call","kind":"method","lang":"ruby","code":"def self.call(env)\n Thread.current[:last_env] = env\n body = (env['REQUEST_METHOD'] == 'HEAD' ? '' : 'ok')\n [200, { 'content-type' => env['wants'] || 'text/plain' }, [body]]\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/not_implemented_as_pending.rb","line":4,"symbol":"NotImplementedAsPending","kind":"module","lang":"ruby","doc":"see http://blog.101ideas.cz/posts/pending-examples-via-not-implemented-error-in-rspec.html","code":"module NotImplementedAsPending\n def self.included(base)\n base.class_eval do\n alias_method :__finish__, :finish\n remove_method :finish\n end\n end\n\n def finish(reporter)\n if @exception.is_a?(NotImplementedError)\n from = @exception.backtrace[0]\n message = \"#{@exception.message} (from #{from})\"\n @pending_declared_in_example = message\n metadata[:pending] = true\n @exception = nil\n end\n\n __finish__(reporter)\n end\n\n RSpec::Core::Example.send :include, self\nend"}
{"repo":"sinatra","file":"rack-protection/spec/support/not_implemented_as_pending.rb","line":5,"symbol":"included","kind":"method","lang":"ruby","code":"def self.included(base)\n base.class_eval do\n alias_method :__finish__, :finish\n remove_method :finish\n end\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/not_implemented_as_pending.rb","line":12,"symbol":"finish","kind":"method","lang":"ruby","code":"def finish(reporter)\n if @exception.is_a?(NotImplementedError)\n from = @exception.backtrace[0]\n message = \"#{@exception.message} (from #{from})\"\n @pending_declared_in_example = message\n metadata[:pending] = true\n @exception = nil\n end\n\n __finish__(reporter)\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/shared_examples.rb","line":16,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n was = env.dup\n res = app.call(env)\n was.each do |k, v|\n next if env[k] == v\n\n raise \"env[#{k.inspect}] changed from #{v.inspect} to #{env[k].inspect}\"\n end\n res\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/shared_examples.rb","line":42,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n env['foo.bar'] = 42\n app.call(env)\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/shared_examples.rb","line":48,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n app.call(env)\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/spec_helpers.rb","line":5,"symbol":"SpecHelpers","kind":"module","lang":"ruby","code":"module SpecHelpers\n extend Forwardable\n def_delegators :last_response, :body, :headers, :status, :errors\n def_delegators :current_session, :env_for\n attr_writer :app\n\n def app\n @app ||= nil\n @app || mock_app(DummyApp)\n end\n\n def mock_app(app = nil, lint: true, &block)\n app = block if app.nil? && (block.arity == 1)\n if app\n klass = described_class\n mock_app do\n use Rack::Head\n use(Rack::Config) { |e| e['rack.session'] ||= {} }\n use klass\n run app\n end\n elsif lint\n @app = Rack::Lint.new Rack::Builder.new(&block).to_app\n else\n @app = Rack::Builder.new(&block).to_app\n end\n end\n\n def with_headers(headers)\n proc { [200, { 'content-type' => 'text/plain' }.merge(headers), ['ok']] }\n end\n\n def env\n Thread.current[:last_env]\n end\nend"}
{"repo":"sinatra","file":"rack-protection/spec/support/spec_helpers.rb","line":11,"symbol":"app","kind":"method","lang":"ruby","code":"def app\n @app ||= nil\n @app || mock_app(DummyApp)\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/spec_helpers.rb","line":16,"symbol":"mock_app","kind":"method","lang":"ruby","code":"def mock_app(app = nil, lint: true, &block)\n app = block if app.nil? && (block.arity == 1)\n if app\n klass = described_class\n mock_app do\n use Rack::Head\n use(Rack::Config) { |e| e['rack.session'] ||= {} }\n use klass\n run app\n end\n elsif lint\n @app = Rack::Lint.new Rack::Builder.new(&block).to_app\n else\n @app = Rack::Builder.new(&block).to_app\n end\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/spec_helpers.rb","line":33,"symbol":"with_headers","kind":"method","lang":"ruby","code":"def with_headers(headers)\n proc { [200, { 'content-type' => 'text/plain' }.merge(headers), ['ok']] }\n end"}
{"repo":"sinatra","file":"rack-protection/spec/support/spec_helpers.rb","line":37,"symbol":"env","kind":"method","lang":"ruby","code":"def env\n Thread.current[:last_env]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/capture.rb","line":4,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n #\n # = Sinatra::Capture\n #\n # Extension that enables blocks inside other extensions.\n # It currently works for erb, slim and haml.\n # Enables mixing of different template languages.\n #\n # Example:\n #\n # # in hello_world.erb\n #\n # Say\n # <% a = capture do %>World<% end %>\n # Hello <%= a %>!\n #\n # # in hello_world.slim\n #\n # | Say\n # - a = capture do\n # | World\n # | Hello #{a}!\n #\n # # in hello_world.haml\n #\n # Say\n # - a = capture do\n # World\n # Hello #{a.strip}!\n #\n #\n # You can also use nested blocks.\n #\n # Example\n #\n # # in hello_world.erb\n #\n # Say\n # <% a = capture do %>\n # <% b = capture do %>World<% end %>\n # <%= b %>!\n # <% end %>\n # Hello <%= a.strip %>\n #\n #\n # The main advantage of capture is mixing of different template engines.\n #\n # Example\n #\n # # in mix_me_up.slim\n #\n # - two = capture do\n # - erb \"<%= 1 + 1 %>\"\n # | 1 + 1 = #{two}\n #\n # == Usage\n #\n # === Classic Application\n #\n # In a classic application simply require the helpers, and start using them:\n #\n # require \"sinatra\"\n # requ"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/capture.rb","line":84,"symbol":"Capture","kind":"module","lang":"ruby","doc":"class MyApp < Sinatra::Base helpers Sinatra::Capture # The rest of your modular application code goes here... end","code":"module Capture\n include Sinatra::EngineTracking\n\n def capture(*args, &block)\n return block[*args] if ruby?\n\n if haml? && Tilt[:haml] == Tilt::HamlTemplate && defined?(Haml::Buffer)\n buffer = Haml::Buffer.new(nil, Haml::Options.new.for_buffer)\n with_haml_buffer(buffer) { capture_haml(*args, &block) }\n else\n buf_was = @_out_buf\n @_out_buf = +''\n begin\n raw = block[*args]\n captured = block.binding.eval('@_out_buf')\n captured.empty? ? raw : captured\n ensure\n @_out_buf = buf_was\n end\n end\n end\n\n def capture_later(&block)\n engine = current_engine\n proc { |*a| with_engine(engine) { @capture = capture(*a, &block) } }\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/capture.rb","line":87,"symbol":"capture","kind":"method","lang":"ruby","code":"def capture(*args, &block)\n return block[*args] if ruby?\n\n if haml? && Tilt[:haml] == Tilt::HamlTemplate && defined?(Haml::Buffer)\n buffer = Haml::Buffer.new(nil, Haml::Options.new.for_buffer)\n with_haml_buffer(buffer) { capture_haml(*args, &block) }\n else\n buf_was = @_out_buf\n @_out_buf = +''\n begin\n raw = block[*args]\n captured = block.binding.eval('@_out_buf')\n captured.empty? ? raw : captured\n ensure\n @_out_buf = buf_was\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/capture.rb","line":106,"symbol":"capture_later","kind":"method","lang":"ruby","code":"def capture_later(&block)\n engine = current_engine\n proc { |*a| with_engine(engine) { @capture = capture(*a, &block) } }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::ConfigFile\n #\n # <tt>Sinatra::ConfigFile</tt> is an extension that allows you to load the\n # application's configuration from YAML files. It automatically detects if\n # the files contain specific environment settings and it will use those\n # corresponding to the current one.\n #\n # You can access those options through +settings+ within the application. If\n # you try to get the value for a setting that hasn't been defined in the\n # config file for the current environment, you will get whatever it was set\n # to in the application.\n #\n # == Usage\n #\n # Once you have written your configurations to a YAML file you can tell the\n # extension to load them. See below for more information about how these\n # files are interpreted.\n #\n # For the examples, lets assume the following config.yml file:\n #\n # greeting: Welcome to my file configurable application\n #\n # === Classic Application\n #\n # require \"sinatra\"\n # require \"sinatra/config_file\"\n #\n # config_file 'path/to/config.yml'\n #\n # get '/' do\n # @greeting = settings.greeting\n # haml :index\n # end\n #\n # # The rest of your classic applica"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":108,"symbol":"ConfigFile","kind":"module","lang":"ruby","doc":"bar: 'bar' production: <<: *common_settings bar: 'baz' # override the default value","code":"module ConfigFile\n # When the extension is registered sets the +environments+ setting to the\n # traditional environments: development, test and production.\n def self.registered(base)\n base.set :environments, %w[test production development]\n end\n\n # Loads the configuration from the YAML files whose +paths+ are passed as\n # arguments, filtering the settings for the current environment. Note that\n # these +paths+ can actually be globs.\n def config_file(*paths)\n Dir.chdir(root || '.') do\n paths.each do |pattern|\n Dir.glob(pattern) do |file|\n raise UnsupportedConfigType unless ['.yml', '.yaml', '.erb'].include?(File.extname(file))\n\n logger.info \"loading config file '#{file}'\" if logging? && respond_to?(:logger)\n document = ERB.new(File.read(file)).result\n yaml = YAML.respond_to?(:unsafe_load) ? YAML.unsafe_load(document) : YAML.load(document)\n config = config_for_env(yaml)\n config.each_pair { |key, value| set(key, value) }\n end\n end\n end\n end\n\n class UnsupportedConfigType < StandardError\n def message\n 'Invalid config file type, use ."}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":111,"symbol":"registered","kind":"method","lang":"ruby","doc":"When the extension is registered sets the +environments+ setting to the traditional environments: development, test and production.","code":"def self.registered(base)\n base.set :environments, %w[test production development]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":118,"symbol":"config_file","kind":"method","lang":"ruby","doc":"Loads the configuration from the YAML files whose +paths+ are passed as arguments, filtering the settings for the current environment. Note that these +paths+ can actually be globs.","code":"def config_file(*paths)\n Dir.chdir(root || '.') do\n paths.each do |pattern|\n Dir.glob(pattern) do |file|\n raise UnsupportedConfigType unless ['.yml', '.yaml', '.erb'].include?(File.extname(file))\n\n logger.info \"loading config file '#{file}'\" if logging? && respond_to?(:logger)\n document = ERB.new(File.read(file)).result\n yaml = YAML.respond_to?(:unsafe_load) ? YAML.unsafe_load(document) : YAML.load(document)\n config = config_for_env(yaml)\n config.each_pair { |key, value| set(key, value) }\n end\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":134,"symbol":"UnsupportedConfigType","kind":"class","lang":"ruby","code":"class UnsupportedConfigType < StandardError\n def message\n 'Invalid config file type, use .yml, .yaml or .erb'\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":135,"symbol":"message","kind":"method","lang":"ruby","code":"def message\n 'Invalid config file type, use .yml, .yaml or .erb'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":145,"symbol":"config_for_env","kind":"method","lang":"ruby","doc":"Given a +hash+ containing application configuration it returns settings applicable to the current environment. Note: It gives precedence to environment settings defined at the root-level.","code":"def config_for_env(hash)\n return from_environment_key(hash) if environment_keys?(hash)\n\n hash.each_with_object(IndifferentHash[]) do |(k, v), acc|\n if environment_keys?(v)\n acc.merge!(k => v[environment.to_s]) if v.key?(environment.to_s)\n else\n acc.merge!(k => v)\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":159,"symbol":"from_environment_key","kind":"method","lang":"ruby","doc":"Given a +hash+ returns the settings corresponding to the current environment.","code":"def from_environment_key(hash)\n hash[environment.to_s] || hash[environment.to_sym] || {}\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/config_file.rb","line":165,"symbol":"environment_keys?","kind":"method","lang":"ruby","doc":"Returns true if supplied with a hash that has any recognized +environments+ in its root keys.","code":"def environment_keys?(hash)\n hash.is_a?(Hash) && hash.any? { |k, _| environments.include?(k.to_s) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/content_for.rb","line":6,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::ContentFor\n #\n # <tt>Sinatra::ContentFor</tt> is a set of helpers that allows you to capture\n # blocks inside views to be rendered later during the request. The most\n # common use is to populate different parts of your layout from your view.\n #\n # The currently supported engines are: Erb, Erubi, Haml and Slim.\n #\n # == Usage\n #\n # You call +content_for+, generally from a view, to capture a block of markup\n # giving it an identifier:\n #\n # # index.erb\n # <% content_for :some_key do %>\n # <chunk of=\"html\">...</chunk>\n # <% end %>\n #\n # Then, you call +yield_content+ with that identifier, generally from a\n # layout, to render the captured block:\n #\n # # layout.erb\n # <%= yield_content :some_key %>\n #\n # If you have provided +yield_content+ with a block and no content for the\n # specified key is found, it will render the results of the block provided\n # to yield_content.\n #\n # # layout.erb\n # <% yield_content :some_key_with_no_content do %>\n # <chunk of=\"default html\">...</chunk>\n # <% end %>\n #\n # === Classic Application\n #\n # To use the helpers in a classic application all you"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/content_for.rb","line":112,"symbol":"ContentFor","kind":"module","lang":"ruby","doc":"# body.erb # Display both alerts <%= yield %> <%= yield_content :one %> <%= yield_content :two %>","code":"module ContentFor\n include Capture\n\n # Capture a block of content to be rendered later. For example:\n #\n # <% content_for :head do %>\n # <script type=\"text/javascript\" src=\"/foo.js\"></script>\n # <% end %>\n #\n # You can also pass an immediate value instead of a block:\n #\n # <% content_for :title, \"foo\" %>\n #\n # You can call +content_for+ multiple times with the same key\n # (in the example +:head+), and when you render the blocks for\n # that key all of them will be rendered, in the same order you\n # captured them.\n #\n # Your blocks can also receive values, which are passed to them\n # by <tt>yield_content</tt>\n def content_for(key, value = nil, options = {}, &block)\n block ||= proc { |*| value }\n clear_content_for(key) if options[:flush]\n content_blocks[key.to_sym] << capture_later(&block)\n end\n\n # Check if a block of content with the given key was defined. For\n # example:\n #\n # <% content_for :head do %>\n # <script type=\"text/javascript\" src=\"/foo.js\"></script>\n # <% end %>\n #\n # <% if content_for? :head %>\n # <span>content \"head\" was defined"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/content_for.rb","line":132,"symbol":"content_for","kind":"method","lang":"ruby","doc":"(in the example +:head+), and when you render the blocks for that key all of them will be rendered, in the same order you captured them. Your blocks can also receive values, which are passed to them by <tt>yield_content</tt>","code":"def content_for(key, value = nil, options = {}, &block)\n block ||= proc { |*| value }\n clear_content_for(key) if options[:flush]\n content_blocks[key.to_sym] << capture_later(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/content_for.rb","line":148,"symbol":"content_for?","kind":"method","lang":"ruby","doc":"<script type=\"text/javascript\" src=\"/foo.js\"></script> <% end %> <% if content_for? :head %> <span>content \"head\" was defined.</span> <% end %>","code":"def content_for?(key)\n content_blocks[key.to_sym].any?\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/content_for.rb","line":155,"symbol":"clear_content_for","kind":"method","lang":"ruby","doc":"Unset a named block of content. For example: <% clear_content_for :head %>","code":"def clear_content_for(key)\n content_blocks.delete(key.to_sym) if content_for?(key)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/content_for.rb","line":176,"symbol":"yield_content","kind":"method","lang":"ruby","doc":"as arguments after the key: <%= yield_content :head, 1, 2 %> Would pass <tt>1</tt> and <tt>2</tt> to all the blocks registered for <tt>:head</tt>.","code":"def yield_content(key, *args, &block)\n if block_given? && !content_for?(key)\n haml? && Tilt[:haml] == Tilt::HamlTemplate && respond_to?(:capture_haml) ? capture_haml(*args, &block) : yield(*args)\n else\n content = content_blocks[key.to_sym].map { |b| capture(*args, &b) }\n content.join.tap do |c|\n if block_given? && (erb? || erubi?)\n @_out_buf << c\n end\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/content_for.rb","line":191,"symbol":"content_blocks","kind":"method","lang":"ruby","code":"def content_blocks\n @content_blocks ||= Hash.new { |h, k| h[k] = [] }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":6,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n module Contrib\n module Loader\n def extensions\n @extensions ||= { helpers: [], register: [] }\n end\n\n def register(name, path)\n autoload name, path, :register\n end\n\n def helpers(name, path)\n autoload name, path, :helpers\n end\n\n def autoload(name, path, method = nil)\n extensions[method] << name if method\n Sinatra.autoload(name, path)\n end\n\n def registered(base)\n @extensions.each do |method, list|\n list = list.map { |name| Sinatra.const_get name }\n base.send(method, *list) unless base == ::Sinatra::Application\n end\n end\n end\n\n module Common\n extend Loader\n end\n\n module Custom\n extend Loader\n end\n\n module All\n def self.registered(base)\n base.register Common, Custom\n end\n end\n\n extend Loader\n def self.registered(base)\n base.register Common, Custom\n end\n end\nend"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":7,"symbol":"Contrib","kind":"module","lang":"ruby","code":"module Contrib\n module Loader\n def extensions\n @extensions ||= { helpers: [], register: [] }\n end\n\n def register(name, path)\n autoload name, path, :register\n end\n\n def helpers(name, path)\n autoload name, path, :helpers\n end\n\n def autoload(name, path, method = nil)\n extensions[method] << name if method\n Sinatra.autoload(name, path)\n end\n\n def registered(base)\n @extensions.each do |method, list|\n list = list.map { |name| Sinatra.const_get name }\n base.send(method, *list) unless base == ::Sinatra::Application\n end\n end\n end\n\n module Common\n extend Loader\n end\n\n module Custom\n extend Loader\n end\n\n module All\n def self.registered(base)\n base.register Common, Custom\n end\n end\n\n extend Loader\n def self.registered(base)\n base.register Common, Custom\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":8,"symbol":"Loader","kind":"module","lang":"ruby","code":"module Loader\n def extensions\n @extensions ||= { helpers: [], register: [] }\n end\n\n def register(name, path)\n autoload name, path, :register\n end\n\n def helpers(name, path)\n autoload name, path, :helpers\n end\n\n def autoload(name, path, method = nil)\n extensions[method] << name if method\n Sinatra.autoload(name, path)\n end\n\n def registered(base)\n @extensions.each do |method, list|\n list = list.map { |name| Sinatra.const_get name }\n base.send(method, *list) unless base == ::Sinatra::Application\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":9,"symbol":"extensions","kind":"method","lang":"ruby","code":"def extensions\n @extensions ||= { helpers: [], register: [] }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":13,"symbol":"register","kind":"method","lang":"ruby","code":"def register(name, path)\n autoload name, path, :register\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":17,"symbol":"helpers","kind":"method","lang":"ruby","code":"def helpers(name, path)\n autoload name, path, :helpers\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":21,"symbol":"autoload","kind":"method","lang":"ruby","code":"def autoload(name, path, method = nil)\n extensions[method] << name if method\n Sinatra.autoload(name, path)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":26,"symbol":"registered","kind":"method","lang":"ruby","code":"def registered(base)\n @extensions.each do |method, list|\n list = list.map { |name| Sinatra.const_get name }\n base.send(method, *list) unless base == ::Sinatra::Application\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":34,"symbol":"Common","kind":"module","lang":"ruby","code":"module Common\n extend Loader\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":38,"symbol":"Custom","kind":"module","lang":"ruby","code":"module Custom\n extend Loader\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":42,"symbol":"All","kind":"module","lang":"ruby","code":"module All\n def self.registered(base)\n base.register Common, Custom\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":43,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(base)\n base.register Common, Custom\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/setup.rb","line":49,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(base)\n base.register Common, Custom\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/version.rb","line":3,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n module Contrib\n VERSION = '4.2.1'\n end\nend"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib/version.rb","line":4,"symbol":"Contrib","kind":"module","lang":"ruby","code":"module Contrib\n VERSION = '4.2.1'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n module Contrib\n ##\n # Common middleware that doesn't bring run time overhead if not used\n # or breaks if external dependencies are missing. Will extend\n # Sinatra::Application by default.\n module Common\n register :ConfigFile, 'sinatra/config_file'\n register :MultiRoute, 'sinatra/multi_route'\n register :Namespace, 'sinatra/namespace'\n register :RespondWith, 'sinatra/respond_with'\n\n helpers :Capture, 'sinatra/capture'\n helpers :ContentFor, 'sinatra/content_for'\n helpers :Cookies, 'sinatra/cookies'\n helpers :EngineTracking, 'sinatra/engine_tracking'\n helpers :JSON, 'sinatra/json'\n helpers :LinkHeader, 'sinatra/link_header'\n helpers :Streaming, 'sinatra/streaming'\n helpers :RequiredParams, 'sinatra/required_params'\n end\n\n ##\n # Other extensions you don't want to be loaded unless needed.\n module Custom\n register :Reloader, 'sinatra/reloader'\n\n helpers :HamlHelpers, 'sinatra/haml_helpers'\n end\n\n ##\n # Stuff that aren't Sinatra extensions, technically.\n autoload :Extension, 'sinatra/extension'\n autoload :TestHelpers, 'sinatra/test_helpers'\n end\n\n register Sina"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib.rb","line":6,"symbol":"Contrib","kind":"module","lang":"ruby","code":"module Contrib\n ##\n # Common middleware that doesn't bring run time overhead if not used\n # or breaks if external dependencies are missing. Will extend\n # Sinatra::Application by default.\n module Common\n register :ConfigFile, 'sinatra/config_file'\n register :MultiRoute, 'sinatra/multi_route'\n register :Namespace, 'sinatra/namespace'\n register :RespondWith, 'sinatra/respond_with'\n\n helpers :Capture, 'sinatra/capture'\n helpers :ContentFor, 'sinatra/content_for'\n helpers :Cookies, 'sinatra/cookies'\n helpers :EngineTracking, 'sinatra/engine_tracking'\n helpers :JSON, 'sinatra/json'\n helpers :LinkHeader, 'sinatra/link_header'\n helpers :Streaming, 'sinatra/streaming'\n helpers :RequiredParams, 'sinatra/required_params'\n end\n\n ##\n # Other extensions you don't want to be loaded unless needed.\n module Custom\n register :Reloader, 'sinatra/reloader'\n\n helpers :HamlHelpers, 'sinatra/haml_helpers'\n end\n\n ##\n # Stuff that aren't Sinatra extensions, technically.\n autoload :Extension, 'sinatra/extension'\n autoload :TestHelpers, 'sinatra/test_helpers'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib.rb","line":11,"symbol":"Common","kind":"module","lang":"ruby","doc":"# Common middleware that doesn't bring run time overhead if not used or breaks if external dependencies are missing. Will extend Sinatra::Application by default.","code":"module Common\n register :ConfigFile, 'sinatra/config_file'\n register :MultiRoute, 'sinatra/multi_route'\n register :Namespace, 'sinatra/namespace'\n register :RespondWith, 'sinatra/respond_with'\n\n helpers :Capture, 'sinatra/capture'\n helpers :ContentFor, 'sinatra/content_for'\n helpers :Cookies, 'sinatra/cookies'\n helpers :EngineTracking, 'sinatra/engine_tracking'\n helpers :JSON, 'sinatra/json'\n helpers :LinkHeader, 'sinatra/link_header'\n helpers :Streaming, 'sinatra/streaming'\n helpers :RequiredParams, 'sinatra/required_params'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/contrib.rb","line":29,"symbol":"Custom","kind":"module","lang":"ruby","doc":"# Other extensions you don't want to be loaded unless needed.","code":"module Custom\n register :Reloader, 'sinatra/reloader'\n\n helpers :HamlHelpers, 'sinatra/haml_helpers'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::Cookies\n #\n # Easy way to deal with cookies\n #\n # == Usage\n #\n # Allows you to read cookies:\n #\n # get '/' do\n # \"value: #{cookies[:something]}\"\n # end\n #\n # And of course to write cookies:\n #\n # get '/set' do\n # cookies[:something] = 'foobar'\n # redirect to('/')\n # end\n #\n # And generally behaves like a hash:\n #\n # get '/demo' do\n # cookies.merge! 'foo' => 'bar', 'bar' => 'baz'\n # cookies.keep_if { |key, value| key.start_with? 'b' }\n # foo, bar = cookies.values_at 'foo', 'bar'\n # \"size: #{cookies.length}\"\n # end\n #\n # === Classic Application\n #\n # In a classic application simply require the helpers, and start using them:\n #\n # require \"sinatra\"\n # require \"sinatra/cookies\"\n #\n # # The rest of your classic application code goes here...\n #\n # === Modular Application\n #\n # In a modular application you need to require the helpers, and then tell\n # the application to use them:\n #\n # require \"sinatra/base\"\n # require \"sinatra/cookies\"\n #\n # class MyApp < Sinatra::Base\n # helpers Sinatra::Cookies\n #\n # # The rest of your modular applica"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":57,"symbol":"Cookies","kind":"module","lang":"ruby","doc":"class MyApp < Sinatra::Base helpers Sinatra::Cookies # The rest of your modular application code goes here... end","code":"module Cookies\n class Jar\n include Enumerable\n attr_reader :options\n\n def initialize(app)\n @response_array = nil\n @response_hash = {}\n @response = app.response\n @request = app.request\n @deleted = []\n\n @options = {\n path: @request.script_name.to_s.empty? ? '/' : @request.script_name,\n domain: @request.host == 'localhost' ? nil : @request.host,\n secure: @request.secure?,\n httponly: true\n }\n\n return unless app.settings.respond_to? :cookie_options\n\n @options.merge! app.settings.cookie_options\n end\n\n def ==(other)\n other.respond_to? :to_hash and to_hash == other.to_hash\n end\n\n def [](key)\n response_cookies[key.to_s] || request_cookies[key.to_s]\n end\n\n def []=(key, value)\n set(key, value: value)\n end\n\n if Hash.method_defined? :assoc\n def assoc(key)\n to_hash.assoc(key.to_s)\n end\n end\n\n def clear\n each_key { |k| delete(k) }\n end\n\n def compare_by_identity?\n false\n end\n\n def default\n nil\n end\n\n alias default_"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":58,"symbol":"Jar","kind":"class","lang":"ruby","code":"class Jar\n include Enumerable\n attr_reader :options\n\n def initialize(app)\n @response_array = nil\n @response_hash = {}\n @response = app.response\n @request = app.request\n @deleted = []\n\n @options = {\n path: @request.script_name.to_s.empty? ? '/' : @request.script_name,\n domain: @request.host == 'localhost' ? nil : @request.host,\n secure: @request.secure?,\n httponly: true\n }\n\n return unless app.settings.respond_to? :cookie_options\n\n @options.merge! app.settings.cookie_options\n end\n\n def ==(other)\n other.respond_to? :to_hash and to_hash == other.to_hash\n end\n\n def [](key)\n response_cookies[key.to_s] || request_cookies[key.to_s]\n end\n\n def []=(key, value)\n set(key, value: value)\n end\n\n if Hash.method_defined? :assoc\n def assoc(key)\n to_hash.assoc(key.to_s)\n end\n end\n\n def clear\n each_key { |k| delete(k) }\n end\n\n def compare_by_identity?\n false\n end\n\n def default\n nil\n end\n\n alias default_proc default\n\n "}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":62,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app)\n @response_array = nil\n @response_hash = {}\n @response = app.response\n @request = app.request\n @deleted = []\n\n @options = {\n path: @request.script_name.to_s.empty? ? '/' : @request.script_name,\n domain: @request.host == 'localhost' ? nil : @request.host,\n secure: @request.secure?,\n httponly: true\n }\n\n return unless app.settings.respond_to? :cookie_options\n\n @options.merge! app.settings.cookie_options\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":94,"symbol":"assoc","kind":"method","lang":"ruby","code":"def assoc(key)\n to_hash.assoc(key.to_s)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":99,"symbol":"clear","kind":"method","lang":"ruby","code":"def clear\n each_key { |k| delete(k) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":103,"symbol":"compare_by_identity?","kind":"method","lang":"ruby","code":"def compare_by_identity?\n false\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":107,"symbol":"default","kind":"method","lang":"ruby","code":"def default\n nil\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":113,"symbol":"delete","kind":"method","lang":"ruby","code":"def delete(key)\n result = self[key]\n @response.delete_cookie(key.to_s, @options)\n result\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":119,"symbol":"delete_if","kind":"method","lang":"ruby","code":"def delete_if\n return enum_for(__method__) unless block_given?\n\n each { |k, v| delete(k) if yield(k, v) }\n self\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":126,"symbol":"each","kind":"method","lang":"ruby","code":"def each(&block)\n return enum_for(__method__) unless block_given?\n\n to_hash.each(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":132,"symbol":"each_key","kind":"method","lang":"ruby","code":"def each_key(&block)\n return enum_for(__method__) unless block_given?\n\n to_hash.each_key(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":140,"symbol":"each_value","kind":"method","lang":"ruby","code":"def each_value(&block)\n return enum_for(__method__) unless block_given?\n\n to_hash.each_value(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":146,"symbol":"empty?","kind":"method","lang":"ruby","code":"def empty?\n to_hash.empty?\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":150,"symbol":"fetch","kind":"method","lang":"ruby","code":"def fetch(key, &block)\n response_cookies.fetch(key.to_s) do\n request_cookies.fetch(key.to_s, &block)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":157,"symbol":"flatten","kind":"method","lang":"ruby","code":"def flatten\n to_hash.flatten\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":162,"symbol":"has_key?","kind":"method","lang":"ruby","code":"def has_key?(key)\n response_cookies.key? key.to_s or request_cookies.key? key.to_s\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":166,"symbol":"has_value?","kind":"method","lang":"ruby","code":"def has_value?(value)\n response_cookies.value? value or request_cookies.value? value\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":170,"symbol":"hash","kind":"method","lang":"ruby","code":"def hash\n to_hash.hash\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":177,"symbol":"inspect","kind":"method","lang":"ruby","code":"def inspect\n \"<##{self.class}: #{to_hash.inspect[1..-2]}>\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":182,"symbol":"invert","kind":"method","lang":"ruby","code":"def invert\n to_hash.invert\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":187,"symbol":"keep_if","kind":"method","lang":"ruby","code":"def keep_if\n return enum_for(__method__) unless block_given?\n\n delete_if { |*a| !yield(*a) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":193,"symbol":"key","kind":"method","lang":"ruby","code":"def key(value)\n to_hash.key(value)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":199,"symbol":"keys","kind":"method","lang":"ruby","code":"def keys\n to_hash.keys\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":203,"symbol":"length","kind":"method","lang":"ruby","code":"def length\n to_hash.length\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":207,"symbol":"merge","kind":"method","lang":"ruby","code":"def merge(other, &block)\n to_hash.merge(other, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":211,"symbol":"merge!","kind":"method","lang":"ruby","code":"def merge!(other)\n other.each_pair do |key, value|\n self[key] = if block_given? && include?(key)\n yield(key.to_s, self[key], value)\n else\n value\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":221,"symbol":"rassoc","kind":"method","lang":"ruby","code":"def rassoc(value)\n to_hash.rassoc(value)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":225,"symbol":"rehash","kind":"method","lang":"ruby","code":"def rehash\n response_cookies.rehash\n request_cookies.rehash\n self\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":231,"symbol":"reject","kind":"method","lang":"ruby","code":"def reject(&block)\n return enum_for(__method__) unless block_given?\n\n to_hash.reject(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":239,"symbol":"replace","kind":"method","lang":"ruby","code":"def replace(other)\n select! { |k, _v| other.include?(k) or other.include?(k.to_s) }\n merge! other\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":244,"symbol":"select","kind":"method","lang":"ruby","code":"def select(&block)\n return enum_for(__method__) unless block_given?\n\n to_hash.select(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":252,"symbol":"set","kind":"method","lang":"ruby","code":"def set(key, options = {})\n @response.set_cookie key.to_s, @options.merge(options)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":256,"symbol":"shift","kind":"method","lang":"ruby","code":"def shift\n key, value = to_hash.shift\n delete(key)\n [key, value]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":265,"symbol":"sort","kind":"method","lang":"ruby","code":"def sort(&block)\n to_hash.sort(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":272,"symbol":"to_hash","kind":"method","lang":"ruby","code":"def to_hash\n request_cookies.merge(response_cookies)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":276,"symbol":"to_a","kind":"method","lang":"ruby","code":"def to_a\n to_hash.to_a\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":280,"symbol":"to_s","kind":"method","lang":"ruby","code":"def to_s\n to_hash.to_s\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":287,"symbol":"values","kind":"method","lang":"ruby","code":"def values\n to_hash.values\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":291,"symbol":"values_at","kind":"method","lang":"ruby","code":"def values_at(*list)\n list.map { |k| self[k] }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":297,"symbol":"warn","kind":"method","lang":"ruby","code":"def warn(message)\n super \"#{caller.first[/^[^:]:\\d+:/]} warning: #{message}\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":301,"symbol":"deleted","kind":"method","lang":"ruby","code":"def deleted\n parse_response\n @deleted\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":306,"symbol":"response_cookies","kind":"method","lang":"ruby","code":"def response_cookies\n parse_response\n @response_hash\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":311,"symbol":"parse_response","kind":"method","lang":"ruby","code":"def parse_response\n cookies_from_response = Array(@response['Set-Cookie'])\n return if @response_array == cookies_from_response\n\n hash = {}\n\n cookies_from_response.each do |line|\n key, value = line.split(';', 2).first.to_s.split('=', 2)\n next if key.nil?\n\n key = Rack::Utils.unescape(key)\n if line =~ /expires=Thu, 01[-\\s]Jan[-\\s]1970/\n @deleted << key\n else\n @deleted.delete key\n hash[key] = value\n end\n end\n\n @response_hash.replace hash\n @response_array = cookies_from_response\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":334,"symbol":"request_cookies","kind":"method","lang":"ruby","code":"def request_cookies\n @request.cookies.reject { |key, _value| deleted.include? key }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/cookies.rb","line":339,"symbol":"cookies","kind":"method","lang":"ruby","code":"def cookies\n @cookies ||= Jar.new(self)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/custom_logger.rb","line":3,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::CustomLogger\n #\n # CustomLogger extension allows you to define your own logger instance\n # using +logger+ setting. That logger then will be available\n # as #logger helper method in your routes and views.\n #\n # == Usage\n #\n # === Classic Application\n #\n # To define your custom logger instance in a classic application:\n #\n # require 'sinatra'\n # require 'sinatra/custom_logger'\n # require 'logger'\n #\n # set :logger, Logger.new(STDOUT)\n #\n # get '/' do\n # logger.info 'Some message' # STDOUT logger is used\n # # Other code...\n # end\n #\n # === Modular Application\n #\n # The same for modular application:\n #\n # require 'sinatra/base'\n # require 'sinatra/custom_logger'\n # require 'logger'\n #\n # class MyApp < Sinatra::Base\n # helpers Sinatra::CustomLogger\n #\n # configure :development, :production do\n # logger = Logger.new(File.open(\"#{root}/log/#{environment}.log\", 'a'))\n # logger.level = Logger::DEBUG if development?\n # set :logger, logger\n # end\n #\n # get '/' do\n # logger.info 'Some message' # File-based logger is u"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/custom_logger.rb","line":50,"symbol":"CustomLogger","kind":"module","lang":"ruby","doc":"get '/' do logger.info 'Some message' # File-based logger is used # Other code... end end","code":"module CustomLogger\n def logger\n if settings.respond_to?(:logger)\n settings.logger\n else\n request.logger\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/custom_logger.rb","line":51,"symbol":"logger","kind":"method","lang":"ruby","code":"def logger\n if settings.respond_to?(:logger)\n settings.logger\n else\n request.logger\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # Adds methods like `haml?` that allow helper methods to check whether they\n # are called from within a template.\n module EngineTracking\n attr_reader :current_engine\n\n # @return [Boolean] Returns true if current engine is `:erb`.\n def erb?\n @current_engine == :erb\n end\n\n # Returns true if the current engine is `:erubi`, or `Tilt[:erb]` is set\n # to Tilt::ErubiTemplate.\n #\n # @return [Boolean] Returns true if current engine is `:erubi`.\n def erubi?\n @current_engine == :erubi or\n (erb? && Tilt[:erb] == Tilt::ErubiTemplate)\n end\n\n # @return [Boolean] Returns true if current engine is `:haml`.\n def haml?\n @current_engine == :haml\n end\n\n # @return [Boolean] Returns true if current engine is `:sass`.\n def sass?\n @current_engine == :sass\n end\n\n # @return [Boolean] Returns true if current engine is `:scss`.\n def scss?\n @current_engine == :scss\n end\n\n # @return [Boolean] Returns true if current engine is `:builder`.\n def builder?\n @current_engine == :builder\n end\n\n # @return [Boolean] Returns true if current engine is `:liquid`.\n def liquid?\n @current_engine ="}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":8,"symbol":"EngineTracking","kind":"module","lang":"ruby","doc":"Adds methods like `haml?` that allow helper methods to check whether they are called from within a template.","code":"module EngineTracking\n attr_reader :current_engine\n\n # @return [Boolean] Returns true if current engine is `:erb`.\n def erb?\n @current_engine == :erb\n end\n\n # Returns true if the current engine is `:erubi`, or `Tilt[:erb]` is set\n # to Tilt::ErubiTemplate.\n #\n # @return [Boolean] Returns true if current engine is `:erubi`.\n def erubi?\n @current_engine == :erubi or\n (erb? && Tilt[:erb] == Tilt::ErubiTemplate)\n end\n\n # @return [Boolean] Returns true if current engine is `:haml`.\n def haml?\n @current_engine == :haml\n end\n\n # @return [Boolean] Returns true if current engine is `:sass`.\n def sass?\n @current_engine == :sass\n end\n\n # @return [Boolean] Returns true if current engine is `:scss`.\n def scss?\n @current_engine == :scss\n end\n\n # @return [Boolean] Returns true if current engine is `:builder`.\n def builder?\n @current_engine == :builder\n end\n\n # @return [Boolean] Returns true if current engine is `:liquid`.\n def liquid?\n @current_engine == :liquid\n end\n\n # @return [Boolean] Returns true if current engine is `:markdown`.\n def markdown?\n @current_engine == :"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":12,"symbol":"erb?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:erb`.","code":"def erb?\n @current_engine == :erb\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":20,"symbol":"erubi?","kind":"method","lang":"ruby","doc":"Returns true if the current engine is `:erubi`, or `Tilt[:erb]` is set to Tilt::ErubiTemplate. @return [Boolean] Returns true if current engine is `:erubi`.","code":"def erubi?\n @current_engine == :erubi or\n (erb? && Tilt[:erb] == Tilt::ErubiTemplate)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":26,"symbol":"haml?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:haml`.","code":"def haml?\n @current_engine == :haml\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":31,"symbol":"sass?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:sass`.","code":"def sass?\n @current_engine == :sass\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":36,"symbol":"scss?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:scss`.","code":"def scss?\n @current_engine == :scss\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":41,"symbol":"builder?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:builder`.","code":"def builder?\n @current_engine == :builder\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":46,"symbol":"liquid?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:liquid`.","code":"def liquid?\n @current_engine == :liquid\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":51,"symbol":"markdown?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:markdown`.","code":"def markdown?\n @current_engine == :markdown\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":56,"symbol":"rdoc?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:rdoc`.","code":"def rdoc?\n @current_engine == :rdoc\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":61,"symbol":"markaby?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:markaby`.","code":"def markaby?\n @current_engine == :markaby\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":66,"symbol":"nokogiri?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:nokogiri`.","code":"def nokogiri?\n @current_engine == :nokogiri\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":71,"symbol":"slim?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:slim`.","code":"def slim?\n @current_engine == :slim\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":76,"symbol":"ruby?","kind":"method","lang":"ruby","doc":"@return [Boolean] Returns true if current engine is `:ruby`.","code":"def ruby?\n @current_engine == :ruby\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":80,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(*)\n @current_engine = :ruby\n super\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":86,"symbol":"with_engine","kind":"method","lang":"ruby","doc":"@param engine [Symbol, String] Name of Engine to shift to.","code":"def with_engine(engine)\n engine_was = @current_engine\n @current_engine = engine.to_sym\n yield\n ensure\n @current_engine = engine_was\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/engine_tracking.rb","line":96,"symbol":"render","kind":"method","lang":"ruby","code":"def render(engine, *)\n with_engine(engine) { super }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::Extension\n #\n # <tt>Sinatra::Extension</tt> is a mixin that provides some syntactic sugar\n # for your extensions. It allows you to call almost any\n # <tt>Sinatra::Base</tt> method directly inside your extension\n # module. This means you can use +get+ to define a route, +before+\n # to define a before filter, +set+ to define a setting and so on.\n #\n # Is important to be aware that this mixin remembers the method calls you\n # make, and then, when your extension is registered, replays them on the\n # Sinatra application that has been extended. In order to do that, it\n # defines a <tt>registered</tt> method, so, if your extension defines one\n # too, remember to call +super+.\n #\n # == Usage\n #\n # Just require the mixin and extend your extension with it:\n #\n # require 'sinatra/extension'\n #\n # module MyExtension\n # extend Sinatra::Extension\n #\n # # set some settings for development\n # configure :development do\n # set :reload_stuff, true\n # end\n #\n # # define a route\n # get '/' do\n # 'Hello World'\n # end\n #\n # # The rest of your extension code goes here...\n"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":50,"symbol":"Extension","kind":"module","lang":"ruby","doc":"MyExtension = Sinatra::Extension.new do # Your extension code goes here... end This is useful when you just want to pass a block to <tt>Sinatra::Base.register</tt>.","code":"module Extension\n def self.new(&block)\n ext = Module.new.extend(self)\n ext.class_eval(&block)\n ext\n end\n\n def settings\n self\n end\n\n def configure(*args, &block)\n record(:configure, *args) { |c| c.instance_exec(c, &block) }\n end\n\n def registered(base = nil, &block)\n base ? replay(base) : record(:class_eval, &block)\n end\n\n private\n\n def record(method, *args, &block)\n recorded_methods << [method, args, block]\n end\n\n def replay(object)\n recorded_methods.each { |m, a, b| object.send(m, *a, &b) }\n end\n\n def recorded_methods\n @recorded_methods ||= []\n end\n\n def method_missing(method, *args, &block)\n return super unless Sinatra::Base.respond_to? method\n\n record(method, *args, &block)\n DontCall.new(method)\n end\n\n class DontCall < BasicObject\n def initialize(method) @method = method end\n def method_missing(*) raise \"not supposed to use result of #{@method}!\" end\n def inspect; \"#<#{self.class}: #{@method}>\" end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":51,"symbol":"new","kind":"method","lang":"ruby","code":"def self.new(&block)\n ext = Module.new.extend(self)\n ext.class_eval(&block)\n ext\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":57,"symbol":"settings","kind":"method","lang":"ruby","code":"def settings\n self\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":61,"symbol":"configure","kind":"method","lang":"ruby","code":"def configure(*args, &block)\n record(:configure, *args) { |c| c.instance_exec(c, &block) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":65,"symbol":"registered","kind":"method","lang":"ruby","code":"def registered(base = nil, &block)\n base ? replay(base) : record(:class_eval, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":71,"symbol":"record","kind":"method","lang":"ruby","code":"def record(method, *args, &block)\n recorded_methods << [method, args, block]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":75,"symbol":"replay","kind":"method","lang":"ruby","code":"def replay(object)\n recorded_methods.each { |m, a, b| object.send(m, *a, &b) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":79,"symbol":"recorded_methods","kind":"method","lang":"ruby","code":"def recorded_methods\n @recorded_methods ||= []\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":83,"symbol":"method_missing","kind":"method","lang":"ruby","code":"def method_missing(method, *args, &block)\n return super unless Sinatra::Base.respond_to? method\n\n record(method, *args, &block)\n DontCall.new(method)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":90,"symbol":"DontCall","kind":"class","lang":"ruby","code":"class DontCall < BasicObject\n def initialize(method) @method = method end\n def method_missing(*) raise \"not supposed to use result of #{@method}!\" end\n def inspect; \"#<#{self.class}: #{@method}>\" end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":91,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(method) @method = method end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":92,"symbol":"method_missing","kind":"method","lang":"ruby","code":"def method_missing(*) raise \"not supposed to use result of #{@method}!\" end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/extension.rb","line":93,"symbol":"inspect","kind":"method","lang":"ruby","code":"def inspect; \"#<#{self.class}: #{@method}>\" end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/haml_helpers.rb","line":6,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::HamlHelpers\n #\n # This extension provides some of the helper methods that existed in Haml 5\n # but were removed in Haml 6. To use this in your app, just +register+ it:\n #\n # require 'sinatra/base'\n # require 'sinatra/haml_helpers'\n #\n # class Application < Sinatra::Base\n # helpers Sinatra::HamlHelpers\n #\n # # now you can use the helpers in your views\n # get '/' do\n # haml_code = <<~HAML\n # %p\n # != surround \"(\", \")\" do\n # %a{ href: \"https://example.org/\" } example.org\n # HAML\n # haml haml_code\n # end\n # end\n #\n module HamlHelpers\n include Sinatra::Capture\n\n def surround(front, back = front, &block)\n \"#{front}#{_capture_haml(&block).chomp}#{back}\\n\"\n end\n\n def precede(str, &block)\n \"#{str}#{_capture_haml(&block).chomp}\\n\"\n end\n\n def succeed(str, &block)\n \"#{_capture_haml(&block).chomp}#{str}\\n\"\n end\n\n def _capture_haml(*args, &block)\n capture(*args, &block)\n end\n end\n\n helpers HamlHelpers\nend"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/haml_helpers.rb","line":29,"symbol":"HamlHelpers","kind":"module","lang":"ruby","doc":"%a{ href: \"https://example.org/\" } example.org HAML haml haml_code end end","code":"module HamlHelpers\n include Sinatra::Capture\n\n def surround(front, back = front, &block)\n \"#{front}#{_capture_haml(&block).chomp}#{back}\\n\"\n end\n\n def precede(str, &block)\n \"#{str}#{_capture_haml(&block).chomp}\\n\"\n end\n\n def succeed(str, &block)\n \"#{_capture_haml(&block).chomp}#{str}\\n\"\n end\n\n def _capture_haml(*args, &block)\n capture(*args, &block)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/haml_helpers.rb","line":32,"symbol":"surround","kind":"method","lang":"ruby","code":"def surround(front, back = front, &block)\n \"#{front}#{_capture_haml(&block).chomp}#{back}\\n\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/haml_helpers.rb","line":36,"symbol":"precede","kind":"method","lang":"ruby","code":"def precede(str, &block)\n \"#{str}#{_capture_haml(&block).chomp}\\n\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/haml_helpers.rb","line":40,"symbol":"succeed","kind":"method","lang":"ruby","code":"def succeed(str, &block)\n \"#{_capture_haml(&block).chomp}#{str}\\n\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/haml_helpers.rb","line":44,"symbol":"_capture_haml","kind":"method","lang":"ruby","code":"def _capture_haml(*args, &block)\n capture(*args, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/json.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::JSON\n #\n # <tt>Sinatra::JSON</tt> adds a helper method, called +json+, for (obviously)\n # json generation.\n #\n # == Usage\n #\n # === Classic Application\n #\n # In a classic application simply require the helper, and start using it:\n #\n # require \"sinatra\"\n # require \"sinatra/json\"\n #\n # # define a route that uses the helper\n # get '/' do\n # json :foo => 'bar'\n # end\n #\n # # The rest of your classic application code goes here...\n #\n # === Modular Application\n #\n # In a modular application you need to require the helper, and then tell the\n # application you will use it:\n #\n # require \"sinatra/base\"\n # require \"sinatra/json\"\n #\n # class MyApp < Sinatra::Base\n #\n # # define a route that uses the helper\n # get '/' do\n # json :foo => 'bar'\n # end\n #\n # # The rest of your modular application code goes here...\n # end\n #\n # === Encoders\n #\n # By default it will try to call +to_json+ on the object, but if it doesn't\n # respond to that message, it will use its own rather simple encoder. You can\n # easily change that anyways. To use +JSON+, simpl"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/json.rb","line":90,"symbol":"JSON","kind":"module","lang":"ruby","doc":"respectively. You can also pass those to the json method: get '/' do json({:foo => 'bar'}, :encoder => :to_json, :content_type => :js) end","code":"module JSON\n class << self\n def encode(object)\n ::MultiJson.dump(object)\n end\n end\n\n def json(object, options = {})\n content_type resolve_content_type(options)\n resolve_encoder_action object, resolve_encoder(options)\n end\n\n private\n\n def resolve_content_type(options = {})\n options[:content_type] || settings.json_content_type\n end\n\n def resolve_encoder(options = {})\n options[:json_encoder] || settings.json_encoder\n end\n\n def resolve_encoder_action(object, encoder)\n %i[encode generate].each do |method|\n return encoder.send(method, object) if encoder.respond_to? method\n end\n raise \"#{encoder} does not respond to #generate nor #encode\" unless encoder.is_a? Symbol\n\n object.__send__(encoder)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/json.rb","line":92,"symbol":"encode","kind":"method","lang":"ruby","code":"def encode(object)\n ::MultiJson.dump(object)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/json.rb","line":97,"symbol":"json","kind":"method","lang":"ruby","code":"def json(object, options = {})\n content_type resolve_content_type(options)\n resolve_encoder_action object, resolve_encoder(options)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/json.rb","line":104,"symbol":"resolve_content_type","kind":"method","lang":"ruby","code":"def resolve_content_type(options = {})\n options[:content_type] || settings.json_content_type\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/json.rb","line":108,"symbol":"resolve_encoder","kind":"method","lang":"ruby","code":"def resolve_encoder(options = {})\n options[:json_encoder] || settings.json_encoder\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/json.rb","line":112,"symbol":"resolve_encoder_action","kind":"method","lang":"ruby","code":"def resolve_encoder_action(object, encoder)\n %i[encode generate].each do |method|\n return encoder.send(method, object) if encoder.respond_to? method\n end\n raise \"#{encoder} does not respond to #generate nor #encode\" unless encoder.is_a? Symbol\n\n object.__send__(encoder)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/link_header.rb","line":3,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::LinkHeader\n #\n # <tt>Sinatra::LinkHeader</tt> adds a set of helper methods to generate link\n # HTML tags and their corresponding Link HTTP headers.\n #\n # == Usage\n #\n # Once you had set up the helpers in your application (see below), you will\n # be able to call the following methods from inside your route handlers,\n # filters and templates:\n #\n # +prefetch+::\n # Sets the Link HTTP headers and returns HTML tags to prefetch the given\n # resources.\n #\n # +stylesheet+::\n # Sets the Link HTTP headers and returns HTML tags to use the given\n # stylesheets.\n #\n # +link+::\n # Sets the Link HTTP headers and returns the corresponding HTML tags\n # for the given resources.\n #\n # +link_headers+::\n # Returns the corresponding HTML tags for the current Link HTTP headers.\n #\n # === Classic Application\n #\n # In a classic application simply require the helpers, and start using them:\n #\n # require \"sinatra\"\n # require \"sinatra/link_header\"\n #\n # # The rest of your classic application code goes here...\n #\n # === Modular Application\n #\n # In a modular application you need to require the helpers, an"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/link_header.rb","line":53,"symbol":"LinkHeader","kind":"module","lang":"ruby","doc":"class MyApp < Sinatra::Base helpers Sinatra::LinkHeader # The rest of your modular application code goes here... end","code":"module LinkHeader\n ##\n # Sets Link HTTP header and returns HTML tags for telling the browser to\n # prefetch given resources (only supported by Opera and Firefox at the\n # moment).\n def prefetch(*urls)\n link(:prefetch, *urls)\n end\n\n ##\n # Sets Link HTTP header and returns HTML tags for using stylesheets.\n def stylesheet(*urls)\n urls << {} unless urls.last.respond_to? :to_hash\n urls.last[:type] ||= mime_type(:css)\n link(:stylesheet, *urls)\n end\n\n ##\n # Sets Link HTTP header and returns corresponding HTML tags.\n #\n # Example:\n #\n # # Sets header:\n # # Link: </foo>; rel=\"next\"\n # # Returns String:\n # # '<link href=\"/foo\" rel=\"next\" />'\n # link '/foo', :rel => :next\n #\n # # Multiple URLs\n # link :stylesheet, '/a.css', '/b.css'\n def link(*urls)\n opts = urls.last.respond_to?(:to_hash) ? urls.pop : {}\n opts[:rel] = urls.shift unless urls.first.respond_to? :to_str\n options = opts.map { |k, v| \" #{k}=#{v.to_s.inspect}\" }\n html_pattern = \"<link href=\\\"%s\\\"#{options.join} />\"\n http_pattern = ['<%s>', *options].join ';'\n link = "}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/link_header.rb","line":58,"symbol":"prefetch","kind":"method","lang":"ruby","doc":"# Sets Link HTTP header and returns HTML tags for telling the browser to prefetch given resources (only supported by Opera and Firefox at the moment).","code":"def prefetch(*urls)\n link(:prefetch, *urls)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/link_header.rb","line":64,"symbol":"stylesheet","kind":"method","lang":"ruby","doc":"# Sets Link HTTP header and returns HTML tags for using stylesheets.","code":"def stylesheet(*urls)\n urls << {} unless urls.last.respond_to? :to_hash\n urls.last[:type] ||= mime_type(:css)\n link(:stylesheet, *urls)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/link_header.rb","line":83,"symbol":"link","kind":"method","lang":"ruby","doc":"# Returns String: # '<link href=\"/foo\" rel=\"next\" />' link '/foo', :rel => :next # Multiple URLs link :stylesheet, '/a.css', '/b.css'","code":"def link(*urls)\n opts = urls.last.respond_to?(:to_hash) ? urls.pop : {}\n opts[:rel] = urls.shift unless urls.first.respond_to? :to_str\n options = opts.map { |k, v| \" #{k}=#{v.to_s.inspect}\" }\n html_pattern = \"<link href=\\\"%s\\\"#{options.join} />\"\n http_pattern = ['<%s>', *options].join ';'\n link = (response['Link'] ||= '')\n\n link = response['Link'] = +link\n\n urls.map do |url|\n link << \",\" unless link.empty?\n link << (http_pattern % url)\n html_pattern % url\n end.join\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/link_header.rb","line":118,"symbol":"link_headers","kind":"method","lang":"ruby","doc":"__END__ @@ layout %head= link_headers %body= yield","code":"def link_headers\n yield if block_given?\n return '' unless response.include? 'Link'\n\n response['Link'].split(\",\").map do |line|\n url, *opts = line.split(';').map(&:strip)\n \"<link href=\\\"#{url[1..-2]}\\\" #{opts.join ' '} />\"\n end.join\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/link_header.rb","line":128,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(_base)\n puts \"WARNING: #{self} is a helpers module, not an extension.\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::MultiRoute\n #\n # Create multiple routes with one statement.\n #\n # == Usage\n #\n # Use this extension to create a handler for multiple routes:\n #\n # get '/foo', '/bar' do\n # # ...\n # end\n #\n # Or for multiple verbs:\n #\n # route :get, :post, '/' do\n # # ...\n # end\n #\n # Or for multiple verbs and multiple routes:\n #\n # route :get, :post, ['/foo', '/bar'] do\n # # ...\n # end\n #\n # Or even for custom verbs:\n #\n # route 'LIST', '/' do\n # # ...\n # end\n #\n # === Classic Application\n #\n # To use the extension in a classic application all you need to do is require\n # it:\n #\n # require \"sinatra\"\n # require \"sinatra/multi_route\"\n #\n # # Your classic application code goes here...\n #\n # === Modular Application\n #\n # To use the extension in a modular application you need to require it, and\n # then, tell the application you will use it:\n #\n # require \"sinatra/base\"\n # require \"sinatra/multi_route\"\n #\n # class MyApp < Sinatra::Base\n # register Sinatra::MultiRoute\n #\n # # The rest of your modular application code goes here...\n # end\n #\n module Mult"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":60,"symbol":"MultiRoute","kind":"module","lang":"ruby","doc":"class MyApp < Sinatra::Base register Sinatra::MultiRoute # The rest of your modular application code goes here... end","code":"module MultiRoute\n def head(*args, &block) super(*route_args(args), &block) end\n def delete(*args, &block) super(*route_args(args), &block) end\n def get(*args, &block) super(*route_args(args), &block) end\n def options(*args, &block) super(*route_args(args), &block) end\n def patch(*args, &block) super(*route_args(args), &block) end\n def post(*args, &block) super(*route_args(args), &block) end\n def put(*args, &block) super(*route_args(args), &block) end\n\n def route(*args, &block)\n options = Hash === args.last ? args.pop : {}\n routes = [*args.pop]\n args.each do |verb|\n verb = verb.to_s.upcase if Symbol === verb\n routes.each do |route|\n super(verb, route, options, &block)\n end\n end\n end\n\n private\n\n def route_args(args)\n options = Hash === args.last ? args.pop : {}\n [args, options]\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":61,"symbol":"head","kind":"method","lang":"ruby","code":"def head(*args, &block) super(*route_args(args), &block) end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":62,"symbol":"delete","kind":"method","lang":"ruby","code":"def delete(*args, &block) super(*route_args(args), &block) end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":63,"symbol":"get","kind":"method","lang":"ruby","code":"def get(*args, &block) super(*route_args(args), &block) end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":64,"symbol":"options","kind":"method","lang":"ruby","code":"def options(*args, &block) super(*route_args(args), &block) end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":65,"symbol":"patch","kind":"method","lang":"ruby","code":"def patch(*args, &block) super(*route_args(args), &block) end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":66,"symbol":"post","kind":"method","lang":"ruby","code":"def post(*args, &block) super(*route_args(args), &block) end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":67,"symbol":"put","kind":"method","lang":"ruby","code":"def put(*args, &block) super(*route_args(args), &block) end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":69,"symbol":"route","kind":"method","lang":"ruby","code":"def route(*args, &block)\n options = Hash === args.last ? args.pop : {}\n routes = [*args.pop]\n args.each do |verb|\n verb = verb.to_s.upcase if Symbol === verb\n routes.each do |route|\n super(verb, route, options, &block)\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/multi_route.rb","line":82,"symbol":"route_args","kind":"method","lang":"ruby","code":"def route_args(args)\n options = Hash === args.last ? args.pop : {}\n [args, options]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":6,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::Namespace\n #\n # <tt>Sinatra::Namespace</tt> is an extension that adds namespaces to an\n # application. This namespaces will allow you to share a path prefix for the\n # routes within the namespace, and define filters, conditions and error\n # handlers exclusively for them. Besides that, you can also register helpers\n # and extensions that will be used only within the namespace.\n #\n # == Usage\n #\n # Once you have loaded the extension (see below), you can use the +namespace+\n # method to define namespaces in your application.\n #\n # You can define a namespace by a path prefix:\n #\n # namespace '/blog' do\n # get { haml :blog }\n # get '/:entry_permalink' do\n # @entry = Entry.find_by_permalink!(params[:entry_permalink])\n # haml :entry\n # end\n #\n # # More blog routes...\n # end\n #\n # by a condition:\n #\n # namespace :host_name => 'localhost' do\n # get('/admin/dashboard') { haml :dashboard }\n # get('/admin/login') { haml :login }\n #\n # # More admin routes...\n # end\n #\n # or both:\n #\n # namespace '/admin', :host_name => 'localhost' do\n # get"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":188,"symbol":"Namespace","kind":"module","lang":"ruby","doc":"Zomg::App.run! # Don't forget to start your app ;) Phew! That was a mouthful. I hope that helps you use `Sinatra::Namespace` in every way imaginable!","code":"module Namespace\n def self.new(base, pattern, conditions = {}, &block)\n Module.new do\n # quelch uninitialized variable warnings, since these get used by compile method.\n @pattern = nil\n @conditions = nil\n extend NamespacedMethods\n include InstanceMethods\n @base = base\n @extensions = []\n @errors = {}\n @pattern, @conditions = compile(pattern, conditions)\n @templates = Hash.new { |_h, k| @base.templates[k] }\n namespace = self\n before { extend(@namespace = namespace) }\n class_eval(&block)\n end\n end\n\n module InstanceMethods\n def settings\n @namespace\n end\n\n def template_cache\n super.fetch(:nested, @namespace) { TemplateCache.new }\n end\n\n def redirect_to(uri, *args)\n redirect(\"#{@namespace.pattern}#{uri}\", *args)\n end\n end\n\n module SharedMethods\n def namespace(pattern, conditions = {}, &block)\n Sinatra::Namespace.new(self, pattern, conditions, &block)\n end\n end\n\n module NamespacedMethods\n include SharedMethods\n attr_reader :base, :templates\n\n ALLOWED_ENGINES = %i[\n erb "}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":189,"symbol":"new","kind":"method","lang":"ruby","code":"def self.new(base, pattern, conditions = {}, &block)\n Module.new do\n # quelch uninitialized variable warnings, since these get used by compile method.\n @pattern = nil\n @conditions = nil\n extend NamespacedMethods\n include InstanceMethods\n @base = base\n @extensions = []\n @errors = {}\n @pattern, @conditions = compile(pattern, conditions)\n @templates = Hash.new { |_h, k| @base.templates[k] }\n namespace = self\n before { extend(@namespace = namespace) }\n class_eval(&block)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":207,"symbol":"InstanceMethods","kind":"module","lang":"ruby","code":"module InstanceMethods\n def settings\n @namespace\n end\n\n def template_cache\n super.fetch(:nested, @namespace) { TemplateCache.new }\n end\n\n def redirect_to(uri, *args)\n redirect(\"#{@namespace.pattern}#{uri}\", *args)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":208,"symbol":"settings","kind":"method","lang":"ruby","code":"def settings\n @namespace\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":212,"symbol":"template_cache","kind":"method","lang":"ruby","code":"def template_cache\n super.fetch(:nested, @namespace) { TemplateCache.new }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":216,"symbol":"redirect_to","kind":"method","lang":"ruby","code":"def redirect_to(uri, *args)\n redirect(\"#{@namespace.pattern}#{uri}\", *args)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":221,"symbol":"SharedMethods","kind":"module","lang":"ruby","code":"module SharedMethods\n def namespace(pattern, conditions = {}, &block)\n Sinatra::Namespace.new(self, pattern, conditions, &block)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":222,"symbol":"namespace","kind":"method","lang":"ruby","code":"def namespace(pattern, conditions = {}, &block)\n Sinatra::Namespace.new(self, pattern, conditions, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":227,"symbol":"NamespacedMethods","kind":"module","lang":"ruby","code":"module NamespacedMethods\n include SharedMethods\n attr_reader :base, :templates\n\n ALLOWED_ENGINES = %i[\n erb erubi haml hamlit builder nokogiri sass scss\n liquid markdown rdoc asciidoc markaby\n rabl slim yajl\n ]\n\n def self.prefixed(*names)\n names.each { |n| define_method(n) { |*a, &b| prefixed(n, *a, &b) } }\n end\n\n prefixed :before, :after, :delete, :get, :head, :options, :patch, :post, :put\n\n def helpers(*extensions, &block)\n class_eval(&block) if block_given?\n include(*extensions) if extensions.any?\n end\n\n def register(*extensions, &block)\n extensions << Module.new(&block) if block_given?\n @extensions += extensions\n extensions.each do |extension|\n extend extension\n extension.registered(self) if extension.respond_to?(:registered)\n end\n end\n\n def invoke_hook(name, *args)\n @extensions.each { |e| e.send(name, *args) if e.respond_to?(name) }\n end\n\n def not_found(&block)\n error(Sinatra::NotFound, &block)\n end\n\n def errors\n base.errors.merge(namespace_errors)\n end\n\n def namespace_errors\n "}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":237,"symbol":"prefixed","kind":"method","lang":"ruby","code":"def self.prefixed(*names)\n names.each { |n| define_method(n) { |*a, &b| prefixed(n, *a, &b) } }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":243,"symbol":"helpers","kind":"method","lang":"ruby","code":"def helpers(*extensions, &block)\n class_eval(&block) if block_given?\n include(*extensions) if extensions.any?\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":248,"symbol":"register","kind":"method","lang":"ruby","code":"def register(*extensions, &block)\n extensions << Module.new(&block) if block_given?\n @extensions += extensions\n extensions.each do |extension|\n extend extension\n extension.registered(self) if extension.respond_to?(:registered)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":257,"symbol":"invoke_hook","kind":"method","lang":"ruby","code":"def invoke_hook(name, *args)\n @extensions.each { |e| e.send(name, *args) if e.respond_to?(name) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":261,"symbol":"not_found","kind":"method","lang":"ruby","code":"def not_found(&block)\n error(Sinatra::NotFound, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":265,"symbol":"errors","kind":"method","lang":"ruby","code":"def errors\n base.errors.merge(namespace_errors)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":269,"symbol":"namespace_errors","kind":"method","lang":"ruby","code":"def namespace_errors\n @errors\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":273,"symbol":"error","kind":"method","lang":"ruby","code":"def error(*codes, &block)\n args = Sinatra::Base.send(:compile!, 'ERROR', /.*/, block)\n codes = codes.map { |c| Array(c) }.flatten\n codes << Exception if codes.empty?\n codes << Sinatra::NotFound if codes.include?(404)\n\n codes.each do |c|\n errors = @errors[c] ||= []\n errors << args\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":285,"symbol":"respond_to","kind":"method","lang":"ruby","code":"def respond_to(*args)\n return @conditions[:provides] || base.respond_to if args.empty?\n\n @conditions[:provides] = args\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":291,"symbol":"set","kind":"method","lang":"ruby","code":"def set(key, value = self, &block)\n return key.each { |k, v| set(k, v) } if key.respond_to?(:each) && block.nil? && (value == self)\n raise ArgumentError, \"may not set #{key}\" unless ([:views] + ALLOWED_ENGINES).include?(key)\n\n block ||= proc { value }\n singleton_class.send(:define_method, key, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":299,"symbol":"enable","kind":"method","lang":"ruby","code":"def enable(*opts)\n opts.each { |key| set(key, true) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":303,"symbol":"disable","kind":"method","lang":"ruby","code":"def disable(*opts)\n opts.each { |key| set(key, false) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":307,"symbol":"template","kind":"method","lang":"ruby","code":"def template(name, &block)\n first_location = caller_locations.first\n filename = first_location.path\n line = first_location.lineno\n templates[name] = [block, filename, line]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":314,"symbol":"layout","kind":"method","lang":"ruby","code":"def layout(name = :layout, &block)\n template name, &block\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":318,"symbol":"pattern","kind":"method","lang":"ruby","code":"def pattern\n @pattern\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":324,"symbol":"app","kind":"method","lang":"ruby","code":"def app\n base.respond_to?(:base) ? base.base : base\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":328,"symbol":"compile","kind":"method","lang":"ruby","code":"def compile(pattern, conditions, default_pattern = nil)\n if pattern.respond_to? :to_hash\n conditions = conditions.merge pattern.to_hash\n pattern = nil\n end\n base_pattern = @pattern\n base_conditions = @conditions\n pattern ||= default_pattern\n [prefixed_path(base_pattern, pattern),\n (base_conditions || {}).merge(conditions)]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":340,"symbol":"prefixed_path","kind":"method","lang":"ruby","code":"def prefixed_path(a, b)\n return a || b || /.*/ unless a && b\n return Mustermann.new(b) if a == /.*/\n\n Mustermann.new(a) + Mustermann.new(b)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":347,"symbol":"prefixed","kind":"method","lang":"ruby","code":"def prefixed(method, pattern = nil, conditions = {}, &block)\n default = %r{(?:/.*)?} if (method == :before) || (method == :after)\n pattern, conditions = compile pattern, conditions, default\n result = base.send(method, pattern, **conditions, &block)\n invoke_hook :route_added, method.to_s.upcase, pattern, block\n result\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":355,"symbol":"method_missing","kind":"method","lang":"ruby","code":"def method_missing(method, *args, &block)\n base.send(method, *args, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":359,"symbol":"respond_to?","kind":"method","lang":"ruby","code":"def respond_to?(method, include_private = false)\n super || base.respond_to?(method, include_private)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":364,"symbol":"BaseMethods","kind":"module","lang":"ruby","code":"module BaseMethods\n include SharedMethods\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/namespace.rb","line":368,"symbol":"extended","kind":"method","lang":"ruby","code":"def self.extended(base)\n base.extend BaseMethods\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/quiet_logger.rb","line":3,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::QuietLogger\n #\n # QuietLogger extension allows you to define paths excluded\n # from logging using the +quiet_logger_prefixes+ setting.\n # It is inspired from rails quiet_logger, but handles multiple paths.\n #\n # == Usage\n #\n # === Classic Application\n #\n # You have to require the quiet_logger, set the prefixes\n # and register the extension in your application.\n #\n # require 'sinatra'\n # require 'sinatra/quiet_logger'\n #\n # set :quiet_logger_prefixes, %w(css js images fonts)\n # register Sinatra::QuietLogger\n #\n # === Modular Application\n #\n # The same for modular application:\n #\n # require 'sinatra/base'\n # require 'sinatra/quiet_logger'\n #\n # set :quiet_logger_prefixes, %w(css js images fonts)\n #\n # class App < Sinatra::Base\n # register Sinatra::QuietLogger\n # end\n #\n module QuietLogger\n def self.registered(app)\n quiet_logger_prefixes = begin\n app.settings.quiet_logger_prefixes.join('|')\n rescue StandardError\n ''\n end\n return warn('You need to specify the paths you wish to exclude from logging via `set :quiet_logger_prefixes, %w(images css fon"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/quiet_logger.rb","line":36,"symbol":"QuietLogger","kind":"module","lang":"ruby","doc":"set :quiet_logger_prefixes, %w(css js images fonts) class App < Sinatra::Base register Sinatra::QuietLogger end","code":"module QuietLogger\n def self.registered(app)\n quiet_logger_prefixes = begin\n app.settings.quiet_logger_prefixes.join('|')\n rescue StandardError\n ''\n end\n return warn('You need to specify the paths you wish to exclude from logging via `set :quiet_logger_prefixes, %w(images css fonts)`') if quiet_logger_prefixes.empty?\n\n const_set('QUIET_LOGGER_REGEX', %r(\\A/{0,2}(?:#{quiet_logger_prefixes})))\n ::Rack::CommonLogger.prepend(\n ::Module.new do\n def log(env, *)\n super unless env['PATH_INFO'] =~ QUIET_LOGGER_REGEX\n end\n end\n )\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/quiet_logger.rb","line":37,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(app)\n quiet_logger_prefixes = begin\n app.settings.quiet_logger_prefixes.join('|')\n rescue StandardError\n ''\n end\n return warn('You need to specify the paths you wish to exclude from logging via `set :quiet_logger_prefixes, %w(images css fonts)`') if quiet_logger_prefixes.empty?\n\n const_set('QUIET_LOGGER_REGEX', %r(\\A/{0,2}(?:#{quiet_logger_prefixes})))\n ::Rack::CommonLogger.prepend(\n ::Module.new do\n def log(env, *)\n super unless env['PATH_INFO'] =~ QUIET_LOGGER_REGEX\n end\n end\n )\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/quiet_logger.rb","line":48,"symbol":"log","kind":"method","lang":"ruby","code":"def log(env, *)\n super unless env['PATH_INFO'] =~ QUIET_LOGGER_REGEX\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::Reloader\n #\n # <b>DEPRECATED:<b> Please consider using an alternative like\n # <tt>rerun</tt> or <tt>rack-unreloader</tt> instead.\n #\n # Extension to reload modified files. Useful during development,\n # since it will automatically require files defining routes, filters,\n # error handlers and inline templates, with every incoming request,\n # but only if they have been updated.\n #\n # == Usage\n #\n # === Classic Application\n #\n # To enable the reloader in a classic application all you need to do is\n # require it:\n #\n # require \"sinatra\"\n # require \"sinatra/reloader\" if development?\n #\n # # Your classic application code goes here...\n #\n # === Modular Application\n #\n # To enable the reloader in a modular application all you need to do is\n # require it, and then, register it:\n #\n # require \"sinatra/base\"\n # require \"sinatra/reloader\"\n #\n # class MyApp < Sinatra::Base\n # configure :development do\n # register Sinatra::Reloader\n # end\n #\n # # Your modular application code goes here...\n # end\n #\n # == Using the Reloader in Other Environments\n #\n # By default, the reloade"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":100,"symbol":"Reloader","kind":"module","lang":"ruby","doc":"end end # Your modular application code goes here... end","code":"module Reloader\n # Watches a file so it can tell when it has been updated, and what\n # elements does it contain.\n class Watcher\n # Represents an element of a Sinatra application that may need to\n # be reloaded. An element could be:\n # * a route\n # * a filter\n # * an error handler\n # * a middleware\n # * inline templates\n #\n # Its +representation+ attribute is there to allow to identify the\n # element within an application, that is, to match it with its\n # Sinatra's internal representation.\n class Element < Struct.new(:type, :representation)\n end\n\n # Collection of file +Watcher+ that can be associated with a\n # Sinatra application. That way, we can know which files belong\n # to a given application and which files have been modified. It\n # also provides a mechanism to inform a Watcher of the elements\n # defined in the file being watched and if its changes should be\n # ignored.\n class List\n @app_list_map = Hash.new { |hash, key| hash[key] = new }\n\n # Returns the +List+ for the application +app+.\n def self.for(app)\n @app_list_map[app]\n end\n"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":103,"symbol":"Watcher","kind":"class","lang":"ruby","doc":"Watches a file so it can tell when it has been updated, and what elements does it contain.","code":"class Watcher\n # Represents an element of a Sinatra application that may need to\n # be reloaded. An element could be:\n # * a route\n # * a filter\n # * an error handler\n # * a middleware\n # * inline templates\n #\n # Its +representation+ attribute is there to allow to identify the\n # element within an application, that is, to match it with its\n # Sinatra's internal representation.\n class Element < Struct.new(:type, :representation)\n end\n\n # Collection of file +Watcher+ that can be associated with a\n # Sinatra application. That way, we can know which files belong\n # to a given application and which files have been modified. It\n # also provides a mechanism to inform a Watcher of the elements\n # defined in the file being watched and if its changes should be\n # ignored.\n class List\n @app_list_map = Hash.new { |hash, key| hash[key] = new }\n\n # Returns the +List+ for the application +app+.\n def self.for(app)\n @app_list_map[app]\n end\n\n # Creates a new +List+ instance.\n def initialize\n @path_watcher_map = Hash.new do |hash, key|\n "}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":115,"symbol":"Element","kind":"class","lang":"ruby","doc":"* a middleware * inline templates Its +representation+ attribute is there to allow to identify the element within an application, that is, to match it with its Sinatra's internal representation.","code":"class Element < Struct.new(:type, :representation)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":124,"symbol":"List","kind":"class","lang":"ruby","doc":"Collection of file +Watcher+ that can be associated with a Sinatra application. That way, we can know which files belong to a given application and which files have been modified. It also provides a mechanism to inform a Watcher of the elements defined in the file being watched and if its changes should be ignored.","code":"class List\n @app_list_map = Hash.new { |hash, key| hash[key] = new }\n\n # Returns the +List+ for the application +app+.\n def self.for(app)\n @app_list_map[app]\n end\n\n # Creates a new +List+ instance.\n def initialize\n @path_watcher_map = Hash.new do |hash, key|\n hash[key] = Watcher.new(key)\n end\n end\n\n # Lets the +Watcher+ for the file located at +path+ know that the\n # +element+ is defined there, and adds the +Watcher+ to the +List+,\n # if it isn't already there.\n def watch(path, element)\n watcher_for(path).elements << element\n end\n\n # Tells the +Watcher+ for the file located at +path+ to ignore\n # the file changes, and adds the +Watcher+ to the +List+, if\n # it isn't already there.\n def ignore(path)\n watcher_for(path).ignore\n end\n\n # Adds a +Watcher+ for the file located at +path+ to the\n # +List+, if it isn't already there.\n def watcher_for(path)\n @path_watcher_map[File.expand_path(path)]\n end\n alias watch_file watcher_for\n\n # Returns an array with all the wat"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":128,"symbol":"for","kind":"method","lang":"ruby","doc":"Returns the +List+ for the application +app+.","code":"def self.for(app)\n @app_list_map[app]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":133,"symbol":"initialize","kind":"method","lang":"ruby","doc":"Creates a new +List+ instance.","code":"def initialize\n @path_watcher_map = Hash.new do |hash, key|\n hash[key] = Watcher.new(key)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":142,"symbol":"watch","kind":"method","lang":"ruby","doc":"Lets the +Watcher+ for the file located at +path+ know that the +element+ is defined there, and adds the +Watcher+ to the +List+, if it isn't already there.","code":"def watch(path, element)\n watcher_for(path).elements << element\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":149,"symbol":"ignore","kind":"method","lang":"ruby","doc":"Tells the +Watcher+ for the file located at +path+ to ignore the file changes, and adds the +Watcher+ to the +List+, if it isn't already there.","code":"def ignore(path)\n watcher_for(path).ignore\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":155,"symbol":"watcher_for","kind":"method","lang":"ruby","doc":"Adds a +Watcher+ for the file located at +path+ to the +List+, if it isn't already there.","code":"def watcher_for(path)\n @path_watcher_map[File.expand_path(path)]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":161,"symbol":"watchers","kind":"method","lang":"ruby","doc":"Returns an array with all the watchers in the +List+.","code":"def watchers\n @path_watcher_map.values\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":167,"symbol":"updated","kind":"method","lang":"ruby","doc":"Returns an array with all the watchers in the +List+ that have been updated.","code":"def updated\n watchers.find_all(&:updated?)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":175,"symbol":"initialize","kind":"method","lang":"ruby","doc":"Creates a new +Watcher+ instance for the file located at +path+.","code":"def initialize(path)\n @ignore = nil\n @path = path\n @elements = []\n update\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":183,"symbol":"updated?","kind":"method","lang":"ruby","doc":"Indicates whether or not the file being watched has been modified.","code":"def updated?\n !ignore? && !removed? && mtime != File.mtime(path)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":188,"symbol":"update","kind":"method","lang":"ruby","doc":"Updates the mtime of the file being watched.","code":"def update\n @mtime = File.mtime(path)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":194,"symbol":"inline_templates?","kind":"method","lang":"ruby","doc":"Indicates whether or not the file being watched has inline templates.","code":"def inline_templates?\n elements.any? { |element| element.type == :inline_templates }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":200,"symbol":"ignore","kind":"method","lang":"ruby","doc":"Informs that the modifications to the file being watched should be ignored.","code":"def ignore\n @ignore = true\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":206,"symbol":"ignore?","kind":"method","lang":"ruby","doc":"Indicates whether or not the modifications to the file being watched should be ignored.","code":"def ignore?\n !!@ignore\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":211,"symbol":"removed?","kind":"method","lang":"ruby","doc":"Indicates whether or not the file being watched has been removed.","code":"def removed?\n !File.exist?(path)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":220,"symbol":"after_reload","kind":"method","lang":"ruby","doc":"Allow a block to be executed after any file being reloaded","code":"def after_reload(&block)\n @@after_reload << block\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":227,"symbol":"registered","kind":"method","lang":"ruby","doc":"When the extension is registered it extends the Sinatra application +klass+ with the modules +BaseMethods+ and +ExtensionMethods+ and defines a before filter to +perform+ the reload of the modified files.","code":"def self.registered(klass)\n @reloader_loaded_in ||= {}\n return if @reloader_loaded_in[klass]\n\n @reloader_loaded_in[klass] = true\n\n klass.extend BaseMethods\n klass.extend ExtensionMethods\n klass.set(:reloader) { klass.development? }\n klass.set(:reload_templates) { klass.reloader? }\n klass.before do\n if klass.reloader?\n MUTEX_FOR_PERFORM.synchronize { Reloader.perform(klass) }\n end\n end\n klass.set(:inline_templates, klass.app_file) if klass == Sinatra::Application\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":247,"symbol":"perform","kind":"method","lang":"ruby","doc":"Reloads the modified files, adding, updating and removing the needed elements.","code":"def self.perform(klass)\n reloaded_paths = []\n Watcher::List.for(klass).updated.each do |watcher|\n klass.set(:inline_templates, watcher.path) if watcher.inline_templates?\n watcher.elements.each { |element| klass.deactivate(element) }\n # Deletes all old elements.\n watcher.elements.delete_if { true }\n $LOADED_FEATURES.delete(watcher.path)\n require watcher.path\n watcher.update\n reloaded_paths << watcher.path\n end\n return if reloaded_paths.empty?\n\n @@after_reload.each do |block|\n block.arity.zero? ? block.call : block.call(reloaded_paths)\n end\n # Prevents after_reload from increasing each time it's reloaded.\n @@after_reload.delete_if do |blk|\n path, = blk.source_location\n path && reloaded_paths.include?(path)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":272,"symbol":"BaseMethods","kind":"module","lang":"ruby","doc":"Contains the methods defined in Sinatra::Base that are overridden.","code":"module BaseMethods\n # Protects Sinatra::Base.run! from being called more than once.\n def run!(*args)\n if settings.reloader?\n super unless running?\n else\n super\n end\n end\n\n # Does everything Sinatra::Base#route does, but it also tells the\n # +Watcher::List+ for the Sinatra application to watch the defined\n # route.\n #\n # Note: We are using #compile! so we don't interfere with extensions\n # changing #route.\n def compile!(verb, path, block, **options)\n source_location = block.respond_to?(:source_location) ?\n block.source_location.first : caller_files[1]\n signature = super\n watch_element(\n source_location, :route, { verb: verb, signature: signature }\n )\n signature\n end\n\n # Does everything Sinatra::Base#inline_templates= does, but it also\n # tells the +Watcher::List+ for the Sinatra application to watch the\n # inline templates in +file+ or the file who made the call to this\n # method.\n def inline_templates=(file = nil)\n file = (caller_files[1] || File.expand_path($0)) if file.nil? || file == true\n watch_"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":274,"symbol":"run!","kind":"method","lang":"ruby","doc":"Protects Sinatra::Base.run! from being called more than once.","code":"def run!(*args)\n if settings.reloader?\n super unless running?\n else\n super\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":288,"symbol":"compile!","kind":"method","lang":"ruby","doc":"Does everything Sinatra::Base#route does, but it also tells the +Watcher::List+ for the Sinatra application to watch the defined route. Note: We are using #compile! so we don't interfere with extensions changing #route.","code":"def compile!(verb, path, block, **options)\n source_location = block.respond_to?(:source_location) ?\n block.source_location.first : caller_files[1]\n signature = super\n watch_element(\n source_location, :route, { verb: verb, signature: signature }\n )\n signature\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":311,"symbol":"use","kind":"method","lang":"ruby","doc":"Does everything Sinatra::Base#use does, but it also tells the +Watcher::List+ for the Sinatra application to watch the middleware being used.","code":"def use(middleware, *args, &block)\n path = caller_files[1] || File.expand_path($0)\n watch_element(path, :middleware, [middleware, args, block])\n super\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":320,"symbol":"add_filter","kind":"method","lang":"ruby","doc":"Does everything Sinatra::Base#add_filter does, but it also tells the +Watcher::List+ for the Sinatra application to watch the defined filter.","code":"def add_filter(type, path = nil, **options, &block)\n source_location = block.respond_to?(:source_location) ?\n block.source_location.first : caller_files[1]\n result = super\n watch_element(source_location, :\"#{type}_filter\", filters[type].last)\n result\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":331,"symbol":"error","kind":"method","lang":"ruby","doc":"Does everything Sinatra::Base#error does, but it also tells the +Watcher::List+ for the Sinatra application to watch the defined error handler.","code":"def error(*codes, &block)\n path = caller_files[1] || File.expand_path($0)\n result = super\n codes.each do |c|\n watch_element(path, :error, code: c, handler: @errors[c])\n end\n result\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":343,"symbol":"register","kind":"method","lang":"ruby","doc":"Does everything Sinatra::Base#register does, but it also lets the reloader know that an extension is being registered, because the elements defined in its +registered+ method need a special treatment.","code":"def register(*extensions, &block)\n start_registering_extension\n result = super\n stop_registering_extension\n result\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":352,"symbol":"inherited","kind":"method","lang":"ruby","doc":"Does everything Sinatra::Base#register does and then registers the reloader in the +subclass+.","code":"def inherited(subclass)\n result = super\n subclass.register Sinatra::Reloader\n result\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":360,"symbol":"ExtensionMethods","kind":"module","lang":"ruby","doc":"Contains the methods that the extension adds to the Sinatra application.","code":"module ExtensionMethods\n # Removes the +element+ from the Sinatra application.\n def deactivate(element)\n case element.type\n when :route\n verb = element.representation[:verb]\n signature = element.representation[:signature]\n (routes[verb] ||= []).delete(signature)\n when :middleware\n @middleware.delete(element.representation)\n when :before_filter\n filters[:before].delete(element.representation)\n when :after_filter\n filters[:after].delete(element.representation)\n when :error\n code = element.representation[:code]\n handler = element.representation[:handler]\n @errors.delete(code) if @errors[code] == handler\n end\n end\n\n # Indicates with a +glob+ which files should be reloaded if they\n # have been modified. It can be called several times.\n def also_reload(*glob)\n Dir[*glob].each { |path| Watcher::List.for(self).watch_file(path) }\n end\n\n # Indicates with a +glob+ which files should not be reloaded even if\n # they have been modified. It can be called several times.\n def dont_reload(*glob)\n Di"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":362,"symbol":"deactivate","kind":"method","lang":"ruby","doc":"Removes the +element+ from the Sinatra application.","code":"def deactivate(element)\n case element.type\n when :route\n verb = element.representation[:verb]\n signature = element.representation[:signature]\n (routes[verb] ||= []).delete(signature)\n when :middleware\n @middleware.delete(element.representation)\n when :before_filter\n filters[:before].delete(element.representation)\n when :after_filter\n filters[:after].delete(element.representation)\n when :error\n code = element.representation[:code]\n handler = element.representation[:handler]\n @errors.delete(code) if @errors[code] == handler\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":383,"symbol":"also_reload","kind":"method","lang":"ruby","doc":"Indicates with a +glob+ which files should be reloaded if they have been modified. It can be called several times.","code":"def also_reload(*glob)\n Dir[*glob].each { |path| Watcher::List.for(self).watch_file(path) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":389,"symbol":"dont_reload","kind":"method","lang":"ruby","doc":"Indicates with a +glob+ which files should not be reloaded even if they have been modified. It can be called several times.","code":"def dont_reload(*glob)\n Dir[*glob].each { |path| Watcher::List.for(self).ignore(path) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":396,"symbol":"register_path","kind":"method","lang":"ruby","doc":"attr_reader :register_path warn on -w (private attribute)","code":"def register_path; @register_path ||= nil; end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":399,"symbol":"start_registering_extension","kind":"method","lang":"ruby","doc":"Indicates an extension is being registered.","code":"def start_registering_extension\n @register_path = caller_files[2]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":404,"symbol":"stop_registering_extension","kind":"method","lang":"ruby","doc":"Indicates the extension has already been registered.","code":"def stop_registering_extension\n @register_path = nil\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":409,"symbol":"registering_extension?","kind":"method","lang":"ruby","doc":"Indicates whether or not an extension is being registered.","code":"def registering_extension?\n !register_path.nil?\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/reloader.rb","line":421,"symbol":"watch_element","kind":"method","lang":"ruby","doc":"in the file located at +path+. If an extension is being registered, it also tells the list to watch it in the file where the extension has been registered. This prevents the duplication of the elements added by the extension in its +registered+ method with every reload.","code":"def watch_element(path, type, representation = nil)\n list = Watcher::List.for(self)\n element = Watcher::Element.new(type, representation)\n list.watch(path, element)\n list.watch(register_path, element) if registering_extension?\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/required_params.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::RequiredParams\n #\n # Ensure required query parameters\n #\n # == Usage\n #\n # Set required query parameter keys in the argument.\n # It'll halt with 400 if required keys don't exist.\n #\n # get '/simple_keys' do\n # required_params :p1, :p2\n # end\n #\n # Complicated pattern is also fine.\n #\n # get '/complicated_keys' do\n # required_params :p1, :p2 => [:p3, :p4]\n # end\n #\n # === Classic Application\n #\n # In a classic application simply require the helpers, and start using them:\n #\n # require \"sinatra\"\n # require \"sinatra/required_params\"\n #\n # # The rest of your classic application code goes here...\n #\n # === Modular Application\n #\n # In a modular application you need to require the helpers, and then tell\n # the application to use them:\n #\n # require \"sinatra/base\"\n # require \"sinatra/required_params\"\n #\n # class MyApp < Sinatra::Base\n # helpers Sinatra::RequiredParams\n #\n # # The rest of your modular application code goes here...\n # end\n #\n module RequiredParams\n def required_params(*keys)\n _required_params(params, *keys)\n end\n\n private\n\n def _re"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/required_params.rb","line":48,"symbol":"RequiredParams","kind":"module","lang":"ruby","doc":"class MyApp < Sinatra::Base helpers Sinatra::RequiredParams # The rest of your modular application code goes here... end","code":"module RequiredParams\n def required_params(*keys)\n _required_params(params, *keys)\n end\n\n private\n\n def _required_params(p, *keys)\n keys.each do |key|\n if key.is_a?(Hash)\n _required_params(p, *key.keys)\n key.each do |k, v|\n _required_params(p[k.to_s], v)\n end\n elsif key.is_a?(Array)\n _required_params(p, *key)\n else\n halt 400 unless p.respond_to?(:key?) && p&.key?(key.to_s)\n end\n end\n true\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/required_params.rb","line":49,"symbol":"required_params","kind":"method","lang":"ruby","code":"def required_params(*keys)\n _required_params(params, *keys)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/required_params.rb","line":55,"symbol":"_required_params","kind":"method","lang":"ruby","code":"def _required_params(p, *keys)\n keys.each do |key|\n if key.is_a?(Hash)\n _required_params(p, *key.keys)\n key.each do |k, v|\n _required_params(p[k.to_s], v)\n end\n elsif key.is_a?(Array)\n _required_params(p, *key)\n else\n halt 400 unless p.respond_to?(:key?) && p&.key?(key.to_s)\n end\n end\n true\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":6,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n #\n # = Sinatra::RespondWith\n #\n # These extensions let Sinatra automatically choose what template to render or\n # action to perform depending on the request's Accept header.\n #\n # Example:\n #\n # # Without Sinatra::RespondWith\n # get '/' do\n # data = { :name => 'example' }\n # request.accept.each do |type|\n # case type.to_s\n # when 'text/html'\n # halt haml(:index, :locals => data)\n # when 'text/json'\n # halt data.to_json\n # when 'application/atom+xml'\n # halt nokogiri(:'index.atom', :locals => data)\n # when 'application/xml', 'text/xml'\n # halt nokogiri(:'index.xml', :locals => data)\n # when 'text/plain'\n # halt 'just an example'\n # end\n # end\n # error 406\n # end\n #\n # # With Sinatra::RespondWith\n # get '/' do\n # respond_with :index, :name => 'example' do |f|\n # f.txt { 'just an example' }\n # end\n # end\n #\n # Both helper methods +respond_to+ and +respond_with+ let you define custom\n # handlers like the one above for +text/plain+. +respond_with+ additionally\n # takes a template name and/or an object to offer t"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":90,"symbol":"RespondWith","kind":"module","lang":"ruby","doc":"f.on('text/*') { data.to_s } f.on('*/*') { \"matches everything\" } end end Definition order does not matter.","code":"module RespondWith\n class Format\n def initialize(app)\n @app = app\n @map = {}\n @generic = {}\n @default = nil\n end\n\n def on(type, &block)\n @app.settings.mime_types(type).each do |mime|\n case mime\n when '*/*' then @default = block\n when %r{^([^/]+)/\\*$} then @generic[$1] = block\n else @map[mime] = block\n end\n end\n end\n\n def finish\n yield self if block_given?\n mime_type = @app.content_type ||\n @app.request.preferred_type(@map.keys) ||\n @app.request.preferred_type ||\n 'text/html'\n type = mime_type.split(/\\s*;\\s*/, 2).first\n handlers = [@map[type], @generic[type[%r{^[^/]+}]], @default].compact\n handlers.each do |block|\n if (result = block.call(type))\n @app.content_type mime_type\n @app.halt result\n end\n end\n @app.halt 500, 'Unknown template engine'\n end\n\n def method_missing(method, *args, &block)\n return super if args.any? || block.nil? || !@app.mime_type(method)\n\n"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":91,"symbol":"Format","kind":"class","lang":"ruby","code":"class Format\n def initialize(app)\n @app = app\n @map = {}\n @generic = {}\n @default = nil\n end\n\n def on(type, &block)\n @app.settings.mime_types(type).each do |mime|\n case mime\n when '*/*' then @default = block\n when %r{^([^/]+)/\\*$} then @generic[$1] = block\n else @map[mime] = block\n end\n end\n end\n\n def finish\n yield self if block_given?\n mime_type = @app.content_type ||\n @app.request.preferred_type(@map.keys) ||\n @app.request.preferred_type ||\n 'text/html'\n type = mime_type.split(/\\s*;\\s*/, 2).first\n handlers = [@map[type], @generic[type[%r{^[^/]+}]], @default].compact\n handlers.each do |block|\n if (result = block.call(type))\n @app.content_type mime_type\n @app.halt result\n end\n end\n @app.halt 500, 'Unknown template engine'\n end\n\n def method_missing(method, *args, &block)\n return super if args.any? || block.nil? || !@app.mime_type(method)\n\n on(method, &blo"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":92,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app)\n @app = app\n @map = {}\n @generic = {}\n @default = nil\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":99,"symbol":"on","kind":"method","lang":"ruby","code":"def on(type, &block)\n @app.settings.mime_types(type).each do |mime|\n case mime\n when '*/*' then @default = block\n when %r{^([^/]+)/\\*$} then @generic[$1] = block\n else @map[mime] = block\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":109,"symbol":"finish","kind":"method","lang":"ruby","code":"def finish\n yield self if block_given?\n mime_type = @app.content_type ||\n @app.request.preferred_type(@map.keys) ||\n @app.request.preferred_type ||\n 'text/html'\n type = mime_type.split(/\\s*;\\s*/, 2).first\n handlers = [@map[type], @generic[type[%r{^[^/]+}]], @default].compact\n handlers.each do |block|\n if (result = block.call(type))\n @app.content_type mime_type\n @app.halt result\n end\n end\n @app.halt 500, 'Unknown template engine'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":126,"symbol":"method_missing","kind":"method","lang":"ruby","code":"def method_missing(method, *args, &block)\n return super if args.any? || block.nil? || !@app.mime_type(method)\n\n on(method, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":133,"symbol":"Helpers","kind":"module","lang":"ruby","code":"module Helpers\n include Sinatra::JSON\n\n def respond_with(template, object = nil, &block)\n unless Symbol === template\n object = template\n template = nil\n end\n format = Format.new(self)\n format.on '*/*' do |type|\n exts = settings.ext_map[type]\n exts << :xml if type.end_with? '+xml'\n if template\n args = template_cache.fetch(type, template) { template_for(template, exts) }\n if args.any?\n locals = { object: object }\n locals.merge! object.to_hash if object.respond_to? :to_hash\n\n renderer = args.first\n options = args[1..] + [{ locals: locals }]\n\n halt send(renderer, *options)\n end\n end\n if object\n exts.each do |ext|\n halt json(object) if ext == :json\n next unless object.respond_to? method = \"to_#{ext}\"\n\n halt(*object.send(method))\n end\n end\n false\n end\n format.finish(&block)\n end\n\n def respond_to(&block)\n Format.new(self).finish(&block)\n end\n\n private\n\n def template_for("}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":136,"symbol":"respond_with","kind":"method","lang":"ruby","code":"def respond_with(template, object = nil, &block)\n unless Symbol === template\n object = template\n template = nil\n end\n format = Format.new(self)\n format.on '*/*' do |type|\n exts = settings.ext_map[type]\n exts << :xml if type.end_with? '+xml'\n if template\n args = template_cache.fetch(type, template) { template_for(template, exts) }\n if args.any?\n locals = { object: object }\n locals.merge! object.to_hash if object.respond_to? :to_hash\n\n renderer = args.first\n options = args[1..] + [{ locals: locals }]\n\n halt send(renderer, *options)\n end\n end\n if object\n exts.each do |ext|\n halt json(object) if ext == :json\n next unless object.respond_to? method = \"to_#{ext}\"\n\n halt(*object.send(method))\n end\n end\n false\n end\n format.finish(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":170,"symbol":"respond_to","kind":"method","lang":"ruby","code":"def respond_to(&block)\n Format.new(self).finish(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":176,"symbol":"template_for","kind":"method","lang":"ruby","code":"def template_for(name, exts)\n # in production this is cached, so don't worry too much about runtime\n possible = []\n settings.template_engines[:all].each do |engine|\n exts.each { |ext| possible << [engine, \"#{name}.#{ext}\"] }\n end\n\n exts.each do |ext|\n settings.template_engines[ext].each { |e| possible << [e, name] }\n end\n\n possible.each do |engine, template|\n klass = Tilt.default_mapping.template_map[engine.to_s] ||\n Tilt.lazy_map[engine.to_s].fetch(0, [])[0]\n\n find_template(settings.views, template, klass) do |file|\n next unless File.exist? file\n\n return settings.rendering_method(engine) << template.to_sym\n end\n end\n [] # nil or false would not be cached\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":201,"symbol":"remap_extensions","kind":"method","lang":"ruby","code":"def remap_extensions\n ext_map.clear\n Rack::Mime::MIME_TYPES.each { |e, t| ext_map[t] << e[1..].to_sym }\n ext_map['text/javascript'] << 'js'\n ext_map['text/xml'] << 'xml'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":208,"symbol":"mime_type","kind":"method","lang":"ruby","code":"def mime_type(*)\n result = super\n remap_extensions\n result\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":214,"symbol":"respond_to","kind":"method","lang":"ruby","code":"def respond_to(*formats)\n @respond_to ||= nil\n\n if formats.any?\n @respond_to ||= []\n @respond_to.concat formats\n elsif @respond_to.nil? && superclass.respond_to?(:respond_to)\n superclass.respond_to\n else\n @respond_to\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":227,"symbol":"rendering_method","kind":"method","lang":"ruby","code":"def rendering_method(engine)\n return [engine] if Sinatra::Templates.method_defined? engine\n return [:mab] if engine.to_sym == :markaby\n\n %i[render engine]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":236,"symbol":"compile!","kind":"method","lang":"ruby","code":"def compile!(verb, path, block, **options)\n options[:provides] ||= respond_to if respond_to\n super\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":241,"symbol":"jrubyify","kind":"method","lang":"ruby","code":"def self.jrubyify(engs)\n not_supported = [:markdown]\n engs.each_key do |key|\n engs[key].collect! { |eng| eng == :yajl ? :json_pure : eng }\n engs[key].delete_if { |eng| not_supported.include?(eng) }\n end\n engs\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":250,"symbol":"engines","kind":"method","lang":"ruby","code":"def self.engines\n engines = {\n css: %i[sass scss],\n xml: %i[builder nokogiri],\n html: %i[erb erubi haml hamlit slim liquid\n mab markdown rdoc],\n all: (Sinatra::Templates.instance_methods.map(&:to_sym) +\n [:mab] - %i[find_template markaby]),\n json: [:yajl]\n }\n engines.default = []\n defined?(JRUBY_VERSION) ? jrubyify(engines) : engines\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/respond_with.rb","line":264,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(base)\n base.set :ext_map, Hash.new { |h, k| h[k] = [] }\n base.set :template_engines, engines\n base.remap_extensions\n base.helpers Helpers\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":7,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # NOTE: This feature is experimental, and missing tests!\n #\n # Helps you spinning up and shutting down your own sinatra app. This is especially helpful for running\n # real network tests against a sinatra backend.\n #\n # The backend server could look like the following (in test/server.rb).\n #\n # require \"sinatra\"\n #\n # get \"/\" do\n # \"Cheers from test server\"\n # end\n #\n # get \"/ping\" do\n # \"1\"\n # end\n #\n # Note that you need to implement a ping action for internal use.\n #\n # Next, you need to write your runner.\n #\n # require 'sinatra/runner'\n #\n # class Runner < Sinatra::Runner\n # def app_file\n # File.expand_path(\"server.rb\", __dir__)\n # end\n # end\n #\n # Override Runner#app_file, #command, #port, #protocol and #ping_path for customization.\n #\n # **Don't forget to override #app_file specific to your application!**\n #\n # Wherever you need this test backend, here's how you manage it. The following example assumes you\n # have a test in your app that needs to be run against your test backend.\n #\n # runner = ServerRunner.new\n # runner.run\n #\n # # ..tests against localhost:4567 here..\n #\n # "}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":52,"symbol":"Runner","kind":"class","lang":"ruby","doc":"# ..tests against localhost:4567 here.. runner.kill For an example, check https://github.com/apotonick/roar/blob/master/test/integration/runner.rb","code":"class Runner\n def app_file\n File.expand_path('server.rb', __dir__)\n end\n\n def run\n @pipe = start\n @started = Time.now\n warn \"#{server} up and running on port #{port}\" if ping\n end\n\n def kill\n return unless pipe\n\n Process.kill('KILL', pipe.pid)\n rescue NotImplementedError\n system \"kill -9 #{pipe.pid}\"\n rescue Errno::ESRCH\n end\n\n def get(url)\n Timeout.timeout(1) { get_url(\"#{protocol}://127.0.0.1:#{port}#{url}\") }\n end\n\n def get_stream(url = '/stream', &block)\n Net::HTTP.start '127.0.0.1', port do |http|\n request = Net::HTTP::Get.new url\n http.request request do |response|\n response.read_body(&block)\n end\n end\n end\n\n def get_response(url)\n Net::HTTP.start '127.0.0.1', port do |http|\n request = Net::HTTP::Get.new url\n http.request request do |response|\n response\n end\n end\n end\n\n def log\n @log ||= +''\n loop { @log << pipe.read_nonblock(1) }\n rescue Exception\n @log\n end\n\n private\n\n attr_accessor :pipe\n\n def start\n IO.popen(command)\n end\n\n # to be overwritten\n def command\n "}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":53,"symbol":"app_file","kind":"method","lang":"ruby","code":"def app_file\n File.expand_path('server.rb', __dir__)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":57,"symbol":"run","kind":"method","lang":"ruby","code":"def run\n @pipe = start\n @started = Time.now\n warn \"#{server} up and running on port #{port}\" if ping\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":63,"symbol":"kill","kind":"method","lang":"ruby","code":"def kill\n return unless pipe\n\n Process.kill('KILL', pipe.pid)\n rescue NotImplementedError\n system \"kill -9 #{pipe.pid}\"\n rescue Errno::ESRCH\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":72,"symbol":"get","kind":"method","lang":"ruby","code":"def get(url)\n Timeout.timeout(1) { get_url(\"#{protocol}://127.0.0.1:#{port}#{url}\") }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":76,"symbol":"get_stream","kind":"method","lang":"ruby","code":"def get_stream(url = '/stream', &block)\n Net::HTTP.start '127.0.0.1', port do |http|\n request = Net::HTTP::Get.new url\n http.request request do |response|\n response.read_body(&block)\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":85,"symbol":"get_response","kind":"method","lang":"ruby","code":"def get_response(url)\n Net::HTTP.start '127.0.0.1', port do |http|\n request = Net::HTTP::Get.new url\n http.request request do |response|\n response\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":94,"symbol":"log","kind":"method","lang":"ruby","code":"def log\n @log ||= +''\n loop { @log << pipe.read_nonblock(1) }\n rescue Exception\n @log\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":105,"symbol":"start","kind":"method","lang":"ruby","code":"def start\n IO.popen(command)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":110,"symbol":"command","kind":"method","lang":"ruby","doc":"to be overwritten","code":"def command\n \"bundle exec ruby #{app_file} -p #{port} -e production\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":114,"symbol":"ping","kind":"method","lang":"ruby","code":"def ping(timeout = 30)\n loop do\n return if alive?\n\n if Time.now - @started > timeout\n warn command, log\n raise \"timeout starting server with command '#{command}'\"\n else\n sleep 0.1\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":127,"symbol":"alive?","kind":"method","lang":"ruby","code":"def alive?\n 3.times { get(ping_path) }\n true\n rescue EOFError, SystemCallError, OpenURI::HTTPError, Timeout::Error\n false\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":135,"symbol":"ping_path","kind":"method","lang":"ruby","doc":"to be overwritten","code":"def ping_path\n '/ping'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":140,"symbol":"port","kind":"method","lang":"ruby","doc":"to be overwritten","code":"def port\n 4567\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":144,"symbol":"protocol","kind":"method","lang":"ruby","code":"def protocol\n 'http'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":148,"symbol":"get_url","kind":"method","lang":"ruby","code":"def get_url(url)\n uri = URI.parse(url)\n\n return uri.read unless protocol == 'https'\n\n get_https_url(uri)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/runner.rb","line":156,"symbol":"get_https_url","kind":"method","lang":"ruby","code":"def get_https_url(uri)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Get.new(uri.request_uri)\n http.request(request).body\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::Streaming\n #\n # Sinatra 1.3 introduced the +stream+ helper. This addon improves the\n # streaming API by making the stream object imitate an IO object, turning\n # it into a real Deferrable and making the body play nicer with middleware\n # unaware of streaming.\n #\n # == IO-like behavior\n #\n # This is useful when passing the stream object to a library expecting an\n # IO or StringIO object.\n #\n # get '/' do\n # stream do |out|\n # out.puts \"Hello World!\", \"How are you?\"\n # out.write \"Written #{out.pos} bytes so far!\\n\"\n # out.putc(65) unless out.closed?\n # out.flush\n # end\n # end\n #\n # == Better Middleware Handling\n #\n # Blocks passed to #map! or #map will actually be applied when streaming\n # takes place (as you might have suspected, #map! applies modifications\n # to the current body, while #map creates a new one):\n #\n # class StupidMiddleware\n # def initialize(app) @app = app end\n #\n # def call(env)\n # status, headers, body = @app.call(env)\n # body.map! { |e| e.upcase }\n # [status, headers, body]\n # end\n # end\n #\n # use StupidMiddleware\n #\n # ge"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":78,"symbol":"Streaming","kind":"module","lang":"ruby","doc":"require \"sinatra/base\" require \"sinatra/streaming\" class MyApp < Sinatra::Base helpers Sinatra::Streaming end","code":"module Streaming\n def stream(*)\n stream = super\n stream.extend Stream\n stream.app = self\n env['async.close'].callback { stream.close } if env.key? 'async.close'\n stream\n end\n\n module Stream\n attr_accessor :app, :lineno, :pos, :transformer, :closed\n alias tell pos\n alias closed? closed\n\n def self.extended(obj)\n obj.closed = false\n obj.lineno = 0\n obj.pos = 0\n obj.callback { obj.closed = true }\n obj.errback { obj.closed = true }\n end\n\n def <<(data)\n raise IOError, 'not opened for writing' if closed?\n\n @transformer ||= nil\n data = data.to_s\n data = @transformer[data] if @transformer\n @pos += data.bytesize\n super(data)\n end\n\n def each\n # that way body.each.map { ... } works\n return self unless block_given?\n\n super\n end\n\n def map(&block)\n # dup would not copy the mixin\n clone.map!(&block)\n end\n\n def map!(&block)\n @transformer ||= nil\n\n if @transformer\n inner = @transformer\n outer = block\n block = proc { |value| outer[inner[value]] }\n en"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":79,"symbol":"stream","kind":"method","lang":"ruby","code":"def stream(*)\n stream = super\n stream.extend Stream\n stream.app = self\n env['async.close'].callback { stream.close } if env.key? 'async.close'\n stream\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":87,"symbol":"Stream","kind":"module","lang":"ruby","code":"module Stream\n attr_accessor :app, :lineno, :pos, :transformer, :closed\n alias tell pos\n alias closed? closed\n\n def self.extended(obj)\n obj.closed = false\n obj.lineno = 0\n obj.pos = 0\n obj.callback { obj.closed = true }\n obj.errback { obj.closed = true }\n end\n\n def <<(data)\n raise IOError, 'not opened for writing' if closed?\n\n @transformer ||= nil\n data = data.to_s\n data = @transformer[data] if @transformer\n @pos += data.bytesize\n super(data)\n end\n\n def each\n # that way body.each.map { ... } works\n return self unless block_given?\n\n super\n end\n\n def map(&block)\n # dup would not copy the mixin\n clone.map!(&block)\n end\n\n def map!(&block)\n @transformer ||= nil\n\n if @transformer\n inner = @transformer\n outer = block\n block = proc { |value| outer[inner[value]] }\n end\n @transformer = block\n self\n end\n\n def write(data)\n self << data\n data.to_s.bytesize\n end\n\n alias syswrite write\n alias write_nonblock write\n\n def pri"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":92,"symbol":"extended","kind":"method","lang":"ruby","code":"def self.extended(obj)\n obj.closed = false\n obj.lineno = 0\n obj.pos = 0\n obj.callback { obj.closed = true }\n obj.errback { obj.closed = true }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":110,"symbol":"each","kind":"method","lang":"ruby","code":"def each\n # that way body.each.map { ... } works\n return self unless block_given?\n\n super\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":117,"symbol":"map","kind":"method","lang":"ruby","code":"def map(&block)\n # dup would not copy the mixin\n clone.map!(&block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":122,"symbol":"map!","kind":"method","lang":"ruby","code":"def map!(&block)\n @transformer ||= nil\n\n if @transformer\n inner = @transformer\n outer = block\n block = proc { |value| outer[inner[value]] }\n end\n @transformer = block\n self\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":134,"symbol":"write","kind":"method","lang":"ruby","code":"def write(data)\n self << data\n data.to_s.bytesize\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":142,"symbol":"print","kind":"method","lang":"ruby","code":"def print(*args)\n args.each { |arg| self << arg }\n nil\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":147,"symbol":"printf","kind":"method","lang":"ruby","code":"def printf(format, *args)\n print(format.to_s % args)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":151,"symbol":"putc","kind":"method","lang":"ruby","code":"def putc(c)\n print c.chr\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":155,"symbol":"puts","kind":"method","lang":"ruby","code":"def puts(*args)\n args.each { |arg| self << \"#{arg}\\n\" }\n nil\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":160,"symbol":"close_read","kind":"method","lang":"ruby","code":"def close_read\n raise IOError, 'closing non-duplex IO for reading'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":164,"symbol":"closed_read?","kind":"method","lang":"ruby","code":"def closed_read?\n true\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":168,"symbol":"closed_write?","kind":"method","lang":"ruby","code":"def closed_write?\n closed?\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":172,"symbol":"external_encoding","kind":"method","lang":"ruby","code":"def external_encoding\n Encoding.find settings.default_encoding\n rescue NameError\n settings.default_encoding\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":178,"symbol":"settings","kind":"method","lang":"ruby","code":"def settings\n app.settings\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":182,"symbol":"rewind","kind":"method","lang":"ruby","code":"def rewind\n @pos = @lineno = 0\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":186,"symbol":"not_open_for_reading","kind":"method","lang":"ruby","code":"def not_open_for_reading(*)\n raise IOError, 'not opened for reading'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":208,"symbol":"enum_not_open_for_reading","kind":"method","lang":"ruby","code":"def enum_not_open_for_reading(*)\n not_open_for_reading if block_given?\n enum_for(:not_open_for_reading)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":220,"symbol":"dummy","kind":"method","lang":"ruby","code":"def dummy(*) end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":227,"symbol":"seek","kind":"method","lang":"ruby","code":"def seek(*)\n 0\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":233,"symbol":"sync","kind":"method","lang":"ruby","code":"def sync\n true\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/streaming.rb","line":237,"symbol":"tty?","kind":"method","lang":"ruby","code":"def tty?\n false\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":12,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n Base.set :environment, :test\n\n # Helper methods to ease testing your Sinatra application. Partly extracted\n # from Sinatra. Testing framework agnostic.\n module TestHelpers\n include Rack::Test::Methods\n extend Forwardable\n attr_accessor :settings\n\n # @!group Instance Methods delegated to last_response\n\n # @!method body\n #\n # Body of last_response\n #\n # @see https://www.rubydoc.info/github/rack/rack/main/Rack/Response#body-instance_method\n # @return [String] body of the last response\n\n # @!method headers\n #\n # Headers of last_response\n #\n # @return [Hash] hash of the last response\n\n # @!method status\n #\n # HTTP status of last_response\n #\n # @return [Integer] HTTP status of the last response\n\n # @!method errors\n #\n # Errors of last_response\n #\n # @return [Array] errors of the last response\n def_delegators :last_response, :body, :headers, :status, :errors\n # @!endgroup\n\n # @!group Class Methods delegated to app\n\n # @!method configure(*envs) {|_self| ... }\n # @!scope class\n # @yieldparam _self [Sinatra::Base] the object that the method was called on\n #\n # Set configurat"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":17,"symbol":"TestHelpers","kind":"module","lang":"ruby","doc":"Helper methods to ease testing your Sinatra application. Partly extracted from Sinatra. Testing framework agnostic.","code":"module TestHelpers\n include Rack::Test::Methods\n extend Forwardable\n attr_accessor :settings\n\n # @!group Instance Methods delegated to last_response\n\n # @!method body\n #\n # Body of last_response\n #\n # @see https://www.rubydoc.info/github/rack/rack/main/Rack/Response#body-instance_method\n # @return [String] body of the last response\n\n # @!method headers\n #\n # Headers of last_response\n #\n # @return [Hash] hash of the last response\n\n # @!method status\n #\n # HTTP status of last_response\n #\n # @return [Integer] HTTP status of the last response\n\n # @!method errors\n #\n # Errors of last_response\n #\n # @return [Array] errors of the last response\n def_delegators :last_response, :body, :headers, :status, :errors\n # @!endgroup\n\n # @!group Class Methods delegated to app\n\n # @!method configure(*envs) {|_self| ... }\n # @!scope class\n # @yieldparam _self [Sinatra::Base] the object that the method was called on\n #\n # Set configuration options for Sinatra and/or the app. Allows scoping of\n # settings for certain environments.\n\n # @!method set(option, value = (not_set = true), ignore_setter = fals"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":123,"symbol":"mock_app","kind":"method","lang":"ruby","doc":"an app instance. Any given code in `block` is `class_eval`'d on this new instance before the instance is returned. @param base [Sinatra::Base] App base class @return [Sinatra] Configured mocked app","code":"def mock_app(base = Sinatra::Base, &block)\n inner = nil\n @app = Sinatra.new(base) do\n inner = self\n class_eval(&block)\n end\n @settings = inner\n app\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":151,"symbol":"app","kind":"method","lang":"ruby","doc":"used and stored. (Rack::Lint validates your application and the requests and responses according to the Rack spec.) @return [Sinatra::Base]","code":"def app\n @app ||= Class.new Sinatra::Base\n Rack::Lint.new @app\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":162,"symbol":"options","kind":"method","lang":"ruby","doc":"Processes an OPTIONS request in the context of the current session. @param uri [String] @param params [Hash] @param env [Hash]","code":"def options(uri, params = {}, env = {}, &block)\n env = env_for(uri, env.merge(method: 'OPTIONS', params: params))\n current_session.send(:process_request, uri, env, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":174,"symbol":"patch","kind":"method","lang":"ruby","doc":"Processes a PATCH request in the context of the current session. @param uri [String] @param params [Hash] @param env [Hash]","code":"def patch(uri, params = {}, env = {}, &block)\n env = env_for(uri, env.merge(method: 'PATCH', params: params))\n current_session.send(:process_request, uri, env, &block)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":181,"symbol":"last_request?","kind":"method","lang":"ruby","doc":"@return [Boolean]","code":"def last_request?\n last_request\n true\n rescue Rack::Test::Error\n false\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":190,"symbol":"session","kind":"method","lang":"ruby","doc":"@raise [Rack::Test:Error] If sessions are not enabled for app @return [Hash] Session of last request, or the empty Hash","code":"def session\n return {} unless last_request?\n raise Rack::Test::Error, 'session not enabled for app' unless last_env['rack.session'] || app.session?\n\n last_request.session\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/test_helpers.rb","line":198,"symbol":"last_env","kind":"method","lang":"ruby","doc":"@return The env of the last request","code":"def last_env\n last_request.env\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":5,"symbol":"Sinatra","kind":"module","lang":"ruby","code":"module Sinatra\n # = Sinatra::WebDAV\n #\n # This extensions provides WebDAV verbs, as defined by RFC 4918\n # (https://tools.ietf.org/html/rfc4918). To use this in your app,\n # just +register+ it:\n #\n # require 'sinatra/base'\n # require 'sinatra/webdav'\n #\n # class Application < Sinatra::Base\n # register Sinatra::WebDAV\n #\n # # Now you can use any WebDAV verb:\n # propfind '/2014/january/21' do\n # 'I have a lunch at 9 PM'\n # end\n # end\n #\n # You can use it in classic application just by requiring the extension:\n #\n # require 'sinatra'\n # require 'sinatra/webdav'\n #\n # mkcol '/2015' do\n # 'You started 2015!'\n # end\n #\n module WebDAV\n def self.registered(_)\n Sinatra::Request.include WebDAV::Request\n end\n\n module Request\n def self.included(base)\n base.class_eval do\n alias_method :_safe?, :safe?\n alias_method :_idempotent?, :idempotent?\n\n def safe?\n _safe? or propfind?\n end\n\n def idempotent?\n _idempotent? or propfind? or move? or unlock? # or lock?\n end\n end\n end\n\n def propfind?\n request_method =="}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":33,"symbol":"WebDAV","kind":"module","lang":"ruby","doc":"require 'sinatra/webdav' mkcol '/2015' do 'You started 2015!' end","code":"module WebDAV\n def self.registered(_)\n Sinatra::Request.include WebDAV::Request\n end\n\n module Request\n def self.included(base)\n base.class_eval do\n alias_method :_safe?, :safe?\n alias_method :_idempotent?, :idempotent?\n\n def safe?\n _safe? or propfind?\n end\n\n def idempotent?\n _idempotent? or propfind? or move? or unlock? # or lock?\n end\n end\n end\n\n def propfind?\n request_method == 'PROPFIND'\n end\n\n def proppatch?\n request_method == 'PROPPATCH'\n end\n\n def mkcol?\n request_method == 'MKCOL'\n end\n\n def copy?\n request_method == 'COPY'\n end\n\n def move?\n request_method == 'MOVE'\n end\n\n # def lock?\n # request_method == 'LOCK'\n # end\n\n def unlock?\n request_method == 'UNLOCK'\n end\n end\n\n def propfind(path, opts = {}, &bk) route 'PROPFIND', path, opts, &bk end\n def proppatch(path, opts = {}, &bk) route 'PROPPATCH', path, opts, &bk end\n def mkcol(path, opts = {}, &bk) route 'MKCOL', path, opts, &bk end\n def copy(path, opts = {}, &bk) rou"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":34,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(_)\n Sinatra::Request.include WebDAV::Request\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":38,"symbol":"Request","kind":"module","lang":"ruby","code":"module Request\n def self.included(base)\n base.class_eval do\n alias_method :_safe?, :safe?\n alias_method :_idempotent?, :idempotent?\n\n def safe?\n _safe? or propfind?\n end\n\n def idempotent?\n _idempotent? or propfind? or move? or unlock? # or lock?\n end\n end\n end\n\n def propfind?\n request_method == 'PROPFIND'\n end\n\n def proppatch?\n request_method == 'PROPPATCH'\n end\n\n def mkcol?\n request_method == 'MKCOL'\n end\n\n def copy?\n request_method == 'COPY'\n end\n\n def move?\n request_method == 'MOVE'\n end\n\n # def lock?\n # request_method == 'LOCK'\n # end\n\n def unlock?\n request_method == 'UNLOCK'\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":39,"symbol":"included","kind":"method","lang":"ruby","code":"def self.included(base)\n base.class_eval do\n alias_method :_safe?, :safe?\n alias_method :_idempotent?, :idempotent?\n\n def safe?\n _safe? or propfind?\n end\n\n def idempotent?\n _idempotent? or propfind? or move? or unlock? # or lock?\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":44,"symbol":"safe?","kind":"method","lang":"ruby","code":"def safe?\n _safe? or propfind?\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":48,"symbol":"idempotent?","kind":"method","lang":"ruby","code":"def idempotent?\n _idempotent? or propfind? or move? or unlock? # or lock?\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":54,"symbol":"propfind?","kind":"method","lang":"ruby","code":"def propfind?\n request_method == 'PROPFIND'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":58,"symbol":"proppatch?","kind":"method","lang":"ruby","code":"def proppatch?\n request_method == 'PROPPATCH'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":62,"symbol":"mkcol?","kind":"method","lang":"ruby","code":"def mkcol?\n request_method == 'MKCOL'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":66,"symbol":"copy?","kind":"method","lang":"ruby","code":"def copy?\n request_method == 'COPY'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":70,"symbol":"move?","kind":"method","lang":"ruby","code":"def move?\n request_method == 'MOVE'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":78,"symbol":"unlock?","kind":"method","lang":"ruby","code":"def unlock?\n request_method == 'UNLOCK'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":83,"symbol":"propfind","kind":"method","lang":"ruby","code":"def propfind(path, opts = {}, &bk) route 'PROPFIND', path, opts, &bk end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":84,"symbol":"proppatch","kind":"method","lang":"ruby","code":"def proppatch(path, opts = {}, &bk) route 'PROPPATCH', path, opts, &bk end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":85,"symbol":"mkcol","kind":"method","lang":"ruby","code":"def mkcol(path, opts = {}, &bk) route 'MKCOL', path, opts, &bk end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":86,"symbol":"copy","kind":"method","lang":"ruby","code":"def copy(path, opts = {}, &bk) route 'COPY', path, opts, &bk end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":87,"symbol":"move","kind":"method","lang":"ruby","code":"def move(path, opts = {}, &bk) route 'MOVE', path, opts, &bk end"}
{"repo":"sinatra","file":"sinatra-contrib/lib/sinatra/webdav.rb","line":89,"symbol":"unlock","kind":"method","lang":"ruby","doc":"def lock(path, opts = {}, &bk) route 'LOCK', path, opts, &bk end","code":"def unlock(path, opts = {}, &bk) route 'UNLOCK', path, opts, &bk end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/capture_spec.rb","line":17,"symbol":"render","kind":"method","lang":"ruby","code":"def render(engine, template)\n subject.send(:render, engine, template.to_sym).strip.gsub(/\\s+/, ' ')\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/config_file_spec.rb","line":4,"symbol":"config_file","kind":"method","lang":"ruby","code":"def config_file(*args, &block)\n mock_app do\n register Sinatra::ConfigFile\n set :root, File.expand_path('config_file', __dir__)\n instance_eval(&block) if block\n config_file(*args)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/content_for_spec.rb","line":17,"symbol":"render","kind":"method","lang":"ruby","code":"def render(engine, template)\n subject.send(:render, engine, template, :layout => false).gsub(/\\s/, '')\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/content_for_spec.rb","line":202,"symbol":"body","kind":"method","lang":"ruby","code":"def body\n last_response.body.gsub(/\\s/, '')\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/cookies_spec.rb","line":4,"symbol":"cookie_route","kind":"method","lang":"ruby","code":"def cookie_route(*cookies, headers: {}, &block)\n result = nil\n set_cookie(cookies)\n @cookie_app.get('/') do\n result = instance_eval(&block)\n \"ok\"\n end\n get '/', {}, headers || {}\n expect(last_response).to be_ok\n expect(body).to eq(\"ok\")\n result\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/cookies_spec.rb","line":17,"symbol":"cookies","kind":"method","lang":"ruby","code":"def cookies(*set_cookies)\n cookie_route(*set_cookies) { cookies }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/extension_spec.rb","line":4,"symbol":"ExampleExtension","kind":"module","lang":"ruby","code":"module ExampleExtension\n extend Sinatra::Extension\n\n set :foo, :bar\n settings.set :bar, :blah\n\n configure :test, :production do\n set :reload_stuff, false\n end\n\n configure :development do\n set :reload_stuff, true\n end\n\n get '/' do\n \"from extension, yay\"\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/json_spec.rb","line":33,"symbol":"mock_app","kind":"method","lang":"ruby","code":"def mock_app(&block)\n super do\n class_eval(&block)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/json_spec.rb","line":39,"symbol":"results_in","kind":"method","lang":"ruby","code":"def results_in(obj)\n expect(OkJson.decode(get('/').body)).to eq(obj)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/json_spec.rb","line":68,"symbol":"generate","kind":"method","lang":"ruby","code":"def enc.generate(obj) obj.inspect end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/json_spec.rb","line":75,"symbol":"encode","kind":"method","lang":"ruby","code":"def enc.encode(obj) obj.inspect end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/json_spec.rb","line":87,"symbol":"generate","kind":"method","lang":"ruby","code":"def enc.generate(obj) obj.inspect end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/json_spec.rb","line":97,"symbol":"encode","kind":"method","lang":"ruby","code":"def enc.encode(obj) obj.inspect end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":6,"symbol":"mock_app","kind":"method","lang":"ruby","code":"def mock_app(&block)\n super do\n register Sinatra::Namespace\n class_eval(&block)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":13,"symbol":"namespace","kind":"method","lang":"ruby","code":"def namespace(*args, &block)\n mock_app { namespace(*args, &block) }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":142,"symbol":"foo","kind":"method","lang":"ruby","code":"def foo\n 'foo'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":336,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":352,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":367,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":386,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":405,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":429,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":448,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":454,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n super - 19\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":497,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":516,"symbol":"magic","kind":"method","lang":"ruby","code":"def magic\n 42\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":584,"symbol":"AError","kind":"class","lang":"ruby","code":"class AError < StandardError; end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":585,"symbol":"BError","kind":"class","lang":"ruby","code":"class BError < AError; end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":617,"symbol":"CError","kind":"class","lang":"ruby","code":"class CError < StandardError;\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":844,"symbol":"dump_args","kind":"method","lang":"ruby","code":"def dump_args(*args)\n args.inspect\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":851,"symbol":"dump_args","kind":"method","lang":"ruby","code":"def dump_args(*args)\n super(:foo, *args)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/namespace_spec.rb","line":860,"symbol":"dump_args","kind":"method","lang":"ruby","code":"def dump_args(*args)\n super(:foo_bar, *args)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":28,"symbol":"OkJson","kind":"module","lang":"ruby","doc":"Some parts adapted from http://golang.org/src/pkg/json/decode.go and http://golang.org/src/pkg/utf8/utf8.go","code":"module OkJson\n extend self\n\n\n # Decodes a json document in string s and\n # returns the corresponding ruby value.\n # String s must be valid UTF-8. If you have\n # a string in some other encoding, convert\n # it first.\n #\n # String values in the resulting structure\n # will be UTF-8.\n def decode(s)\n ts = lex(s)\n v, ts = textparse(ts)\n if ts.length > 0\n raise Error, 'trailing garbage'\n end\n v\n end\n\n\n # Parses a \"json text\" in the sense of RFC 4627.\n # Returns the parsed value and any trailing tokens.\n # Note: this is almost the same as valparse,\n # except that it does not accept atomic values.\n def textparse(ts)\n if ts.length < 0\n raise Error, 'empty'\n end\n\n typ, _, val = ts[0]\n case typ\n when '{' then objparse(ts)\n when '[' then arrparse(ts)\n else\n raise Error, \"unexpected #{val.inspect}\"\n end\n end\n\n\n # Parses a \"value\" in the sense of RFC 4627.\n # Returns the parsed value and any trailing tokens.\n def valparse(ts)\n if ts.length < 0\n raise Error, 'empty'\n end\n\n typ, _, val = ts[0]\n case typ\n when '{' then objparse(ts)\n when '[' then arrparse(ts)\n when :val,:str then [val, ts[1..-1]]\n e"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":40,"symbol":"decode","kind":"method","lang":"ruby","doc":"String s must be valid UTF-8. If you have a string in some other encoding, convert it first. String values in the resulting structure will be UTF-8.","code":"def decode(s)\n ts = lex(s)\n v, ts = textparse(ts)\n if ts.length > 0\n raise Error, 'trailing garbage'\n end\n v\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":54,"symbol":"textparse","kind":"method","lang":"ruby","doc":"Parses a \"json text\" in the sense of RFC 4627. Returns the parsed value and any trailing tokens. Note: this is almost the same as valparse, except that it does not accept atomic values.","code":"def textparse(ts)\n if ts.length < 0\n raise Error, 'empty'\n end\n\n typ, _, val = ts[0]\n case typ\n when '{' then objparse(ts)\n when '[' then arrparse(ts)\n else\n raise Error, \"unexpected #{val.inspect}\"\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":71,"symbol":"valparse","kind":"method","lang":"ruby","doc":"Parses a \"value\" in the sense of RFC 4627. Returns the parsed value and any trailing tokens.","code":"def valparse(ts)\n if ts.length < 0\n raise Error, 'empty'\n end\n\n typ, _, val = ts[0]\n case typ\n when '{' then objparse(ts)\n when '[' then arrparse(ts)\n when :val,:str then [val, ts[1..-1]]\n else\n raise Error, \"unexpected #{val.inspect}\"\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":89,"symbol":"objparse","kind":"method","lang":"ruby","doc":"Parses an \"object\" in the sense of RFC 4627. Returns the parsed value and any trailing tokens.","code":"def objparse(ts)\n ts = eat('{', ts)\n obj = {}\n\n if ts[0][0] == '}'\n return obj, ts[1..-1]\n end\n\n k, v, ts = pairparse(ts)\n obj[k] = v\n\n if ts[0][0] == '}'\n return obj, ts[1..-1]\n end\n\n loop do\n ts = eat(',', ts)\n\n k, v, ts = pairparse(ts)\n obj[k] = v\n\n if ts[0][0] == '}'\n return obj, ts[1..-1]\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":119,"symbol":"pairparse","kind":"method","lang":"ruby","doc":"Parses a \"member\" in the sense of RFC 4627. Returns the parsed values and any trailing tokens.","code":"def pairparse(ts)\n (typ, _, k), ts = ts[0], ts[1..-1]\n if typ != :str\n raise Error, \"unexpected #{k.inspect}\"\n end\n ts = eat(':', ts)\n v, ts = valparse(ts)\n [k, v, ts]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":132,"symbol":"arrparse","kind":"method","lang":"ruby","doc":"Parses an \"array\" in the sense of RFC 4627. Returns the parsed value and any trailing tokens.","code":"def arrparse(ts)\n ts = eat('[', ts)\n arr = []\n\n if ts[0][0] == ']'\n return arr, ts[1..-1]\n end\n\n v, ts = valparse(ts)\n arr << v\n\n if ts[0][0] == ']'\n return arr, ts[1..-1]\n end\n\n loop do\n ts = eat(',', ts)\n\n v, ts = valparse(ts)\n arr << v\n\n if ts[0][0] == ']'\n return arr, ts[1..-1]\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":160,"symbol":"eat","kind":"method","lang":"ruby","code":"def eat(typ, ts)\n if ts[0][0] != typ\n raise Error, \"expected #{typ} (got #{ts[0].inspect})\"\n end\n ts[1..-1]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":170,"symbol":"lex","kind":"method","lang":"ruby","doc":"Sans s and returns a list of json tokens, excluding white space (as defined in RFC 4627).","code":"def lex(s)\n ts = []\n while s.length > 0\n typ, lexeme, val = tok(s)\n if typ == nil\n raise Error, \"invalid character at #{s[0,10].inspect}\"\n end\n if typ != :space\n ts << [typ, lexeme, val]\n end\n s = s[lexeme.length..-1]\n end\n ts\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":199,"symbol":"tok","kind":"method","lang":"ruby","doc":"The second element is the lexeme. The third element is the value of the token for :val and :str, otherwise it is the lexeme.","code":"def tok(s)\n case s[0]\n when ?{ then ['{', s[0,1], s[0,1]]\n when ?} then ['}', s[0,1], s[0,1]]\n when ?: then [':', s[0,1], s[0,1]]\n when ?, then [',', s[0,1], s[0,1]]\n when ?[ then ['[', s[0,1], s[0,1]]\n when ?] then [']', s[0,1], s[0,1]]\n when ?n then nulltok(s)\n when ?t then truetok(s)\n when ?f then falsetok(s)\n when ?\" then strtok(s)\n when Spc then [:space, s[0,1], s[0,1]]\n when ?\\t then [:space, s[0,1], s[0,1]]\n when ?\\n then [:space, s[0,1], s[0,1]]\n when ?\\r then [:space, s[0,1], s[0,1]]\n else numtok(s)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":220,"symbol":"nulltok","kind":"method","lang":"ruby","code":"def nulltok(s); s[0,4] == 'null' && [:val, 'null', nil] end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":221,"symbol":"truetok","kind":"method","lang":"ruby","code":"def truetok(s); s[0,4] == 'true' && [:val, 'true', true] end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":222,"symbol":"falsetok","kind":"method","lang":"ruby","code":"def falsetok(s); s[0,5] == 'false' && [:val, 'false', false] end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":225,"symbol":"numtok","kind":"method","lang":"ruby","code":"def numtok(s)\n m = /-?([1-9][0-9]+|[0-9])([.][0-9]+)?([eE][+-]?[0-9]+)?/.match(s)\n if m && m.begin(0) == 0\n if m[3] && !m[2]\n [:val, m[0], Integer(m[1])*(10**Integer(m[3][1..-1]))]\n elsif m[2]\n [:val, m[0], Float(m[0])]\n else\n [:val, m[0], Integer(m[0])]\n end\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":239,"symbol":"strtok","kind":"method","lang":"ruby","code":"def strtok(s)\n m = /\"([^\"\\\\]|\\\\[\"\\/\\\\bfnrt]|\\\\u[0-9a-fA-F]{4})*\"/.match(s)\n if ! m\n raise Error, \"invalid string literal at #{abbrev(s)}\"\n end\n [:str, m[0], unquote(m[0])]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":248,"symbol":"abbrev","kind":"method","lang":"ruby","code":"def abbrev(s)\n t = s[0,10]\n p = t['`']\n t = t[0,p] if p\n t = t + '...' if t.length < s.length\n '`' + t + '`'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":260,"symbol":"unquote","kind":"method","lang":"ruby","doc":"Converts a quoted json string literal q into a UTF-8-encoded string. The rules are different than for Ruby, so we cannot use eval. Unquote will raise an error if q contains control characters.","code":"def unquote(q)\n q = q[1...-1]\n a = q.dup # allocate a big enough string\n r, w = 0, 0\n while r < q.length\n c = q[r]\n case true\n when c == ?\\\\\n r += 1\n if r >= q.length\n raise Error, \"string literal ends with a \\\"\\\\\\\": \\\"#{q}\\\"\"\n end\n\n case q[r]\n when ?\",?\\\\,?/,?'\n a[w] = q[r]\n r += 1\n w += 1\n when ?b,?f,?n,?r,?t\n a[w] = Unesc[q[r]]\n r += 1\n w += 1\n when ?u\n r += 1\n uchar = begin\n hexdec4(q[r,4])\n rescue RuntimeError => e\n raise Error, \"invalid escape sequence \\\\u#{q[r,4]}: #{e}\"\n end\n r += 4\n if surrogate? uchar\n if q.length >= r+6\n uchar1 = hexdec4(q[r+2,4])\n uchar = subst(uchar, uchar1)\n if uchar != Ucharerr\n # A valid pair; consume.\n r += 6\n end\n end\n end\n w += ucharenc(a, w, uchar)\n else\n raise Error, \"invalid escape char #{q[r]} in \\\"#{q}\\\"\"\n end\n when c == ?\", c < Spc\n raise Error, \"invalid character in string l"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":322,"symbol":"ucharenc","kind":"method","lang":"ruby","doc":"Encodes unicode character u as UTF-8 bytes in string a at position i. Returns the number of bytes written.","code":"def ucharenc(a, i, u)\n case true\n when u <= Uchar1max\n a[i] = (u & 0xff).chr\n 1\n when u <= Uchar2max\n a[i+0] = (Utag2 | ((u>>6)&0xff)).chr\n a[i+1] = (Utagx | (u&Umaskx)).chr\n 2\n when u <= Uchar3max\n a[i+0] = (Utag3 | ((u>>12)&0xff)).chr\n a[i+1] = (Utagx | ((u>>6)&Umaskx)).chr\n a[i+2] = (Utagx | (u&Umaskx)).chr\n 3\n else\n a[i+0] = (Utag4 | ((u>>18)&0xff)).chr\n a[i+1] = (Utagx | ((u>>12)&Umaskx)).chr\n a[i+2] = (Utagx | ((u>>6)&Umaskx)).chr\n a[i+3] = (Utagx | (u&Umaskx)).chr\n 4\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":346,"symbol":"hexdec4","kind":"method","lang":"ruby","code":"def hexdec4(s)\n if s.length != 4\n raise Error, 'short'\n end\n (nibble(s[0])<<12) | (nibble(s[1])<<8) | (nibble(s[2])<<4) | nibble(s[3])\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":354,"symbol":"subst","kind":"method","lang":"ruby","code":"def subst(u1, u2)\n if Usurr1 <= u1 && u1 < Usurr2 && Usurr2 <= u2 && u2 < Usurr3\n return ((u1-Usurr1)<<10) | (u2-Usurr2) + Usurrself\n end\n return Ucharerr\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":362,"symbol":"unsubst","kind":"method","lang":"ruby","code":"def unsubst(u)\n if u < Usurrself || u > Umax || surrogate?(u)\n return Ucharerr, Ucharerr\n end\n u -= Usurrself\n [Usurr1 + ((u>>10)&0x3ff), Usurr2 + (u&0x3ff)]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":371,"symbol":"surrogate?","kind":"method","lang":"ruby","code":"def surrogate?(u)\n Usurr1 <= u && u < Usurr3\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":376,"symbol":"nibble","kind":"method","lang":"ruby","code":"def nibble(c)\n case true\n when ?0 <= c && c <= ?9 then c.ord - ?0.ord\n when ?a <= c && c <= ?z then c.ord - ?a.ord + 10\n when ?A <= c && c <= ?Z then c.ord - ?A.ord + 10\n else\n raise Error, \"invalid hex code #{c}\"\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":396,"symbol":"encode","kind":"method","lang":"ruby","doc":"X itself must be an Array or a Hash. No other value can be encoded, and an error will be raised if x contains any other value, such as Nan, Infinity, Symbol, and Proc, or if a Hash key is not a String. Strings contained in x must be valid UTF-8.","code":"def encode(x)\n case x\n when Hash then objenc(x)\n when Array then arrenc(x)\n else\n raise Error, 'root value must be an Array or a Hash'\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":406,"symbol":"valenc","kind":"method","lang":"ruby","code":"def valenc(x)\n case x\n when Hash then objenc(x)\n when Array then arrenc(x)\n when String then strenc(x)\n when Numeric then numenc(x)\n when true then \"true\"\n when false then \"false\"\n when nil then \"null\"\n else\n raise Error, \"cannot encode #{x.class}: #{x.inspect}\"\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":421,"symbol":"objenc","kind":"method","lang":"ruby","code":"def objenc(x)\n '{' + x.map{|k,v| keyenc(k) + ':' + valenc(v)}.join(',') + '}'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":426,"symbol":"arrenc","kind":"method","lang":"ruby","code":"def arrenc(a)\n '[' + a.map{|x| valenc(x)}.join(',') + ']'\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":431,"symbol":"keyenc","kind":"method","lang":"ruby","code":"def keyenc(k)\n case k\n when String then strenc(k)\n else\n raise Error, \"Hash key is not a string: #{k.inspect}\"\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":440,"symbol":"strenc","kind":"method","lang":"ruby","code":"def strenc(s)\n t = StringIO.new\n t.putc(?\")\n r = 0\n while r < s.length\n case s[r]\n when ?\" then t.print('\\\\\"')\n when ?\\\\ then t.print('\\\\\\\\')\n when ?\\b then t.print('\\\\b')\n when ?\\f then t.print('\\\\f')\n when ?\\n then t.print('\\\\n')\n when ?\\r then t.print('\\\\r')\n when ?\\t then t.print('\\\\t')\n else\n c = s[r]\n case true\n when Spc <= c && c <= ?~\n t.putc(c)\n when true\n u, size = uchardec(s, r)\n r += size - 1 # we add one more at the bottom of the loop\n if u < 0x10000\n t.print('\\\\u')\n hexenc4(t, u)\n else\n u1, u2 = unsubst(u)\n t.print('\\\\u')\n hexenc4(t, u1)\n t.print('\\\\u')\n hexenc4(t, u2)\n end\n else\n # invalid byte; skip it\n end\n end\n r += 1\n end\n t.putc(?\")\n t.string\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":482,"symbol":"hexenc4","kind":"method","lang":"ruby","code":"def hexenc4(t, u)\n t.putc(Hex[(u>>12)&0xf])\n t.putc(Hex[(u>>8)&0xf])\n t.putc(Hex[(u>>4)&0xf])\n t.putc(Hex[u&0xf])\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":490,"symbol":"numenc","kind":"method","lang":"ruby","code":"def numenc(x)\n if x.nan? || x.infinite?\n return 'null'\n end rescue nil\n \"#{x}\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":501,"symbol":"uchardec","kind":"method","lang":"ruby","doc":"Decodes unicode character u from UTF-8 bytes in string s at position i. Returns u and the number of bytes read.","code":"def uchardec(s, i)\n n = s.length - i\n return [Ucharerr, 1] if n < 1\n\n c0 = s[i].ord\n\n # 1-byte, 7-bit sequence?\n if c0 < Utagx\n return [c0, 1]\n end\n\n # unexpected continuation byte?\n return [Ucharerr, 1] if c0 < Utag2\n\n # need continuation byte\n return [Ucharerr, 1] if n < 2\n c1 = s[i+1].ord\n return [Ucharerr, 1] if c1 < Utagx || Utag2 <= c1\n\n # 2-byte, 11-bit sequence?\n if c0 < Utag3\n u = (c0&Umask2)<<6 | (c1&Umaskx)\n return [Ucharerr, 1] if u <= Uchar1max\n return [u, 2]\n end\n\n # need second continuation byte\n return [Ucharerr, 1] if n < 3\n c2 = s[i+2].ord\n return [Ucharerr, 1] if c2 < Utagx || Utag2 <= c2\n\n # 3-byte, 16-bit sequence?\n if c0 < Utag4\n u = (c0&Umask3)<<12 | (c1&Umaskx)<<6 | (c2&Umaskx)\n return [Ucharerr, 1] if u <= Uchar2max\n return [u, 3]\n end\n\n # need third continuation byte\n return [Ucharerr, 1] if n < 4\n c3 = s[i+3].ord\n return [Ucharerr, 1] if c3 < Utagx || Utag2 <= c3\n\n # 4-byte, 21-bit sequence?\n if c0 < Utag5\n u = (c0&Umask4)<<18 | (c1&Umaskx)<<12 | (c2&Umaskx)<<6 | (c3&Umaskx)\n return [Ucharerr, 1] if u <= Uchar3max\n return ["}
{"repo":"sinatra","file":"sinatra-contrib/spec/okjson.rb","line":555,"symbol":"Error","kind":"class","lang":"ruby","code":"class Error < ::StandardError\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":6,"symbol":"tmp_dir","kind":"method","lang":"ruby","doc":"Returns the temporary directory.","code":"def tmp_dir\n File.expand_path('../tmp', __dir__)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":12,"symbol":"app_file_path","kind":"method","lang":"ruby","doc":"Returns the path of the Sinatra application file created by +setup_example_app+.","code":"def app_file_path\n File.join(tmp_dir, \"example_app_#{$example_app_counter}.rb\")\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":19,"symbol":"app_name","kind":"method","lang":"ruby","doc":"Returns the name of the Sinatra application created by +setup_example_app+: 'ExampleApp1' for the first application, 'ExampleApp2' fo the second one, and so on...","code":"def app_name\n \"ExampleApp#{$example_app_counter}\"\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":25,"symbol":"app_const","kind":"method","lang":"ruby","doc":"Returns the (constant of the) Sinatra application created by +setup_example_app+.","code":"def app_const\n Module.const_get(app_name)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":39,"symbol":"write_app_file","kind":"method","lang":"ruby","doc":"template's names as keys and the bodys as values (+:inline_templates+ key) and an optional application name (+:name+) otherwise +app_name+ is used. It ensures to change the written file's mtime when it already exists.","code":"def write_app_file(options={})\n options[:routes] ||= ['get(\"/foo\") { erb :foo }']\n options[:inline_templates] ||= nil\n options[:extensions] ||= []\n options[:middlewares] ||= []\n options[:filters] ||= []\n options[:errors] ||= {}\n options[:name] ||= app_name\n options[:enable_reloader] = true unless options[:enable_reloader] === false\n options[:parent] ||= 'Sinatra::Base'\n\n update_file(app_file_path) do |f|\n template_path = File.expand_path('reloader/app.rb.erb', __dir__)\n template = Tilt.new(template_path, nil, :trim => '<>')\n f.write template.render(Object.new, options)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":61,"symbol":"update_file","kind":"method","lang":"ruby","doc":"It calls <tt>File.open(path, 'w', &block)</tt> all the times needed to change the file's mtime.","code":"def update_file(path, &block)\n original_mtime = File.exist?(path) ? File.mtime(path) : Time.at(0)\n new_time = original_mtime + 1\n File.open(path, 'w', &block)\n File.utime(new_time, new_time, path)\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":71,"symbol":"setup_example_app","kind":"method","lang":"ruby","doc":"Writes a Sinatra application to a file, requires the file, sets the new application as the one being tested and enables the reloader.","code":"def setup_example_app(options={})\n $example_app_counter ||= 0\n $example_app_counter += 1\n\n FileUtils.mkdir_p(tmp_dir)\n write_app_file(options)\n $LOADED_FEATURES.delete app_file_path\n require app_file_path\n self.app = app_const\n app_const.enable :reloader\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":261,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(klass)\n klass.get('/bar') { 'bar' }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":282,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(klass)\n klass.use Rack::Head\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":303,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(klass)\n klass.before { @hi = 'hi' }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/reloader_spec.rb","line":324,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(klass)\n klass.after { @bye = 'bye' }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/respond_with_spec.rb","line":7,"symbol":"respond_app","kind":"method","lang":"ruby","code":"def respond_app(&block)\n mock_app do\n set :app_file, __FILE__\n set :views, root + '/respond_with'\n register Sinatra::RespondWith\n class_eval(&block)\n end\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/respond_with_spec.rb","line":16,"symbol":"respond_to","kind":"method","lang":"ruby","code":"def respond_to(*args, &block)\n respond_app { get('/') { respond_to(*args, &block) } }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/respond_with_spec.rb","line":20,"symbol":"respond_with","kind":"method","lang":"ruby","code":"def respond_with(*args, &block)\n respond_app { get('/') { respond_with(*args, &block) } }\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/respond_with_spec.rb","line":24,"symbol":"req","kind":"method","lang":"ruby","code":"def req(*types)\n path = types.shift if types.first.is_a?(String) && types.first.start_with?('/')\n accept = types.map { |t| Sinatra::Base.mime_type(t).to_s }.join ','\n get (path || '/'), {}, 'HTTP_ACCEPT' => accept\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/respond_with_spec.rb","line":221,"symbol":"to_pdf","kind":"method","lang":"ruby","code":"def object.to_pdf; \"hi\" end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":4,"symbol":"stream","kind":"method","lang":"ruby","code":"def stream(&block)\n rack_middleware = @use\n out = nil\n mock_app do\n rack_middleware.each { |args| use(*args) }\n helpers Sinatra::Streaming\n get('/') { out = stream(&block) }\n end\n get('/')\n out\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":16,"symbol":"use","kind":"method","lang":"ruby","code":"def use(*args)\n @use << args\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":147,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app) @app = app end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":148,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n body.map! { |s| s.upcase }\n [status, headers, body]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":172,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app) @app = app end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":173,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n [status, headers, body.map(&:upcase)]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":186,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app) @app = app end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":187,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n [status, headers, body.map(&:upcase).map(&:reverse)]\n end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":200,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app) @app = app end"}
{"repo":"sinatra","file":"sinatra-contrib/spec/streaming_spec.rb","line":201,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n status, headers, body = @app.call(env)\n [status, headers, body.each.map(&:upcase)]\n end"}
{"repo":"sinatra","file":"test/asciidoctor_test.rb","line":6,"symbol":"AsciidoctorTest","kind":"class","lang":"ruby","code":"class AsciidoctorTest < Minitest::Test\n def asciidoc_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline AsciiDoc strings' do\n asciidoc_app { asciidoc '== Hiya' }\n assert ok?\n assert_match %r{<h2.*?>Hiya</h2>}, body\n end\n\n it 'uses the correct engine' do\n engine = Tilt::AsciidoctorTemplate\n assert_equal engine, Tilt[:ad]\n assert_equal engine, Tilt[:adoc]\n assert_equal engine, Tilt[:asciidoc]\n end\n\n it 'renders .asciidoc files in views path' do\n asciidoc_app { asciidoc :hello }\n assert ok?\n assert_match %r{<h2.*?>Hello from AsciiDoc</h2>}, body\n end\n\n it 'raises error if template not found' do\n mock_app { get('/') { asciidoc :no_such_template } }\n assert_raises(Errno::ENOENT) { get('/') }\n end\n\n it 'renders with inline layouts' do\n mock_app do\n layout { 'THIS. IS. #{yield.upcase}!' }\n get('/') { asciidoc 'Sparta', :layout_engine => :str }\n end\n get '/'\n assert ok?\n assert_include body, 'THIS. IS.'\n assert_include body, '<P>SPARTA</P>'\n end\n\n it 'render"}
{"repo":"sinatra","file":"test/asciidoctor_test.rb","line":7,"symbol":"asciidoc_app","kind":"method","lang":"ruby","code":"def asciidoc_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":3,"symbol":"BaseTest","kind":"class","lang":"ruby","code":"class BaseTest < Minitest::Test\n describe 'Sinatra::Base subclasses' do\n class TestApp < Sinatra::Base\n get('/') { 'Hello World' }\n end\n\n class TestKeywordArgumentInitializerApp < Sinatra::Base\n def initialize(argument:)\n @argument = argument\n end\n\n get('/') { \"Hello World with Keyword Arguments: #{@argument}\" }\n end\n\n it 'include Rack::Utils' do\n assert TestApp.included_modules.include?(Rack::Utils)\n end\n\n it 'processes requests with #call' do\n assert TestApp.respond_to?(:call)\n\n request = Rack::MockRequest.new(TestApp)\n response = request.get('/')\n assert response.ok?\n assert_equal 'Hello World', response.body\n end\n\n class TestApp < Sinatra::Base\n get '/state' do\n @foo ||= \"new\"\n body = \"Foo: #{@foo}\"\n @foo = 'discard'\n body\n end\n end\n\n it 'does not maintain state between requests' do\n request = Rack::MockRequest.new(TestApp)\n 2.times do\n response = request.get('/state')\n assert response.ok?\n assert_equal 'Foo: new', response.body\n end\n end\n\n it \"passes the subclass to configure blocks\" do\n ref = nil\n "}
{"repo":"sinatra","file":"test/base_test.rb","line":5,"symbol":"TestApp","kind":"class","lang":"ruby","code":"class TestApp < Sinatra::Base\n get('/') { 'Hello World' }\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":9,"symbol":"TestKeywordArgumentInitializerApp","kind":"class","lang":"ruby","code":"class TestKeywordArgumentInitializerApp < Sinatra::Base\n def initialize(argument:)\n @argument = argument\n end\n\n get('/') { \"Hello World with Keyword Arguments: #{@argument}\" }\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":10,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(argument:)\n @argument = argument\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":30,"symbol":"TestApp","kind":"class","lang":"ruby","code":"class TestApp < Sinatra::Base\n get '/state' do\n @foo ||= \"new\"\n body = \"Foo: #{@foo}\"\n @foo = 'discard'\n body\n end\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":95,"symbol":"TestMiddleware","kind":"class","lang":"ruby","code":"class TestMiddleware < Sinatra::Base\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":108,"symbol":"TestMiddleware","kind":"class","lang":"ruby","code":"class TestMiddleware < Sinatra::Base\n def route_missing\n env['sinatra.route-missing'] = '1'\n super\n end\n\n get('/') { 'Hello from middleware' }\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":109,"symbol":"route_missing","kind":"method","lang":"ruby","code":"def route_missing\n env['sinatra.route-missing'] = '1'\n super\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":137,"symbol":"TestMiddleware","kind":"class","lang":"ruby","code":"class TestMiddleware < Sinatra::Base\n get('/low-level-forward') { app.call(env) }\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":148,"symbol":"TestMiddleware","kind":"class","lang":"ruby","code":"class TestMiddleware < Sinatra::Base\n get '/explicit-forward' do\n response['X-Middleware'] = 'true'\n res = forward\n assert_nil res\n assert_equal 210, response.status\n assert_equal 'true', response['X-Downstream']\n assert_equal ['Hello from downstream'], response.body\n 'Hello after explicit forward'\n end\n end"}
{"repo":"sinatra","file":"test/base_test.rb","line":171,"symbol":"TestMiddlewareContentLength","kind":"class","lang":"ruby","code":"class TestMiddlewareContentLength < Sinatra::Base\n get '/forward' do\n 'From after explicit forward!'\n end\n end"}
{"repo":"sinatra","file":"test/builder_test.rb","line":6,"symbol":"BuilderTest","kind":"class","lang":"ruby","code":"class BuilderTest < Minitest::Test\n def builder_app(options = {}, &block)\n mock_app do\n set :views, __dir__ + '/views'\n set options\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline Builder strings' do\n builder_app { builder 'xml.instruct!' }\n assert ok?\n assert_equal %{<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n}, body\n end\n\n it 'defaults content type to xml' do\n builder_app { builder 'xml.instruct!' }\n assert ok?\n assert_equal \"application/xml;charset=utf-8\", response['Content-Type']\n end\n\n it 'defaults allows setting content type per route' do\n builder_app do\n content_type :html\n builder 'xml.instruct!'\n end\n assert ok?\n assert_equal \"text/html;charset=utf-8\", response['Content-Type']\n end\n\n it 'defaults allows setting content type globally' do\n builder_app(:builder => { :content_type => 'html' }) do\n builder 'xml.instruct!'\n end\n assert ok?\n assert_equal \"text/html;charset=utf-8\", response['Content-Type']\n end\n\n it 'renders inline blocks' do\n builder_app do\n @name = \"Frank & Mary\"\n builder { |xml| xml.couple @name }\n end\n assert ok?\n assert_equal \"<couple>Frank"}
{"repo":"sinatra","file":"test/builder_test.rb","line":7,"symbol":"builder_app","kind":"method","lang":"ruby","code":"def builder_app(options = {}, &block)\n mock_app do\n set :views, __dir__ + '/views'\n set options\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/compile_test.rb","line":3,"symbol":"CompileTest","kind":"class","lang":"ruby","code":"class CompileTest < Minitest::Test\n def self.parses pattern, example, expected_params, mtype = :sinatra, mopts = {}\n it \"parses #{example} with #{pattern} into params #{expected_params}\" do\n compiled = mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts)\n params = compiled.params(example)\n fail %Q{\"#{example}\" does not parse on pattern \"#{pattern}\".} unless params\n\n assert_equal expected_params, params, \"Pattern #{pattern} does not match path #{example}.\"\n end\n end\n\n def self.fails pattern, example, mtype = :sinatra, mopts = {}\n it \"does not parse #{example} with #{pattern}\" do\n compiled = mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts)\n match = compiled.match(example)\n fail %Q{\"#{pattern}\" does parse \"#{example}\" but it should fail} if match\n end\n end\n\n def self.raises pattern, mtype = :sinatra, mopts = {}\n it \"does not compile #{pattern}\" do\n assert_raises(Mustermann::CompileError, %Q{Pattern \"#{pattern}\" compiles but it should not}) do\n mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts)\n end\n end\n end\n\n parses \"/\""}
{"repo":"sinatra","file":"test/compile_test.rb","line":4,"symbol":"parses","kind":"method","lang":"ruby","code":"def self.parses pattern, example, expected_params, mtype = :sinatra, mopts = {}\n it \"parses #{example} with #{pattern} into params #{expected_params}\" do\n compiled = mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts)\n params = compiled.params(example)\n fail %Q{\"#{example}\" does not parse on pattern \"#{pattern}\".} unless params\n\n assert_equal expected_params, params, \"Pattern #{pattern} does not match path #{example}.\"\n end\n end"}
{"repo":"sinatra","file":"test/compile_test.rb","line":14,"symbol":"fails","kind":"method","lang":"ruby","code":"def self.fails pattern, example, mtype = :sinatra, mopts = {}\n it \"does not parse #{example} with #{pattern}\" do\n compiled = mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts)\n match = compiled.match(example)\n fail %Q{\"#{pattern}\" does parse \"#{example}\" but it should fail} if match\n end\n end"}
{"repo":"sinatra","file":"test/compile_test.rb","line":22,"symbol":"raises","kind":"method","lang":"ruby","code":"def self.raises pattern, mtype = :sinatra, mopts = {}\n it \"does not compile #{pattern}\" do\n assert_raises(Mustermann::CompileError, %Q{Pattern \"#{pattern}\" compiles but it should not}) do\n mock_app { set :mustermann_opts, :type => mtype }.send(:compile, pattern, mopts)\n end\n end\n end"}
{"repo":"sinatra","file":"test/contest.rb","line":29,"symbol":"setup","kind":"method","lang":"ruby","code":"def self.setup(&block) setup_blocks << block end"}
{"repo":"sinatra","file":"test/contest.rb","line":30,"symbol":"teardown","kind":"method","lang":"ruby","code":"def self.teardown(&block) teardown_blocks << block end"}
{"repo":"sinatra","file":"test/contest.rb","line":31,"symbol":"setup_blocks","kind":"method","lang":"ruby","code":"def self.setup_blocks() @setup_blocks ||= [] end"}
{"repo":"sinatra","file":"test/contest.rb","line":32,"symbol":"teardown_blocks","kind":"method","lang":"ruby","code":"def self.teardown_blocks() @teardown_blocks ||= [] end"}
{"repo":"sinatra","file":"test/contest.rb","line":34,"symbol":"setup_blocks","kind":"method","lang":"ruby","code":"def setup_blocks(base = self.class)\n setup_blocks base.superclass if base.superclass.respond_to? :setup_blocks\n base.setup_blocks.each do |block|\n instance_eval(&block)\n end\n end"}
{"repo":"sinatra","file":"test/contest.rb","line":41,"symbol":"teardown_blocks","kind":"method","lang":"ruby","code":"def teardown_blocks(base = self.class)\n teardown_blocks base.superclass if base.superclass.respond_to? :teardown_blocks\n base.teardown_blocks.each do |block|\n instance_eval(&block)\n end\n end"}
{"repo":"sinatra","file":"test/contest.rb","line":51,"symbol":"context","kind":"method","lang":"ruby","code":"def self.context(*name, &block)\n subclass = Class.new(self)\n remove_tests(subclass)\n subclass.class_eval(&block) if block_given?\n const_set(context_name(name.join(\" \")), subclass)\n end"}
{"repo":"sinatra","file":"test/contest.rb","line":58,"symbol":"test","kind":"method","lang":"ruby","code":"def self.test(name, &block)\n define_method(test_name(name), &block)\n end"}
{"repo":"sinatra","file":"test/contest.rb","line":69,"symbol":"context_name","kind":"method","lang":"ruby","code":"def self.context_name(name)\n # \"Test#{sanitize_name(name).gsub(/(^| )(\\w)/) { $2.upcase }}\".to_sym\n name = \"Test#{sanitize_name(name).gsub(/(^| )(\\w)/) { $2.upcase }}\"\n name.tr(\" \", \"_\").to_sym\n end"}
{"repo":"sinatra","file":"test/contest.rb","line":75,"symbol":"test_name","kind":"method","lang":"ruby","code":"def self.test_name(name)\n name = \"test_#{sanitize_name(name).gsub(/\\s+/,'_')}_0\"\n name = name.succ while method_defined? name\n name.to_sym\n end"}
{"repo":"sinatra","file":"test/contest.rb","line":81,"symbol":"sanitize_name","kind":"method","lang":"ruby","code":"def self.sanitize_name(name)\n # name.gsub(/\\W+/, ' ').strip\n name.gsub(/\\W+/, ' ')\n end"}
{"repo":"sinatra","file":"test/contest.rb","line":86,"symbol":"remove_tests","kind":"method","lang":"ruby","code":"def self.remove_tests(subclass)\n subclass.public_instance_methods.grep(/^test_/).each do |meth|\n subclass.send(:undef_method, meth.to_sym)\n end\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":3,"symbol":"DelegatorTest","kind":"class","lang":"ruby","code":"class DelegatorTest < Minitest::Test\n class Mirror\n attr_reader :last_call\n def method_missing(*a, &b)\n @last_call = [*a.map(&:to_s)]\n @last_call << b if b\n end\n end\n\n def self.delegates(name)\n it \"delegates #{name}\" do\n m = mirror { send name }\n assert_equal [name.to_s], m.last_call\n end\n\n it \"delegates #{name} with arguments\" do\n m = mirror { send name, \"foo\", \"bar\" }\n assert_equal [name.to_s, \"foo\", \"bar\"], m.last_call\n end\n\n it \"delegates #{name} with block\" do\n block = proc { }\n m = mirror { send(name, &block) }\n assert_equal [name.to_s, block], m.last_call\n end\n end\n\n setup do\n @target_was = Sinatra::Delegator.target\n end\n\n def teardown\n Sinatra::Delegator.target = @target_was\n end\n\n def delegation_app(&block)\n mock_app { Sinatra::Delegator.target = self }\n delegate(&block)\n end\n\n def mirror(&block)\n mirror = Mirror.new\n Sinatra::Delegator.target = mirror\n delegate(&block)\n end\n\n def delegate(&block)\n assert Sinatra::Delegator.target != Sinatra::Application\n Object.new.extend(Sinatra::Delegator).instance_eval(&block) if block\n Sinatra::Delegator.target\n end\n\n d"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":4,"symbol":"Mirror","kind":"class","lang":"ruby","code":"class Mirror\n attr_reader :last_call\n def method_missing(*a, &b)\n @last_call = [*a.map(&:to_s)]\n @last_call << b if b\n end\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":6,"symbol":"method_missing","kind":"method","lang":"ruby","code":"def method_missing(*a, &b)\n @last_call = [*a.map(&:to_s)]\n @last_call << b if b\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":12,"symbol":"delegates","kind":"method","lang":"ruby","code":"def self.delegates(name)\n it \"delegates #{name}\" do\n m = mirror { send name }\n assert_equal [name.to_s], m.last_call\n end\n\n it \"delegates #{name} with arguments\" do\n m = mirror { send name, \"foo\", \"bar\" }\n assert_equal [name.to_s, \"foo\", \"bar\"], m.last_call\n end\n\n it \"delegates #{name} with block\" do\n block = proc { }\n m = mirror { send(name, &block) }\n assert_equal [name.to_s, block], m.last_call\n end\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":34,"symbol":"teardown","kind":"method","lang":"ruby","code":"def teardown\n Sinatra::Delegator.target = @target_was\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":38,"symbol":"delegation_app","kind":"method","lang":"ruby","code":"def delegation_app(&block)\n mock_app { Sinatra::Delegator.target = self }\n delegate(&block)\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":43,"symbol":"mirror","kind":"method","lang":"ruby","code":"def mirror(&block)\n mirror = Mirror.new\n Sinatra::Delegator.target = mirror\n delegate(&block)\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":49,"symbol":"delegate","kind":"method","lang":"ruby","code":"def delegate(&block)\n assert Sinatra::Delegator.target != Sinatra::Application\n Object.new.extend(Sinatra::Delegator).instance_eval(&block) if block\n Sinatra::Delegator.target\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":55,"symbol":"target","kind":"method","lang":"ruby","code":"def target\n Sinatra::Delegator.target\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":122,"symbol":"respond_to?","kind":"method","lang":"ruby","code":"def respond_to?(method, *)\n method.to_sym == :options or super\n end"}
{"repo":"sinatra","file":"test/delegator_test.rb","line":126,"symbol":"method_missing","kind":"method","lang":"ruby","code":"def method_missing(method, *args, &block)\n return super unless method.to_sym == :options\n {:some => :option}\n end"}
{"repo":"sinatra","file":"test/encoding_test.rb","line":4,"symbol":"BaseTest","kind":"class","lang":"ruby","code":"class BaseTest < Minitest::Test\n setup do\n @base = Sinatra.new(Sinatra::Base)\n @base.set :views, __dir__ + \"/views\"\n end\n\n it 'allows unicode strings in ascii templates per default (1.9)' do\n next unless defined? Encoding\n @base.new!.erb(File.read(@base.views + \"/ascii.erb\").encode(\"ASCII\"), {}, :value => \"åkej\")\n end\n\n it 'allows ascii strings in unicode templates per default (1.9)' do\n next unless defined? Encoding\n @base.new!.erb(:utf8, {}, :value => \"Some Lyrics\".encode(\"ASCII\"))\n end\nend"}
{"repo":"sinatra","file":"test/erb_test.rb","line":3,"symbol":"ERBTest","kind":"class","lang":"ruby","code":"class ERBTest < Minitest::Test\n def engine\n Tilt::ERBTemplate\n end\n\n def setup\n Tilt.prefer engine, :erb\n super\n end\n\n def erb_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'uses the correct engine' do\n assert_equal engine, Tilt[:erb]\n end\n\n it 'renders inline ERB strings' do\n erb_app { erb '<%= 1 + 1 %>' }\n assert ok?\n assert_equal '2', body\n end\n\n it 'renders .erb files in views path' do\n erb_app { erb :hello }\n assert ok?\n assert_equal \"Hello World\\n\", body\n end\n\n it 'takes a :locals option' do\n erb_app do\n locals = {:foo => 'Bar'}\n erb '<%= foo %>', :locals => locals\n end\n assert ok?\n assert_equal 'Bar', body\n end\n\n it \"renders with inline layouts\" do\n mock_app do\n layout { 'THIS. IS. <%= yield.upcase %>!' }\n get('/') { erb 'Sparta' }\n end\n get '/'\n assert ok?\n assert_equal 'THIS. IS. SPARTA!', body\n end\n\n it \"renders with file layouts\" do\n erb_app { erb 'Hello World', :layout => :layout2 }\n assert ok?\n assert_body \"ERB Layout!\\nHello World\"\n end\n\n it \"renders erb with blocks\" do\n mock_app do\n de"}
{"repo":"sinatra","file":"test/erb_test.rb","line":4,"symbol":"engine","kind":"method","lang":"ruby","code":"def engine\n Tilt::ERBTemplate\n end"}
{"repo":"sinatra","file":"test/erb_test.rb","line":8,"symbol":"setup","kind":"method","lang":"ruby","code":"def setup\n Tilt.prefer engine, :erb\n super\n end"}
{"repo":"sinatra","file":"test/erb_test.rb","line":13,"symbol":"erb_app","kind":"method","lang":"ruby","code":"def erb_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/erb_test.rb","line":64,"symbol":"container","kind":"method","lang":"ruby","code":"def container\n @_out_buf << \"THIS.\"\n yield\n @_out_buf << \"SPARTA!\"\n end"}
{"repo":"sinatra","file":"test/erb_test.rb","line":69,"symbol":"is","kind":"method","lang":"ruby","code":"def is; \"IS.\" end"}
{"repo":"sinatra","file":"test/erb_test.rb","line":110,"symbol":"ErubiTest","kind":"class","lang":"ruby","code":"class ErubiTest < ERBTest\n def engine; Tilt::ErubiTemplate end\n end"}
{"repo":"sinatra","file":"test/erb_test.rb","line":111,"symbol":"engine","kind":"method","lang":"ruby","code":"def engine; Tilt::ErubiTemplate end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":3,"symbol":"ExtensionsTest","kind":"class","lang":"ruby","code":"class ExtensionsTest < Minitest::Test\n module FooExtensions\n def foo\n end\n\n private\n def im_hiding_in_ur_foos\n end\n end\n\n module BarExtensions\n def bar\n end\n end\n\n module BazExtensions\n def baz\n end\n end\n\n module QuuxExtensions\n def quux\n end\n end\n\n module PainExtensions\n def foo=(name); end\n def bar?(name); end\n def fizz!(name); end\n end\n\n it 'will add the methods to the DSL for the class in which you register them and its subclasses' do\n Sinatra::Base.register FooExtensions\n assert Sinatra::Base.respond_to?(:foo)\n\n Sinatra::Application.register BarExtensions\n assert Sinatra::Application.respond_to?(:bar)\n assert Sinatra::Application.respond_to?(:foo)\n assert !Sinatra::Base.respond_to?(:bar)\n end\n\n it 'allows extending by passing a block' do\n Sinatra::Base.register { def im_in_ur_anonymous_module; end }\n assert Sinatra::Base.respond_to?(:im_in_ur_anonymous_module)\n end\n\n it 'will make sure any public methods added via Application#register are delegated to Sinatra::Delegator' do\n Sinatra::Application.register FooExtensions\n assert Sinatra::Delegator.private_instance_methods.\n map { |m| m"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":4,"symbol":"FooExtensions","kind":"module","lang":"ruby","code":"module FooExtensions\n def foo\n end\n\n private\n def im_hiding_in_ur_foos\n end\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":5,"symbol":"foo","kind":"method","lang":"ruby","code":"def foo\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":9,"symbol":"im_hiding_in_ur_foos","kind":"method","lang":"ruby","code":"def im_hiding_in_ur_foos\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":13,"symbol":"BarExtensions","kind":"module","lang":"ruby","code":"module BarExtensions\n def bar\n end\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":14,"symbol":"bar","kind":"method","lang":"ruby","code":"def bar\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":18,"symbol":"BazExtensions","kind":"module","lang":"ruby","code":"module BazExtensions\n def baz\n end\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":19,"symbol":"baz","kind":"method","lang":"ruby","code":"def baz\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":23,"symbol":"QuuxExtensions","kind":"module","lang":"ruby","code":"module QuuxExtensions\n def quux\n end\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":24,"symbol":"quux","kind":"method","lang":"ruby","code":"def quux\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":28,"symbol":"PainExtensions","kind":"module","lang":"ruby","code":"module PainExtensions\n def foo=(name); end\n def bar?(name); end\n def fizz!(name); end\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":30,"symbol":"bar?","kind":"method","lang":"ruby","code":"def bar?(name); end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":31,"symbol":"fizz!","kind":"method","lang":"ruby","code":"def fizz!(name); end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":45,"symbol":"im_in_ur_anonymous_module","kind":"method","lang":"ruby","code":"def im_in_ur_anonymous_module; end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":78,"symbol":"BizzleExtension","kind":"module","lang":"ruby","code":"module BizzleExtension\n def bizzle\n bizzle_option\n end\n\n def self.registered(base)\n fail \"base should be BizzleApp\" unless base == BizzleApp\n fail \"base should have already extended BizzleExtension\" unless base.respond_to?(:bizzle)\n base.set :bizzle_option, 'bizzle!'\n end\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":79,"symbol":"bizzle","kind":"method","lang":"ruby","code":"def bizzle\n bizzle_option\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":83,"symbol":"registered","kind":"method","lang":"ruby","code":"def self.registered(base)\n fail \"base should be BizzleApp\" unless base == BizzleApp\n fail \"base should have already extended BizzleExtension\" unless base.respond_to?(:bizzle)\n base.set :bizzle_option, 'bizzle!'\n end"}
{"repo":"sinatra","file":"test/extensions_test.rb","line":90,"symbol":"BizzleApp","kind":"class","lang":"ruby","code":"class BizzleApp < Sinatra::Base\n end"}
{"repo":"sinatra","file":"test/filter_test.rb","line":3,"symbol":"BeforeFilterTest","kind":"class","lang":"ruby","code":"class BeforeFilterTest < Minitest::Test\n it \"executes filters in the order defined\" do\n count = 0\n mock_app do\n get('/') { 'Hello World' }\n before do\n assert_equal 0, count\n count = 1\n end\n before do\n assert_equal 1, count\n count = 2\n end\n end\n\n get '/'\n assert ok?\n assert_equal 2, count\n assert_equal 'Hello World', body\n end\n\n it \"can modify the request\" do\n mock_app do\n get('/foo') { 'foo' }\n get('/bar') { 'bar' }\n before { request.path_info = '/bar' }\n end\n\n get '/foo'\n assert ok?\n assert_equal 'bar', body\n end\n\n it \"can modify instance variables available to routes\" do\n mock_app do\n before { @foo = 'bar' }\n get('/foo') { @foo }\n end\n\n get '/foo'\n assert ok?\n assert_equal 'bar', body\n end\n\n it \"allows redirects\" do\n mock_app do\n before { redirect '/bar' }\n get('/foo') do\n fail 'before block should have halted processing'\n 'ORLY?!'\n end\n end\n\n get '/foo'\n assert redirect?\n assert_equal 'http://example.org/bar', response['Location']\n assert_equal '', body\n end\n\n it \"does not modify the response with"}
{"repo":"sinatra","file":"test/filter_test.rb","line":179,"symbol":"AfterFilterTest","kind":"class","lang":"ruby","code":"class AfterFilterTest < Minitest::Test\n it \"executes before and after filters in correct order\" do\n invoked = 0\n mock_app do\n before { invoked = 2 }\n get('/') { invoked += 2; 'hello' }\n after { invoked *= 2 }\n end\n\n get '/'\n assert ok?\n\n assert_equal 8, invoked\n end\n\n it \"executes filters in the order defined\" do\n count = 0\n mock_app do\n get('/') { 'Hello World' }\n after do\n assert_equal 0, count\n count = 1\n end\n after do\n assert_equal 1, count\n count = 2\n end\n end\n\n get '/'\n assert ok?\n assert_equal 2, count\n assert_equal 'Hello World', body\n end\n\n it \"allows redirects\" do\n mock_app do\n get('/foo') { 'ORLY' }\n after { redirect '/bar' }\n end\n\n get '/foo'\n assert redirect?\n assert_equal 'http://example.org/bar', response['Location']\n assert_equal '', body\n end\n\n it \"does not modify the response with its return value\" do\n mock_app do\n get('/foo') { 'cool' }\n after { 'Hello World!' }\n end\n\n get '/foo'\n assert ok?\n assert_equal 'cool', body\n end\n\n it \"does modify the response with halt\" do\n mock_app do\n get"}
{"repo":"sinatra","file":"test/haml_test.rb","line":6,"symbol":"HAMLTest","kind":"class","lang":"ruby","code":"class HAMLTest < Minitest::Test\n def haml_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline HAML strings' do\n haml_app { haml '%h1 Hiya' }\n assert ok?\n assert_equal \"<h1>Hiya</h1>\\n\", body\n end\n\n it 'renders .haml files in views path' do\n haml_app { haml :hello }\n assert ok?\n assert_equal \"<h1>Hello From Haml</h1>\\n\", body\n end\n\n it \"renders with inline layouts\" do\n mock_app do\n layout { %q(%h1!= 'THIS. IS. ' + yield.upcase) }\n get('/') { haml '%em Sparta' }\n end\n get '/'\n assert ok?\n assert_equal \"<h1>THIS. IS. <EM>SPARTA</EM>\\n</h1>\\n\", body\n end\n\n it \"renders with file layouts\" do\n haml_app { haml 'Hello World', :layout => :layout2 }\n assert ok?\n assert_equal \"<h1>HAML Layout!</h1>\\n<p>Hello World\\n</p>\\n\", body\n end\n\n it \"raises error if template not found\" do\n mock_app { get('/') { haml :no_such_template } }\n assert_raises(Errno::ENOENT) { get('/') }\n end\n\n it \"passes HAML options to the Haml engine\" do\n mock_app {\n get('/') { haml \"!!!\\n%h1 Hello World\", :format => :html5 }\n }\n get '/'\n assert ok?\n asser"}
{"repo":"sinatra","file":"test/haml_test.rb","line":7,"symbol":"haml_app","kind":"method","lang":"ruby","code":"def haml_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":5,"symbol":"HelpersTest","kind":"class","lang":"ruby","code":"class HelpersTest < Minitest::Test\n def test_default\n assert true\n end\n\n def status_app(code, &block)\n code += 2 if [204, 304].include? code\n block ||= proc { }\n mock_app do\n get('/') do\n status code\n instance_eval(&block).inspect\n end\n end\n get '/'\n end\n\n describe 'status' do\n it 'sets the response status code' do\n status_app 207\n assert_equal 207, response.status\n end\n end\n\n describe 'bad_request?' do\n it 'is true for status == 400' do\n status_app(400) { bad_request? }\n assert_body 'true'\n end\n\n it 'is false for status gt 400' do\n status_app(401) { bad_request? }\n assert_body 'false'\n end\n\n it 'is false for status lt 400' do\n status_app(399) { bad_request? }\n assert_body 'false'\n end\n end\n\n describe 'not_found?' do\n it 'is true for status == 404' do\n status_app(404) { not_found? }\n assert_body 'true'\n end\n\n it 'is false for status gt 404' do\n status_app(405) { not_found? }\n assert_body 'false'\n end\n\n it 'is false for status lt 404' do\n status_app(403) { not_found? }\n assert_body 'false'\n end\n end\n\n describe 'informati"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":6,"symbol":"test_default","kind":"method","lang":"ruby","code":"def test_default\n assert true\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":10,"symbol":"status_app","kind":"method","lang":"ruby","code":"def status_app(code, &block)\n code += 2 if [204, 304].include? code\n block ||= proc { }\n mock_app do\n get('/') do\n status code\n instance_eval(&block).inspect\n end\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":761,"symbol":"attachment_app","kind":"method","lang":"ruby","code":"def attachment_app(filename=nil)\n mock_app do\n get('/attachment') do\n attachment filename\n response.write(\"<sinatra></sinatra>\")\n end\n end\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":818,"symbol":"teardown","kind":"method","lang":"ruby","code":"def teardown\n File.unlink @file\n @file = nil\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":823,"symbol":"send_file_app","kind":"method","lang":"ruby","code":"def send_file_app(opts={})\n path = @file\n mock_app {\n get '/file.txt' do\n send_file path, opts\n end\n }\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":1012,"symbol":"method_missing","kind":"method","lang":"ruby","code":"def obj.method_missing(*a, &b) 60.send(*a, &b) end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":1013,"symbol":"is_a?","kind":"method","lang":"ruby","code":"def obj.is_a?(thing) 60.is_a?(thing) end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":1944,"symbol":"one","kind":"method","lang":"ruby","code":"def one; '1'; end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":1945,"symbol":"two","kind":"method","lang":"ruby","code":"def two; '2'; end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":1967,"symbol":"foo","kind":"method","lang":"ruby","code":"def foo\n 'foo'\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":1998,"symbol":"one","kind":"method","lang":"ruby","code":"def one; nil end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":1999,"symbol":"two","kind":"method","lang":"ruby","code":"def two; nil end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2003,"symbol":"two","kind":"method","lang":"ruby","code":"def two; '2' end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2017,"symbol":"HelpersOverloadingBaseHelper","kind":"module","lang":"ruby","code":"module HelpersOverloadingBaseHelper\n def my_test\n 'BaseHelper#test'\n end\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2018,"symbol":"my_test","kind":"method","lang":"ruby","code":"def my_test\n 'BaseHelper#test'\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2023,"symbol":"HelpersOverloadingIncludeAndOverride","kind":"class","lang":"ruby","code":"class HelpersOverloadingIncludeAndOverride < Sinatra::Base\n helpers HelpersOverloadingBaseHelper\n\n get '/' do\n my_test\n end\n\n helpers do\n def my_test\n 'InlineHelper#test'\n end\n end\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2031,"symbol":"my_test","kind":"method","lang":"ruby","code":"def my_test\n 'InlineHelper#test'\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2044,"symbol":"HelperWithIncluded","kind":"module","lang":"ruby","code":"module HelperWithIncluded\n def self.included(base)\n base.extend(ClassMethods)\n end\n\n module ClassMethods\n def nickname(name)\n # do something.\n end\n end\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2045,"symbol":"included","kind":"method","lang":"ruby","code":"def self.included(base)\n base.extend(ClassMethods)\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2049,"symbol":"ClassMethods","kind":"module","lang":"ruby","code":"module ClassMethods\n def nickname(name)\n # do something.\n end\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2050,"symbol":"nickname","kind":"method","lang":"ruby","code":"def nickname(name)\n # do something.\n end"}
{"repo":"sinatra","file":"test/helpers_test.rb","line":2056,"symbol":"ServerApp","kind":"class","lang":"ruby","code":"class ServerApp < Sinatra::Base\n helpers HelperWithIncluded\n # `nickname` method should be available.\n end"}
{"repo":"sinatra","file":"test/host_authorization_test.rb","line":5,"symbol":"HostAuthorization","kind":"class","lang":"ruby","code":"class HostAuthorization < Minitest::Test\n describe \"in development environment\" do\n setup do\n Sinatra::Base.set :environment, :development\n end\n\n %w[\n 127.0.0.1\n 127.0.0.1:3000\n [::1]\n [::1]:3000\n localhost\n localhost:3000\n foo.localhost\n foo.test\n ].each do |development_host|\n it \"allows a host like '#{development_host}'\" do\n mock_app do\n get(\"/\") { \"OK\" }\n end\n\n headers = { \"HTTP_HOST\" => development_host }\n request = Rack::MockRequest.new(@app)\n response = request.get(\"/\", headers)\n\n assert_equal 200, response.status\n assert_equal \"OK\", response.body\n end\n end\n\n it \"stops non-development hosts by default\" do\n mock_app { get(\"/\") { \"OK\" } }\n\n get \"/\", { \"HTTP_HOST\" => \"example.com\" }\n\n assert_equal 403, response.status\n assert_equal \"Host not permitted\", body\n end\n\n it \"allows any requests when no permitted hosts are specified\" do\n mock_app do\n set :host_authorization, { permitted_hosts: [] }\n get(\"/\") { \"OK\" }\n end\n\n get \"/\", { \"HTTP_HOST\" => \"example.com\" }\n\n assert_equal 200, response.sta"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":9,"symbol":"TestIndifferentHashBasics","kind":"class","lang":"ruby","code":"class TestIndifferentHashBasics < Minitest::Test\n def test_flattened_constructor\n hash = Sinatra::IndifferentHash[:a, 1, ?b, 2]\n assert_equal 1, hash[?a]\n assert_equal 2, hash[?b]\n end\n\n def test_pairs_constructor\n hash = Sinatra::IndifferentHash[[[:a, 1], [?b, 2]]]\n assert_equal 1, hash[?a]\n assert_equal 2, hash[?b]\n end\n\n def test_default_block\n hash = Sinatra::IndifferentHash.new { |h, k| h[k] = k.upcase }\n assert_nil hash.default\n assert_equal ?A, hash.default(:a)\n end\n\n def test_default_object\n hash = Sinatra::IndifferentHash.new({:a=>1, ?b=>2})\n assert_equal({ :a=>1, ?b=>2 }, hash.default)\n assert_equal({ :a=>1, ?b=>2 }, hash[:a])\n end\n\n def test_default_assignment\n hash = Sinatra::IndifferentHash.new\n hash.default = { :a=>1, ?b=>2 }\n assert_equal({ ?a=>1, ?b=>2 }, hash.default)\n assert_equal({ ?a=>1, ?b=>2 }, hash[:a])\n end\n\n def test_assignment\n hash = Sinatra::IndifferentHash.new\n hash[:a] = :a\n hash[?b] = :b\n hash[3] = 3\n hash[:simple_nested] = { :a=>:a, ?b=>:b }\n\n assert_equal :a, hash[?a]\n assert_equal :b, hash[?b]\n assert_equal 3, hash[3]\n assert_equal({ ?a=>:a, ?b=>:b }, hash['simple"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":10,"symbol":"test_flattened_constructor","kind":"method","lang":"ruby","code":"def test_flattened_constructor\n hash = Sinatra::IndifferentHash[:a, 1, ?b, 2]\n assert_equal 1, hash[?a]\n assert_equal 2, hash[?b]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":16,"symbol":"test_pairs_constructor","kind":"method","lang":"ruby","code":"def test_pairs_constructor\n hash = Sinatra::IndifferentHash[[[:a, 1], [?b, 2]]]\n assert_equal 1, hash[?a]\n assert_equal 2, hash[?b]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":22,"symbol":"test_default_block","kind":"method","lang":"ruby","code":"def test_default_block\n hash = Sinatra::IndifferentHash.new { |h, k| h[k] = k.upcase }\n assert_nil hash.default\n assert_equal ?A, hash.default(:a)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":28,"symbol":"test_default_object","kind":"method","lang":"ruby","code":"def test_default_object\n hash = Sinatra::IndifferentHash.new({:a=>1, ?b=>2})\n assert_equal({ :a=>1, ?b=>2 }, hash.default)\n assert_equal({ :a=>1, ?b=>2 }, hash[:a])\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":34,"symbol":"test_default_assignment","kind":"method","lang":"ruby","code":"def test_default_assignment\n hash = Sinatra::IndifferentHash.new\n hash.default = { :a=>1, ?b=>2 }\n assert_equal({ ?a=>1, ?b=>2 }, hash.default)\n assert_equal({ ?a=>1, ?b=>2 }, hash[:a])\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":41,"symbol":"test_assignment","kind":"method","lang":"ruby","code":"def test_assignment\n hash = Sinatra::IndifferentHash.new\n hash[:a] = :a\n hash[?b] = :b\n hash[3] = 3\n hash[:simple_nested] = { :a=>:a, ?b=>:b }\n\n assert_equal :a, hash[?a]\n assert_equal :b, hash[?b]\n assert_equal 3, hash[3]\n assert_equal({ ?a=>:a, ?b=>:b }, hash['simple_nested'])\n assert_nil hash[?d]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":55,"symbol":"test_merge!","kind":"method","lang":"ruby","code":"def test_merge!\n # merge! is already mostly tested by the different constructors, so we\n # really just need to test the block form here\n hash = Sinatra::IndifferentHash[:a=>'a', ?b=>'b', 3=>3]\n hash.merge!(?a=>'A', :b=>'B', :d=>'D') do |key, oldval, newval|\n \"#{oldval}*#{key}*#{newval}\"\n end\n\n assert_equal({ ?a=>'a*a*A', ?b=>'b*b*B', 3=>3, ?d=>'D' }, hash)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":67,"symbol":"TestIndifferentHash","kind":"class","lang":"ruby","code":"class TestIndifferentHash < Minitest::Test\n def setup\n @hash = Sinatra::IndifferentHash[:a=>:a, ?b=>:b, 3=>3,\n :simple_nested=>{ :a=>:a, ?b=>:b },\n :nested=>{ :a=>[{ :a=>:a, ?b=>:b }, :c, 4], ?f=>:f, 7=>7 }\n ]\n end\n\n def test_hash_constructor\n assert_equal :a, @hash[?a]\n assert_equal :b, @hash[?b]\n assert_equal 3, @hash[3]\n assert_equal({ ?a=>:a, ?b=>:b }, @hash['nested'][?a][0])\n assert_equal :c, @hash['nested'][?a][1]\n assert_equal 4, @hash['nested'][?a][2]\n assert_equal :f, @hash['nested'][?f]\n assert_equal 7, @hash['nested'][7]\n assert_equal :a, @hash['simple_nested'][?a]\n assert_equal :b, @hash['simple_nested'][?b]\n assert_nil @hash[?d]\n end\n\n def test_assoc\n assert_nil @hash.assoc(:d)\n assert_equal [?a, :a], @hash.assoc(:a)\n assert_equal [?b, :b], @hash.assoc(:b)\n end\n\n def test_rassoc\n assert_nil @hash.rassoc(:d)\n assert_equal [?a, :a], @hash.rassoc(:a)\n assert_equal [?b, :b], @hash.rassoc(:b)\n assert_equal ['simple_nested', { ?a=>:a, ?b=>:b }], @hash.rassoc(:a=>:a, ?b=>:b)\n end\n\n def test_fetch\n assert_raises(KeyError) { @hash.fetch(:d) }\n assert_equal 1, @hash.fetch(:d, 1)\n assert_equal"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":68,"symbol":"setup","kind":"method","lang":"ruby","code":"def setup\n @hash = Sinatra::IndifferentHash[:a=>:a, ?b=>:b, 3=>3,\n :simple_nested=>{ :a=>:a, ?b=>:b },\n :nested=>{ :a=>[{ :a=>:a, ?b=>:b }, :c, 4], ?f=>:f, 7=>7 }\n ]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":75,"symbol":"test_hash_constructor","kind":"method","lang":"ruby","code":"def test_hash_constructor\n assert_equal :a, @hash[?a]\n assert_equal :b, @hash[?b]\n assert_equal 3, @hash[3]\n assert_equal({ ?a=>:a, ?b=>:b }, @hash['nested'][?a][0])\n assert_equal :c, @hash['nested'][?a][1]\n assert_equal 4, @hash['nested'][?a][2]\n assert_equal :f, @hash['nested'][?f]\n assert_equal 7, @hash['nested'][7]\n assert_equal :a, @hash['simple_nested'][?a]\n assert_equal :b, @hash['simple_nested'][?b]\n assert_nil @hash[?d]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":89,"symbol":"test_assoc","kind":"method","lang":"ruby","code":"def test_assoc\n assert_nil @hash.assoc(:d)\n assert_equal [?a, :a], @hash.assoc(:a)\n assert_equal [?b, :b], @hash.assoc(:b)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":95,"symbol":"test_rassoc","kind":"method","lang":"ruby","code":"def test_rassoc\n assert_nil @hash.rassoc(:d)\n assert_equal [?a, :a], @hash.rassoc(:a)\n assert_equal [?b, :b], @hash.rassoc(:b)\n assert_equal ['simple_nested', { ?a=>:a, ?b=>:b }], @hash.rassoc(:a=>:a, ?b=>:b)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":102,"symbol":"test_fetch","kind":"method","lang":"ruby","code":"def test_fetch\n assert_raises(KeyError) { @hash.fetch(:d) }\n assert_equal 1, @hash.fetch(:d, 1)\n assert_equal 2, @hash.fetch(:d) { 2 }\n assert_equal ?d, @hash.fetch(:d) { |k| k }\n assert_equal :a, @hash.fetch(:a, 1)\n assert_equal :a, @hash.fetch(:a) { 2 }\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":111,"symbol":"test_symbolic_retrieval","kind":"method","lang":"ruby","code":"def test_symbolic_retrieval\n assert_equal :a, @hash[:a]\n assert_equal :b, @hash[:b]\n assert_equal({ ?a=>:a, ?b=>:b }, @hash[:nested][:a][0])\n assert_equal :c, @hash[:nested][:a][1]\n assert_equal 4, @hash[:nested][:a][2]\n assert_equal :f, @hash[:nested][:f]\n assert_equal 7, @hash[:nested][7]\n assert_equal :a, @hash[:simple_nested][:a]\n assert_equal :b, @hash[:simple_nested][:b]\n assert_nil @hash[:d]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":124,"symbol":"test_key","kind":"method","lang":"ruby","code":"def test_key\n assert_nil @hash.key(:d)\n assert_equal ?a, @hash.key(:a)\n assert_equal 'simple_nested', @hash.key(:a=>:a, ?b=>:b)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":130,"symbol":"test_key?","kind":"method","lang":"ruby","code":"def test_key?\n assert_operator @hash, :key?, :a\n assert_operator @hash, :key?, ?b\n assert_operator @hash, :key?, 3\n refute_operator @hash, :key?, :d\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":137,"symbol":"test_value?","kind":"method","lang":"ruby","code":"def test_value?\n assert_operator @hash, :value?, :a\n assert_operator @hash, :value?, :b\n assert_operator @hash, :value?, 3\n assert_operator @hash, :value?, { :a=>:a, ?b=>:b }\n refute_operator @hash, :value?, :d\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":145,"symbol":"test_delete","kind":"method","lang":"ruby","code":"def test_delete\n @hash.delete(:a)\n @hash.delete(?b)\n assert_nil @hash[:a]\n assert_nil @hash[?b]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":152,"symbol":"test_dig","kind":"method","lang":"ruby","code":"def test_dig\n assert_equal :a, @hash.dig(:a)\n assert_equal :b, @hash.dig(?b)\n assert_nil @hash.dig(:d)\n\n assert_equal :a, @hash.dig(:simple_nested, :a)\n assert_equal :b, @hash.dig('simple_nested', ?b)\n assert_nil @hash.dig('simple_nested', :d)\n\n assert_equal :a, @hash.dig(:nested, :a, 0, :a)\n assert_equal :b, @hash.dig('nested', ?a, 0, ?b)\n assert_nil @hash.dig('nested', ?a, 0, :d)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":166,"symbol":"test_slice","kind":"method","lang":"ruby","code":"def test_slice\n assert_equal Sinatra::IndifferentHash[a: :a], @hash.slice(:a)\n assert_equal Sinatra::IndifferentHash[b: :b], @hash.slice(?b)\n assert_equal Sinatra::IndifferentHash[3 => 3], @hash.slice(3)\n assert_equal Sinatra::IndifferentHash.new, @hash.slice(:d)\n assert_equal Sinatra::IndifferentHash[a: :a, b: :b, 3 => 3], @hash.slice(:a, :b, 3)\n assert_equal Sinatra::IndifferentHash[simple_nested: { a: :a, ?b => :b }], @hash.slice(:simple_nested)\n assert_equal Sinatra::IndifferentHash[nested: { a: [{ a: :a, ?b => :b }, :c, 4], ?f => :f, 7 => 7 }], @hash.slice(:nested)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":176,"symbol":"test_fetch_values","kind":"method","lang":"ruby","code":"def test_fetch_values\n assert_raises(KeyError) { @hash.fetch_values(3, :d) }\n assert_equal [:a, :b, 3, ?D], @hash.fetch_values(:a, ?b, 3, :d) { |k| k.upcase }\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":181,"symbol":"test_values_at","kind":"method","lang":"ruby","code":"def test_values_at\n assert_equal [:a, :b, 3, nil], @hash.values_at(:a, ?b, 3, :d)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":185,"symbol":"test_merge","kind":"method","lang":"ruby","code":"def test_merge\n # merge just calls merge!, which is already thoroughly tested\n hash2 = @hash.merge(?a=>1, :q=>2) { |key, oldval, newval| \"#{oldval}*#{key}*#{newval}\" }\n\n refute_equal @hash, hash2\n assert_equal 'a*a*1', hash2[:a]\n assert_equal 2, hash2[?q]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":194,"symbol":"test_merge_with_multiple_argument","kind":"method","lang":"ruby","code":"def test_merge_with_multiple_argument\n hash = Sinatra::IndifferentHash.new.merge({a: 1}, {b: 2}, {c: 3})\n assert_equal 1, hash[?a]\n assert_equal 2, hash[?b]\n assert_equal 3, hash[?c]\n\n hash2 = Sinatra::IndifferentHash[d: 4]\n hash3 = {e: 5}\n hash.merge!(hash2, hash3)\n\n assert_equal 4, hash[?d]\n assert_equal 5, hash[?e]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":208,"symbol":"test_replace","kind":"method","lang":"ruby","code":"def test_replace\n @hash.replace(?a=>1, :q=>2)\n assert_equal({ ?a=>1, ?q=>2 }, @hash)\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":213,"symbol":"test_transform_values!","kind":"method","lang":"ruby","code":"def test_transform_values!\n @hash.transform_values! { |v| v.is_a?(Hash) ? Hash[v.to_a] : v }\n\n assert_instance_of Sinatra::IndifferentHash, @hash[:simple_nested]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":219,"symbol":"test_transform_values","kind":"method","lang":"ruby","code":"def test_transform_values\n hash2 = @hash.transform_values { |v| v.respond_to?(:upcase) ? v.upcase : v }\n\n refute_equal @hash, hash2\n assert_equal :A, hash2[:a]\n assert_equal :A, hash2[?a]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":227,"symbol":"test_transform_keys!","kind":"method","lang":"ruby","code":"def test_transform_keys!\n @hash.transform_keys! { |k| k.respond_to?(:to_sym) ? k.to_sym : k }\n\n assert_equal :a, @hash[:a]\n assert_equal :a, @hash[?a]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":234,"symbol":"test_transform_keys","kind":"method","lang":"ruby","code":"def test_transform_keys\n hash2 = @hash.transform_keys { |k| k.respond_to?(:upcase) ? k.upcase : k }\n\n refute_equal @hash, hash2\n refute_operator hash2, :key?, :a\n refute_operator hash2, :key?, ?a\n assert_equal :a, hash2[:A]\n assert_equal :a, hash2[?A]\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":244,"symbol":"test_select","kind":"method","lang":"ruby","code":"def test_select\n hash = @hash.select { |k, v| v == :a }\n assert_equal Sinatra::IndifferentHash[a: :a], hash\n assert_instance_of Sinatra::IndifferentHash, hash\n\n hash2 = @hash.select { |k, v| true }\n assert_equal @hash, hash2\n assert_instance_of Sinatra::IndifferentHash, hash2\n\n enum = @hash.select\n assert_instance_of Enumerator, enum\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":257,"symbol":"test_select!","kind":"method","lang":"ruby","code":"def test_select!\n @hash.select! { |k, v| v == :a }\n assert_equal Sinatra::IndifferentHash[a: :a], @hash\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":262,"symbol":"test_reject","kind":"method","lang":"ruby","code":"def test_reject\n hash = @hash.reject { |k, v| v != :a }\n assert_equal Sinatra::IndifferentHash[a: :a], hash\n assert_instance_of Sinatra::IndifferentHash, hash\n\n hash2 = @hash.reject { |k, v| false }\n assert_equal @hash, hash2\n assert_instance_of Sinatra::IndifferentHash, hash2\n\n enum = @hash.reject\n assert_instance_of Enumerator, enum\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":275,"symbol":"test_reject!","kind":"method","lang":"ruby","code":"def test_reject!\n @hash.reject! { |k, v| v != :a }\n assert_equal Sinatra::IndifferentHash[a: :a], @hash\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":280,"symbol":"test_compact","kind":"method","lang":"ruby","code":"def test_compact\n hash_with_nil_values = @hash.merge({?z => nil})\n compacted_hash = hash_with_nil_values.compact\n assert_equal @hash, compacted_hash\n assert_instance_of Sinatra::IndifferentHash, compacted_hash\n\n empty_hash = Sinatra::IndifferentHash.new\n compacted_hash = empty_hash.compact\n assert_equal empty_hash, compacted_hash\n\n non_empty_hash = Sinatra::IndifferentHash[a: :a]\n compacted_hash = non_empty_hash.compact\n assert_equal non_empty_hash, compacted_hash\n end"}
{"repo":"sinatra","file":"test/indifferent_hash_test.rb","line":295,"symbol":"test_except","kind":"method","lang":"ruby","code":"def test_except\n hash = @hash.except(?b, 3, :simple_nested, 'nested')\n assert_equal Sinatra::IndifferentHash[a: :a], hash\n assert_instance_of Sinatra::IndifferentHash, hash\n end"}
{"repo":"sinatra","file":"test/integration/app.rb","line":64,"symbol":"Subclass","kind":"class","lang":"ruby","code":"class Subclass < Sinatra::Base\n set :out, nil\n get '/subclass/async' do\n stream(:keep_open) { |o| (settings.out = o) << \"hi!\"; sleep 1 }\n end\n\n get '/subclass/send' do\n settings.out << params[:msg] if params[:msg]\n settings.out.close if params[:close]\n \"ok\"\n end\nend"}
{"repo":"sinatra","file":"test/integration_async_helper.rb","line":3,"symbol":"IntegrationAsyncHelper","kind":"module","lang":"ruby","code":"module IntegrationAsyncHelper\n Server = IntegrationHelper::BaseServer\n\n def it(message, &block)\n Server.all_async.each do |server|\n next unless server.installed?\n super(\"with #{server.name}: #{message}\") { server.run_test(self, &block) }\n end\n end\n\n def self.extend_object(obj)\n super\n\n base_port = 5100 + Process.pid % 100\n servers = %w(puma)\n\n servers.each_with_index do |server, index|\n Server.run(server, base_port+index, async: true)\n end\n end\nend"}
{"repo":"sinatra","file":"test/integration_async_helper.rb","line":6,"symbol":"it","kind":"method","lang":"ruby","code":"def it(message, &block)\n Server.all_async.each do |server|\n next unless server.installed?\n super(\"with #{server.name}: #{message}\") { server.run_test(self, &block) }\n end\n end"}
{"repo":"sinatra","file":"test/integration_async_helper.rb","line":13,"symbol":"extend_object","kind":"method","lang":"ruby","code":"def self.extend_object(obj)\n super\n\n base_port = 5100 + Process.pid % 100\n servers = %w(puma)\n\n servers.each_with_index do |server, index|\n Server.run(server, base_port+index, async: true)\n end\n end"}
{"repo":"sinatra","file":"test/integration_async_test.rb","line":5,"symbol":"IntegrationAsyncTest","kind":"class","lang":"ruby","doc":"These tests are like integration_test, but they test asynchronous streaming.","code":"class IntegrationAsyncTest < Minitest::Test\n extend IntegrationAsyncHelper\n attr_accessor :server\n\n it 'streams async' do\n Timeout.timeout(3) do\n chunks = []\n server.get_stream '/async' do |chunk|\n next if chunk.empty?\n chunks << chunk\n case chunk\n when \"hi!\" then server.get \"/send?msg=hello\"\n when \"hello\" then server.get \"/send?close=1\"\n end\n end\n\n assert_equal ['hi!', 'hello'], chunks\n end\n end\n\n it 'streams async from subclass' do\n Timeout.timeout(3) do\n chunks = []\n server.get_stream '/subclass/async' do |chunk|\n next if chunk.empty?\n chunks << chunk\n case chunk\n when \"hi!\" then server.get \"/subclass/send?msg=hello\"\n when \"hello\" then server.get \"/subclass/send?close=1\"\n end\n end\n\n assert_equal ['hi!', 'hello'], chunks\n end\n end\nend"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":6,"symbol":"IntegrationHelper","kind":"module","lang":"ruby","code":"module IntegrationHelper\n class BaseServer < Sinatra::Runner\n extend Enumerable\n attr_accessor :server, :port\n alias name server\n\n def self.all\n @all ||= []\n end\n\n def self.all_async\n @all_async ||= []\n end\n\n def self.each(&block)\n all.each(&block)\n end\n\n def self.run(server, port, async: false)\n new(server, port, async).run\n end\n\n def app_file\n File.expand_path('integration/app.rb', __dir__)\n end\n\n def environment\n \"development\"\n end\n\n def initialize(server, port, async)\n @installed, @pipe, @server, @port = nil, nil, server, port\n ENV['PUMA_MIN_THREADS'] = '1' if server == 'puma'\n if async\n Server.all_async << self\n else\n Server.all << self\n end\n end\n\n def run\n return unless installed?\n kill\n @log = +\"\"\n super\n at_exit { kill }\n end\n\n def installed?\n return @installed unless @installed.nil?\n s = server == 'HTTP' ? 'net/http/server' : server\n require s\n @installed = true\n rescue LoadError\n warn \"#{server} is not installed, skipping integration tests\"\n @installed = false\n end\n\n def comman"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":7,"symbol":"BaseServer","kind":"class","lang":"ruby","code":"class BaseServer < Sinatra::Runner\n extend Enumerable\n attr_accessor :server, :port\n alias name server\n\n def self.all\n @all ||= []\n end\n\n def self.all_async\n @all_async ||= []\n end\n\n def self.each(&block)\n all.each(&block)\n end\n\n def self.run(server, port, async: false)\n new(server, port, async).run\n end\n\n def app_file\n File.expand_path('integration/app.rb', __dir__)\n end\n\n def environment\n \"development\"\n end\n\n def initialize(server, port, async)\n @installed, @pipe, @server, @port = nil, nil, server, port\n ENV['PUMA_MIN_THREADS'] = '1' if server == 'puma'\n if async\n Server.all_async << self\n else\n Server.all << self\n end\n end\n\n def run\n return unless installed?\n kill\n @log = +\"\"\n super\n at_exit { kill }\n end\n\n def installed?\n return @installed unless @installed.nil?\n s = server == 'HTTP' ? 'net/http/server' : server\n require s\n @installed = true\n rescue LoadError\n warn \"#{server} is not installed, skipping integration tests\"\n @installed = false\n end\n\n def command\n @command ||= begin\n"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":12,"symbol":"all","kind":"method","lang":"ruby","code":"def self.all\n @all ||= []\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":16,"symbol":"all_async","kind":"method","lang":"ruby","code":"def self.all_async\n @all_async ||= []\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":20,"symbol":"each","kind":"method","lang":"ruby","code":"def self.each(&block)\n all.each(&block)\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":24,"symbol":"run","kind":"method","lang":"ruby","code":"def self.run(server, port, async: false)\n new(server, port, async).run\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":28,"symbol":"app_file","kind":"method","lang":"ruby","code":"def app_file\n File.expand_path('integration/app.rb', __dir__)\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":32,"symbol":"environment","kind":"method","lang":"ruby","code":"def environment\n \"development\"\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":36,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(server, port, async)\n @installed, @pipe, @server, @port = nil, nil, server, port\n ENV['PUMA_MIN_THREADS'] = '1' if server == 'puma'\n if async\n Server.all_async << self\n else\n Server.all << self\n end\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":46,"symbol":"run","kind":"method","lang":"ruby","code":"def run\n return unless installed?\n kill\n @log = +\"\"\n super\n at_exit { kill }\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":54,"symbol":"installed?","kind":"method","lang":"ruby","code":"def installed?\n return @installed unless @installed.nil?\n s = server == 'HTTP' ? 'net/http/server' : server\n require s\n @installed = true\n rescue LoadError\n warn \"#{server} is not installed, skipping integration tests\"\n @installed = false\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":64,"symbol":"command","kind":"method","lang":"ruby","code":"def command\n @command ||= begin\n cmd = [\"APP_ENV=#{environment}\", \"exec\"]\n if RbConfig.respond_to? :ruby\n cmd << RbConfig.ruby.inspect\n else\n file, dir = RbConfig::CONFIG.values_at('ruby_install_name', 'bindir')\n cmd << File.expand_path(file, dir).inspect\n end\n cmd << \"-w\" unless net_http_server?\n cmd << \"-I\" << File.expand_path('../lib', __dir__).inspect\n cmd << app_file.inspect << '-s' << server << '-o' << '127.0.0.1' << '-p' << port\n cmd << \"-e\" << environment.to_s << '2>&1'\n cmd.join \" \"\n end\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":81,"symbol":"webrick?","kind":"method","lang":"ruby","code":"def webrick?\n name.to_s == \"webrick\"\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":85,"symbol":"puma?","kind":"method","lang":"ruby","code":"def puma?\n name.to_s == \"puma\"\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":89,"symbol":"falcon?","kind":"method","lang":"ruby","code":"def falcon?\n name.to_s == \"falcon\"\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":93,"symbol":"trinidad?","kind":"method","lang":"ruby","code":"def trinidad?\n name.to_s == \"trinidad\"\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":97,"symbol":"net_http_server?","kind":"method","lang":"ruby","code":"def net_http_server?\n name.to_s == 'HTTP'\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":101,"symbol":"warnings","kind":"method","lang":"ruby","code":"def warnings\n log.scan(%r[(?:\\(eval|lib/sinatra).*warning:.*$])\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":105,"symbol":"run_test","kind":"method","lang":"ruby","code":"def run_test(target, &block)\n retries ||= 3\n target.server = self\n run unless alive?\n target.instance_eval(&block)\n rescue Exception => error\n retries -= 1\n kill\n retries < 0 ? retry : raise(error)\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":119,"symbol":"it","kind":"method","lang":"ruby","code":"def it(message, &block)\n Server.each do |server|\n next unless server.installed?\n super(\"with #{server.name}: #{message}\") { server.run_test(self, &block) }\n end\n end"}
{"repo":"sinatra","file":"test/integration_helper.rb","line":126,"symbol":"extend_object","kind":"method","lang":"ruby","code":"def self.extend_object(obj)\n super\n\n base_port = 5000 + Process.pid % 100\n servers = Sinatra::Base.server.dup\n\n # TruffleRuby doesn't support `Fiber.set_scheduler` yet\n unsupported_truffleruby = RUBY_ENGINE == \"truffleruby\" && !Fiber.respond_to?(:set_scheduler)\n # Ruby 2.7 uses falcon 0.42.3 which isn't working with rackup 2.2.0+\n too_old_ruby = RUBY_VERSION <= \"3.0.0\"\n\n if unsupported_truffleruby || too_old_ruby\n warn \"skip falcon server\"\n servers.delete('falcon')\n end\n\n servers.each_with_index do |server, index|\n Server.run(server, base_port+index)\n end\n end"}
{"repo":"sinatra","file":"test/integration_start_helper.rb","line":5,"symbol":"IntegrationStartHelper","kind":"module","lang":"ruby","code":"module IntegrationStartHelper\n def command_for(app_file)\n [\n \"ruby\",\n app_file,\n \"-p\",\n \"0\", # any free port\n \"-s\",\n \"puma\",\n ]\n end\n\n def with_process(command:, env: {}, debug: false)\n process = ChildProcess.build(*command)\n process.leader = true # ensure entire process tree dies\n process.environment.merge!(env)\n read_io, write_io = IO.pipe\n process.io.stdout = write_io\n process.io.stderr = write_io\n process.start\n # Close parent's copy of the write end of the pipe so when the (forked) child\n # process closes its write end of the pipe the parent receives EOF when\n # attempting to read from it. If the parent leaves its write end open, it\n # will not detect EOF.\n write_io.close\n\n echo_output(read_io) if debug || debug_all?\n\n yield process, read_io\n ensure\n read_io.close\n process.stop\n end\n\n def echo_output(read_io)\n Thread.new do\n begin\n loop { print read_io.readpartial(8192) }\n rescue EOFError\n end\n end\n end\n\n def debug_all?\n ENV.key?(\"DEBUG_START_PROCESS\")\n end\n\n def wait_timeout\n case RUBY_ENGINE\n when \"jruby\", \"truffleruby\"\n # takes some time to"}
{"repo":"sinatra","file":"test/integration_start_helper.rb","line":6,"symbol":"command_for","kind":"method","lang":"ruby","code":"def command_for(app_file)\n [\n \"ruby\",\n app_file,\n \"-p\",\n \"0\", # any free port\n \"-s\",\n \"puma\",\n ]\n end"}
{"repo":"sinatra","file":"test/integration_start_helper.rb","line":17,"symbol":"with_process","kind":"method","lang":"ruby","code":"def with_process(command:, env: {}, debug: false)\n process = ChildProcess.build(*command)\n process.leader = true # ensure entire process tree dies\n process.environment.merge!(env)\n read_io, write_io = IO.pipe\n process.io.stdout = write_io\n process.io.stderr = write_io\n process.start\n # Close parent's copy of the write end of the pipe so when the (forked) child\n # process closes its write end of the pipe the parent receives EOF when\n # attempting to read from it. If the parent leaves its write end open, it\n # will not detect EOF.\n write_io.close\n\n echo_output(read_io) if debug || debug_all?\n\n yield process, read_io\n ensure\n read_io.close\n process.stop\n end"}
{"repo":"sinatra","file":"test/integration_start_helper.rb","line":39,"symbol":"echo_output","kind":"method","lang":"ruby","code":"def echo_output(read_io)\n Thread.new do\n begin\n loop { print read_io.readpartial(8192) }\n rescue EOFError\n end\n end\n end"}
{"repo":"sinatra","file":"test/integration_start_helper.rb","line":48,"symbol":"debug_all?","kind":"method","lang":"ruby","code":"def debug_all?\n ENV.key?(\"DEBUG_START_PROCESS\")\n end"}
{"repo":"sinatra","file":"test/integration_start_helper.rb","line":52,"symbol":"wait_timeout","kind":"method","lang":"ruby","code":"def wait_timeout\n case RUBY_ENGINE\n when \"jruby\", \"truffleruby\"\n # takes some time to start the JVM\n 10.0\n else\n 3.0\n end\n end"}
{"repo":"sinatra","file":"test/integration_start_helper.rb","line":62,"symbol":"wait_for_output","kind":"method","lang":"ruby","code":"def wait_for_output(read_io, matcher, timeout = wait_timeout)\n return true if read_io.expect(matcher, timeout).to_a.any?\n\n raise \"Waited for #{timeout} seconds, but received no output matching: \" \\\n \"#{matcher.source}\"\n end"}
{"repo":"sinatra","file":"test/integration_start_test.rb","line":3,"symbol":"IntegrationStartTest","kind":"class","lang":"ruby","code":"class IntegrationStartTest < Minitest::Test\n include IntegrationStartHelper\n\n # what we test here: that the correct help text is printed when the required gems aren't installed\n def test_app_start_without_rackup\n # Why we skip head versions: The Gemfile used here would have to support\n # the ENVs and we would need to bundle before starting the app\n #\n # Example from locally playing with this:\n #\n # root@df8b1e7cb106:/app# rack_session=head BUNDLE_GEMFILE=./test/integration/gemfile_without_rackup.rb ruby ./test/integration/simple_app.rb -p 0 -s puma\n # The git source https://github.com/rack/rack-session.git is not yet checked out. Please run `bundle install` before trying to start your application\n #\n # Using bundler/inline is an idea, but it would add to the startup time\n skip \"So much work to run with rack head branch\" if ENV['rack'] == 'head'\n skip \"So much work to run with rack-session head branch\" if ENV['rack_session'] == 'head'\n\n app_file = File.join(__dir__, \"integration\", \"simple_app.rb\")\n gem_file = File.join(__dir__, \"integration\", \"gemfile_without_rackup.rb\")\n lock_file = File.join(__dir__, \"integration\", \"gemfile_without_"}
{"repo":"sinatra","file":"test/integration_start_test.rb","line":7,"symbol":"test_app_start_without_rackup","kind":"method","lang":"ruby","doc":"what we test here: that the correct help text is printed when the required gems aren't installed","code":"def test_app_start_without_rackup\n # Why we skip head versions: The Gemfile used here would have to support\n # the ENVs and we would need to bundle before starting the app\n #\n # Example from locally playing with this:\n #\n # root@df8b1e7cb106:/app# rack_session=head BUNDLE_GEMFILE=./test/integration/gemfile_without_rackup.rb ruby ./test/integration/simple_app.rb -p 0 -s puma\n # The git source https://github.com/rack/rack-session.git is not yet checked out. Please run `bundle install` before trying to start your application\n #\n # Using bundler/inline is an idea, but it would add to the startup time\n skip \"So much work to run with rack head branch\" if ENV['rack'] == 'head'\n skip \"So much work to run with rack-session head branch\" if ENV['rack_session'] == 'head'\n\n app_file = File.join(__dir__, \"integration\", \"simple_app.rb\")\n gem_file = File.join(__dir__, \"integration\", \"gemfile_without_rackup.rb\")\n lock_file = File.join(__dir__, \"integration\", \"gemfile_without_rackup.rb.lock\")\n command = command_for(app_file)\n # BUNDLE_LOCKFILE is exported by Bundler 4; without clearing it the child would\n # write the alternate gemfile's lock to "}
{"repo":"sinatra","file":"test/integration_start_test.rb","line":38,"symbol":"test_classic_app_start","kind":"method","lang":"ruby","code":"def test_classic_app_start\n app_file = File.join(__dir__, \"integration\", \"simple_app.rb\")\n command = command_for(app_file)\n with_process(command: command) do |process, read_io|\n assert wait_for_output(read_io, /Sinatra \\(v.+\\) has taken the stage/)\n end\n end"}
{"repo":"sinatra","file":"test/integration_start_test.rb","line":46,"symbol":"test_classic_app_with_zeitwerk","kind":"method","lang":"ruby","code":"def test_classic_app_with_zeitwerk\n app_file = File.join(__dir__, \"integration\", \"zeitwerk_app.rb\")\n command = command_for(app_file)\n with_process(command: command) do |process, read_io|\n assert wait_for_output(read_io, /Sinatra \\(v.+\\) has taken the stage/)\n end\n end"}
{"repo":"sinatra","file":"test/integration_test.rb","line":8,"symbol":"IntegrationTest","kind":"class","lang":"ruby","doc":"These tests start a real server and talk to it over TCP. Every test runs with every detected server. See test/integration/app.rb for the code of the app we test against.","code":"class IntegrationTest < Minitest::Test\n extend IntegrationHelper\n attr_accessor :server\n\n it('sets the app_file') { assert_equal server.app_file, server.get(\"/app_file\") }\n it('only extends main') { assert_equal \"true\", server.get(\"/mainonly\") }\n\n it 'logs once in development mode' do\n next if server.puma? or server.falcon? or RUBY_ENGINE == 'jruby'\n random = \"%064x\" % Kernel.rand(2**256-1)\n server.get \"/ping?x=#{random}\"\n count = server.log.scan(\"GET /ping?x=#{random}\").count\n if server.net_http_server?\n assert_equal 0, count\n elsif server.webrick?\n assert(count > 0)\n else\n assert_equal(1, count)\n end\n end\n\n it 'streams' do\n next if server.webrick? or server.trinidad?\n times, chunks = [Process.clock_gettime(Process::CLOCK_MONOTONIC)], []\n server.get_stream do |chunk|\n next if chunk.empty?\n chunks << chunk\n times << Process.clock_gettime(Process::CLOCK_MONOTONIC)\n end\n assert_equal [\"a\", \"b\"], chunks\n int1 = (times[1] - times[0]).round 2\n int2 = (times[2] - times[1]).round 2\n assert_operator 1, :>, int1\n assert_operator 1, :<, int2\n end\n\n it 'starts the correct server' do\n exp = %r{\n ="}
{"repo":"sinatra","file":"test/liquid_test.rb","line":6,"symbol":"LiquidTest","kind":"class","lang":"ruby","code":"class LiquidTest < Minitest::Test\n def liquid_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline liquid strings' do\n liquid_app { liquid '<h1>Hiya</h1>' }\n assert ok?\n assert_equal \"<h1>Hiya</h1>\", body\n end\n\n it 'renders .liquid files in views path' do\n liquid_app { liquid :hello }\n assert ok?\n assert_equal \"<h1>Hello From Liquid</h1>\\n\", body\n end\n\n it \"renders with inline layouts\" do\n mock_app do\n layout { \"<h1>THIS. IS. {{ yield }}</h1>\" }\n get('/') { liquid '<EM>SPARTA</EM>' }\n end\n get '/'\n assert ok?\n assert_equal \"<h1>THIS. IS. <EM>SPARTA</EM></h1>\", body\n end\n\n it \"renders with file layouts\" do\n liquid_app { liquid 'Hello World', :layout => :layout2 }\n assert ok?\n assert_equal \"<h1>Liquid Layout!</h1>\\n<p>Hello World</p>\\n\", body\n end\n\n it \"raises error if template not found\" do\n mock_app { get('/') { liquid :no_such_template } }\n assert_raises(Errno::ENOENT) { get('/') }\n end\n\n it \"allows passing locals\" do\n liquid_app {\n liquid '{{ value }}', :locals => { :value => 'foo' }\n }\n assert ok?\n assert_equal '"}
{"repo":"sinatra","file":"test/liquid_test.rb","line":7,"symbol":"liquid_app","kind":"method","lang":"ruby","code":"def liquid_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":3,"symbol":"FooError","kind":"class","lang":"ruby","code":"class FooError < RuntimeError\nend"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":6,"symbol":"FooNotFound","kind":"class","lang":"ruby","code":"class FooNotFound < Sinatra::NotFound\nend"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":9,"symbol":"FooSpecialError","kind":"class","lang":"ruby","code":"class FooSpecialError < Sinatra::Error\n def http_status; 501 end\nend"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":10,"symbol":"http_status","kind":"method","lang":"ruby","code":"def http_status; 501 end"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":13,"symbol":"FooStatusOutOfRangeError","kind":"class","lang":"ruby","code":"class FooStatusOutOfRangeError < Sinatra::Error\n def code; 4000 end\nend"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":14,"symbol":"code","kind":"method","lang":"ruby","code":"def code; 4000 end"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":17,"symbol":"FooWithCode","kind":"class","lang":"ruby","code":"class FooWithCode < Sinatra::Error\n def code; 419 end\nend"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":18,"symbol":"code","kind":"method","lang":"ruby","code":"def code; 419 end"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":21,"symbol":"FirstError","kind":"class","lang":"ruby","code":"class FirstError < RuntimeError; end"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":22,"symbol":"SecondError","kind":"class","lang":"ruby","code":"class SecondError < RuntimeError; end"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":24,"symbol":"MappedErrorTest","kind":"class","lang":"ruby","code":"class MappedErrorTest < Minitest::Test\n def test_default\n assert true\n end\n\n describe 'Exception Mappings' do\n it 'invokes handlers registered with ::error when raised' do\n mock_app do\n set :raise_errors, false\n error(FooError) { 'Foo!' }\n get('/') { raise FooError }\n end\n get '/'\n assert_equal 500, status\n assert_equal 'Foo!', body\n end\n\n it 'passes the exception object to the error handler' do\n mock_app do\n set :raise_errors, false\n error(FooError) { |e| assert_equal(FooError, e.class) }\n get('/') { raise FooError }\n end\n get('/')\n end\n\n it 'uses the Exception handler if no matching handler found' do\n mock_app do\n set :raise_errors, false\n error(Exception) { 'Exception!' }\n get('/') { raise FooError }\n end\n\n get '/'\n assert_equal 500, status\n assert_equal 'Exception!', body\n end\n\n it 'walks down inheritance chain for errors' do\n mock_app do\n set :raise_errors, false\n error(RuntimeError) { 'Exception!' }\n get('/') { raise FooError }\n end\n\n get '/'\n assert_equal 500, status\n assert_eq"}
{"repo":"sinatra","file":"test/mapped_error_test.rb","line":25,"symbol":"test_default","kind":"method","lang":"ruby","code":"def test_default\n assert true\n end"}
{"repo":"sinatra","file":"test/markaby_test.rb","line":6,"symbol":"MarkabyTest","kind":"class","lang":"ruby","code":"class MarkabyTest < Minitest::Test\n def markaby_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline markaby strings' do\n markaby_app { markaby 'h1 \"Hiya\"' }\n assert ok?\n assert_equal \"<h1>Hiya</h1>\", body\n end\n\n it 'renders .markaby files in views path' do\n markaby_app { markaby :hello }\n assert ok?\n assert_equal \"<h1>Hello From Markaby</h1>\", body\n end\n\n it \"renders with inline layouts\" do\n mock_app do\n layout { 'h1 { text \"THIS. IS. \"; yield }' }\n get('/') { markaby 'em \"SPARTA\"' }\n end\n get '/'\n assert ok?\n assert_equal \"<h1>THIS. IS. <em>SPARTA</em></h1>\", body\n end\n\n it \"renders with file layouts\" do\n markaby_app { markaby 'text \"Hello World\"', :layout => :layout2 }\n assert ok?\n assert_equal \"<h1>Markaby Layout!</h1><p>Hello World</p>\", body\n end\n\n it 'renders inline markaby blocks' do\n markaby_app { markaby { h1 'Hiya' } }\n assert ok?\n assert_equal \"<h1>Hiya</h1>\", body\n end\n\n it 'renders inline markaby blocks with inline layouts' do\n markaby_app do\n settings.layout { 'h1 { text \"THIS. IS. \"; yield }' }\n marka"}
{"repo":"sinatra","file":"test/markaby_test.rb","line":7,"symbol":"markaby_app","kind":"method","lang":"ruby","code":"def markaby_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/markdown_test.rb","line":4,"symbol":"markdown_app","kind":"method","lang":"ruby","code":"def markdown_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/markdown_test.rb","line":12,"symbol":"setup","kind":"method","lang":"ruby","code":"def setup\n Tilt.prefer engine, 'markdown', 'mkd', 'md'\n super\n end"}
{"repo":"sinatra","file":"test/markdown_test.rb","line":18,"symbol":"commonmarker_v1_or_higher?","kind":"method","lang":"ruby","doc":"commonmarker is not installed on all platforms (e.g. jruby)","code":"def commonmarker_v1_or_higher?\n defined?(CommonMarkerTest) && self.class == CommonMarkerTest && defined?(::Commonmarker)\n end"}
{"repo":"sinatra","file":"test/markdown_test.rb","line":24,"symbol":"commonmarker_v2_9_or_higher?","kind":"method","lang":"ruby","doc":"commonmarker 2.9.0 changed how heading anchors are rendered: the anchor now comes after the heading text and uses aria-label/data-heading-content instead of aria-hidden","code":"def commonmarker_v2_9_or_higher?\n commonmarker_v1_or_higher? && Gem::Version.new(::Commonmarker::VERSION) >= Gem::Version.new('2.9.0')\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":3,"symbol":"MiddlewareTest","kind":"class","lang":"ruby","code":"class MiddlewareTest < Minitest::Test\n setup do\n @app = mock_app(Sinatra::Application) do\n get('/*')do\n response.headers['X-Tests'] = env['test.ran'].\n map { |n| n.split('::').last }.\n join(', ')\n env['PATH_INFO']\n end\n end\n end\n\n class MockMiddleware < Struct.new(:app)\n def call(env)\n (env['test.ran'] ||= []) << self.class.to_s\n app.call(env)\n end\n end\n\n class UpcaseMiddleware < MockMiddleware\n def call(env)\n env['PATH_INFO'] = env['PATH_INFO'].upcase\n super\n end\n end\n\n it \"is added with Sinatra::Application.use\" do\n @app.use UpcaseMiddleware\n get '/hello-world'\n assert ok?\n assert_equal '/HELLO-WORLD', body\n end\n\n class DowncaseMiddleware < MockMiddleware\n def call(env)\n env['PATH_INFO'] = env['PATH_INFO'].downcase\n super\n end\n end\n\n it \"runs in the order defined\" do\n @app.use UpcaseMiddleware\n @app.use DowncaseMiddleware\n get '/Foo'\n assert_equal \"/foo\", body\n assert_equal \"UpcaseMiddleware, DowncaseMiddleware\", response['X-Tests']\n end\n\n it \"resets the prebuilt pipeline when new middleware is added\" do\n @app.use UpcaseMiddleware\n get '/Fo"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":15,"symbol":"MockMiddleware","kind":"class","lang":"ruby","code":"class MockMiddleware < Struct.new(:app)\n def call(env)\n (env['test.ran'] ||= []) << self.class.to_s\n app.call(env)\n end\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":16,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n (env['test.ran'] ||= []) << self.class.to_s\n app.call(env)\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":22,"symbol":"UpcaseMiddleware","kind":"class","lang":"ruby","code":"class UpcaseMiddleware < MockMiddleware\n def call(env)\n env['PATH_INFO'] = env['PATH_INFO'].upcase\n super\n end\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":23,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n env['PATH_INFO'] = env['PATH_INFO'].upcase\n super\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":36,"symbol":"DowncaseMiddleware","kind":"class","lang":"ruby","code":"class DowncaseMiddleware < MockMiddleware\n def call(env)\n env['PATH_INFO'] = env['PATH_INFO'].downcase\n super\n end\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":37,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n env['PATH_INFO'] = env['PATH_INFO'].downcase\n super\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":69,"symbol":"FreezeMiddleware","kind":"class","lang":"ruby","code":"class FreezeMiddleware < MockMiddleware\n def call(env)\n req = Rack::Request.new(env)\n req.update_param('bar', 'baz'.freeze)\n super\n end\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":70,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n req = Rack::Request.new(env)\n req.update_param('bar', 'baz'.freeze)\n super\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":82,"symbol":"SpecialConstsMiddleware","kind":"class","lang":"ruby","code":"class SpecialConstsMiddleware < MockMiddleware\n def call(env)\n req = Rack::Request.new(env)\n req.update_param('s', :s)\n req.update_param('i', 1)\n req.update_param('c', 3.to_c)\n req.update_param('t', true)\n req.update_param('f', false)\n req.update_param('n', nil)\n super\n end\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":83,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n req = Rack::Request.new(env)\n req.update_param('s', :s)\n req.update_param('i', 1)\n req.update_param('c', 3.to_c)\n req.update_param('t', true)\n req.update_param('f', false)\n req.update_param('n', nil)\n super\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":100,"symbol":"KeywordArgumentInitializationMiddleware","kind":"class","lang":"ruby","code":"class KeywordArgumentInitializationMiddleware < MockMiddleware\n def initialize(app, **)\n super app\n end\n end"}
{"repo":"sinatra","file":"test/middleware_test.rb","line":101,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app, **)\n super app\n end"}
{"repo":"sinatra","file":"test/nokogiri_test.rb","line":6,"symbol":"NokogiriTest","kind":"class","lang":"ruby","code":"class NokogiriTest < Minitest::Test\n def nokogiri_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline Nokogiri strings' do\n nokogiri_app { nokogiri '' }\n assert ok?\n assert_body %(<?xml version=\"1.0\"?>\\n)\n end\n\n it 'renders inline blocks' do\n nokogiri_app do\n @name = \"Frank & Mary\"\n nokogiri { |xml| xml.couple @name }\n end\n assert ok?\n assert_body %(<?xml version=\"1.0\"?>\\n<couple>Frank &amp; Mary</couple>\\n)\n end\n\n it 'renders .nokogiri files in views path' do\n nokogiri_app do\n @name = \"Blue\"\n nokogiri :hello\n end\n assert ok?\n assert_body \"<?xml version=\\\"1.0\\\"?>\\n<exclaim>You're my boy, Blue!</exclaim>\\n\"\n end\n\n it \"renders with inline layouts\" do\n next if Tilt::VERSION <= \"1.1\"\n mock_app do\n layout { %(xml.layout { xml << yield }) }\n get('/') { nokogiri %(xml.em 'Hello World') }\n end\n get '/'\n assert ok?\n assert_body %(<?xml version=\"1.0\"?>\\n<layout>\\n <em>Hello World</em>\\n</layout>\\n)\n end\n\n it \"renders with file layouts\" do\n next if Tilt::VERSION <= \"1.1\"\n nokogiri_app {\n nokogiri %(xml.em 'Hel"}
{"repo":"sinatra","file":"test/nokogiri_test.rb","line":7,"symbol":"nokogiri_app","kind":"method","lang":"ruby","code":"def nokogiri_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/rabl_test.rb","line":10,"symbol":"RablTest","kind":"class","lang":"ruby","code":"class RablTest < Minitest::Test\n def rabl_app(&block)\n mock_app {\n set :views, __dir__ + '/views'\n get '/', &block\n }\n get '/'\n end\n\n it 'renders inline rabl strings' do\n rabl_app do\n @foo = OpenStruct.new(:baz => 'w00t')\n rabl %q{\n object @foo\n attributes :baz\n }\n end\n assert ok?\n assert_equal '{\"openstruct\":{\"baz\":\"w00t\"}}', body\n end\n it 'renders .rabl files in views path' do\n rabl_app do\n @foo = OpenStruct.new(:bar => 'baz')\n rabl :hello\n end\n assert ok?\n assert_equal '{\"openstruct\":{\"bar\":\"baz\"}}', body\n end\n\n it \"renders with file layouts\" do\n rabl_app {\n @foo = OpenStruct.new(:bar => 'baz')\n rabl :hello, :layout => :layout2\n }\n assert ok?\n assert_equal '{\"qux\":{\"openstruct\":{\"bar\":\"baz\"}}}', body\n end\n\n it \"raises error if template not found\" do\n mock_app {\n get('/') { rabl :no_such_template }\n }\n assert_raises(Errno::ENOENT) { get('/') }\n end\n\n it \"passes rabl options to the rabl engine\" do\n mock_app do\n get('/') do\n @foo = OpenStruct.new(:bar => 'baz')\n rabl %q{\n object @foo\n attributes :bar\n }, :for"}
{"repo":"sinatra","file":"test/rabl_test.rb","line":11,"symbol":"rabl_app","kind":"method","lang":"ruby","code":"def rabl_app(&block)\n mock_app {\n set :views, __dir__ + '/views'\n get '/', &block\n }\n get '/'\n end"}
{"repo":"sinatra","file":"test/rack_test.rb","line":4,"symbol":"RackTest","kind":"class","lang":"ruby","code":"class RackTest < Minitest::Test\n setup do\n @foo = Sinatra.new { get('/foo') { 'foo' }}\n @bar = Sinatra.new { get('/bar') { 'bar' }}\n end\n\n def build(*middleware)\n endpoint = middleware.pop\n @app = Rack::Builder.app do\n middleware.each { |m| use m }\n run endpoint\n end\n end\n\n def check(*middleware)\n build(*middleware)\n assert get('/foo').ok?\n assert_body 'foo'\n assert get('/bar').ok?\n assert_body 'bar'\n end\n\n it 'works as middleware in front of Rack::Lock, with lock enabled' do\n @foo.enable :lock\n check(@foo, Rack::Lock, @bar)\n end\n\n it 'works as middleware behind Rack::Lock, with lock enabled' do\n @foo.enable :lock\n check(Rack::Lock, @foo, @bar)\n end\n\n it 'works as middleware in front of Rack::Lock, with lock disabled' do\n @foo.disable :lock\n check(@foo, Rack::Lock, @bar)\n end\n\n it 'works as middleware behind Rack::Lock, with lock disabled' do\n @foo.disable :lock\n check(Rack::Lock, @foo, @bar)\n end\nend"}
{"repo":"sinatra","file":"test/rack_test.rb","line":10,"symbol":"build","kind":"method","lang":"ruby","code":"def build(*middleware)\n endpoint = middleware.pop\n @app = Rack::Builder.app do\n middleware.each { |m| use m }\n run endpoint\n end\n end"}
{"repo":"sinatra","file":"test/rack_test.rb","line":18,"symbol":"check","kind":"method","lang":"ruby","code":"def check(*middleware)\n build(*middleware)\n assert get('/foo').ok?\n assert_body 'foo'\n assert get('/bar').ok?\n assert_body 'bar'\n end"}
{"repo":"sinatra","file":"test/rdoc_test.rb","line":7,"symbol":"RdocTest","kind":"class","lang":"ruby","code":"class RdocTest < Minitest::Test\n def rdoc_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline rdoc strings' do\n rdoc_app { rdoc '= Hiya' }\n assert ok?\n assert_body(/<h1[^>]*>(<.*>)?Hiya(<.*>)?<\\/h1>/)\n end\n\n it 'renders .rdoc files in views path' do\n rdoc_app { rdoc :hello }\n assert ok?\n assert_body(/<h1[^>]*>(<.*>)?Hello From RDoc(<.*>)?<\\/h1>/)\n end\n\n it \"raises error if template not found\" do\n mock_app { get('/') { rdoc :no_such_template } }\n assert_raises(Errno::ENOENT) { get('/') }\n end\n\n it \"renders with inline layouts\" do\n mock_app do\n layout { 'THIS. IS. #{yield.upcase}!' }\n get('/') { rdoc 'Sparta', :layout_engine => :str }\n end\n get '/'\n assert ok?\n assert_like 'THIS. IS. <P>SPARTA</P>!', body\n end\n\n it \"renders with file layouts\" do\n rdoc_app {\n rdoc 'Hello World', :layout => :layout2, :layout_engine => :erb\n }\n assert ok?\n assert_body \"ERB Layout!\\n<p>Hello World</p>\"\n end\n\n it \"can be used in a nested fashion for partials and whatnot\" do\n mock_app do\n template(:inner) { \"hi\" }\n template(:outer) { \""}
{"repo":"sinatra","file":"test/rdoc_test.rb","line":8,"symbol":"rdoc_app","kind":"method","lang":"ruby","code":"def rdoc_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/readme_test.rb","line":4,"symbol":"ReadmeTest","kind":"class","lang":"ruby","doc":"Tests to check if all the README examples work.","code":"class ReadmeTest < Minitest::Test\n example do\n mock_app { get('/') { 'Hello world!' } }\n get '/'\n assert_body 'Hello world!'\n end\n\n section \"Routes\" do\n example do\n mock_app do\n get('/') { \".. show something ..\" }\n\n post('/') { \".. create something ..\" }\n\n put('/') { \".. replace something ..\" }\n\n patch('/') { \".. modify something ..\" }\n\n delete('/') { \".. annihilate something ..\" }\n\n options('/') { \".. appease something ..\" }\n\n link('/') { \".. affiliate something ..\" }\n\n unlink('/') { \".. separate something ..\" }\n end\n\n get '/'\n assert_body '.. show something ..'\n\n post '/'\n assert_body '.. create something ..'\n\n put '/'\n assert_body '.. replace something ..'\n\n patch '/'\n assert_body '.. modify something ..'\n\n delete '/'\n assert_body '.. annihilate something ..'\n\n options '/'\n assert_body '.. appease something ..'\n\n link '/'\n assert_body '.. affiliate something ..'\n\n unlink '/'\n assert_body '.. separate something ..'\n end\n\n example do\n mock_app do\n get('/hello/:name') do\n # matches \"GET /hello/foo"}
{"repo":"sinatra","file":"test/request_test.rb","line":4,"symbol":"RequestTest","kind":"class","lang":"ruby","code":"class RequestTest < Minitest::Test\n it 'responds to #user_agent' do\n request = Sinatra::Request.new({'HTTP_USER_AGENT' => 'Test'})\n assert request.respond_to?(:user_agent)\n assert_equal 'Test', request.user_agent\n end\n\n it 'parses POST params when Content-Type is form-dataish' do\n request = Sinatra::Request.new(\n 'REQUEST_METHOD' => 'PUT',\n 'CONTENT_TYPE' => 'application/x-www-form-urlencoded',\n 'rack.input' => StringIO.new('foo=bar')\n )\n assert_equal 'bar', request.params['foo']\n end\n\n it 'raises Sinatra::BadRequest when multipart/form-data request has no content' do\n request = Sinatra::Request.new(\n 'REQUEST_METHOD' => 'POST',\n 'CONTENT_TYPE' => 'multipart/form-data; boundary=dummy',\n 'rack.input' => StringIO.new('')\n )\n assert_raises(Sinatra::BadRequest) { request.params }\n end\n\n it 'is secure when the url scheme is https' do\n request = Sinatra::Request.new('rack.url_scheme' => 'https')\n assert request.secure?\n end\n\n it 'is not secure when the url scheme is http' do\n request = Sinatra::Request.new('rack.url_scheme' => 'http')\n assert !request.secure?\n end\n\n it 'respects X-Forwarded-Host header' do\n "}
{"repo":"sinatra","file":"test/response_test.rb","line":3,"symbol":"ResponseTest","kind":"class","lang":"ruby","code":"class ResponseTest < Minitest::Test\n setup { @response = Sinatra::Response.new([], 200, { 'Content-Type' => 'text/html' }) }\n\n def assert_same_body(a, b)\n assert_equal a.to_enum(:each).to_a, b.to_enum(:each).to_a\n end\n\n it \"initializes with 200, text/html, and empty body\" do\n assert_equal 200, @response.status\n assert_equal 'text/html', @response['Content-Type']\n assert_equal [], @response.body\n end\n\n it 'uses case insensitive headers' do\n @response['content-type'] = 'application/foo'\n assert_equal 'application/foo', @response['Content-Type']\n assert_equal 'application/foo', @response['CONTENT-TYPE']\n end\n\n it 'writes to body' do\n @response.body = 'Hello'\n @response.write ' World'\n assert_equal 'Hello World', @response.body.join\n end\n\n [204, 304].each do |status_code|\n it \"removes the Content-Type header and body when response status is #{status_code}\" do\n @response.status = status_code\n @response.body = ['Hello World']\n assert_equal [status_code, {}, []], @response.finish\n end\n end\n\n [200, 201, 202, 301, 302, 400, 401, 403, 404, 500].each do |status_code|\n it \"will not removes the Content-Type header and body when r"}
{"repo":"sinatra","file":"test/response_test.rb","line":6,"symbol":"assert_same_body","kind":"method","lang":"ruby","code":"def assert_same_body(a, b)\n assert_equal a.to_enum(:each).to_a, b.to_enum(:each).to_a\n end"}
{"repo":"sinatra","file":"test/response_test.rb","line":58,"symbol":"inject","kind":"method","lang":"ruby","code":"def object.inject(*) fail 'called' end"}
{"repo":"sinatra","file":"test/response_test.rb","line":59,"symbol":"to_ary","kind":"method","lang":"ruby","code":"def object.to_ary(*) fail 'called' end"}
{"repo":"sinatra","file":"test/response_test.rb","line":60,"symbol":"each","kind":"method","lang":"ruby","code":"def object.each(*) end"}
{"repo":"sinatra","file":"test/result_test.rb","line":3,"symbol":"ThirdPartyError","kind":"class","lang":"ruby","code":"class ThirdPartyError < RuntimeError\n def http_status; 400 end\nend"}
{"repo":"sinatra","file":"test/result_test.rb","line":4,"symbol":"http_status","kind":"method","lang":"ruby","code":"def http_status; 400 end"}
{"repo":"sinatra","file":"test/result_test.rb","line":7,"symbol":"ResultTest","kind":"class","lang":"ruby","code":"class ResultTest < Minitest::Test\n it \"sets response.body when result is a String\" do\n mock_app { get('/') { 'Hello World' } }\n\n get '/'\n assert ok?\n assert_equal 'Hello World', body\n end\n\n it \"sets response.body when result is an Array of Strings\" do\n mock_app { get('/') { ['Hello', 'World'] } }\n\n get '/'\n assert ok?\n assert_equal 'HelloWorld', body\n end\n\n it \"sets response.body when result responds to #each\" do\n mock_app do\n get('/') do\n res = lambda { 'Hello World' }\n def res.each ; yield call ; end\n return res\n end\n end\n\n get '/'\n assert ok?\n assert_equal 'Hello World', body\n end\n\n it \"sets response.body to [] when result is nil\" do\n mock_app { get( '/') { nil } }\n\n get '/'\n assert ok?\n assert_equal '', body\n end\n\n it \"sets status, headers, and body when result is a Rack response tuple\" do\n mock_app {\n get('/') { [203, {'Content-Type' => 'foo/bar'}, 'Hello World'] }\n }\n\n get '/'\n assert_equal 203, status\n assert_equal 'foo/bar', response['Content-Type']\n assert_equal 'Hello World', body\n end\n\n it \"sets status and body when result is a two-tuple\" do\n mock_app { "}
{"repo":"sinatra","file":"test/result_test.rb","line":28,"symbol":"each","kind":"method","lang":"ruby","code":"def res.each ; yield call ; end"}
{"repo":"sinatra","file":"test/route_added_hook_test.rb","line":3,"symbol":"RouteAddedTest","kind":"module","lang":"ruby","code":"module RouteAddedTest\n @routes, @procs = [], []\n def self.routes ; @routes ; end\n def self.procs ; @procs ; end\n def self.route_added(verb, path, proc)\n @routes << [verb, path]\n @procs << proc\n end\nend"}
{"repo":"sinatra","file":"test/route_added_hook_test.rb","line":5,"symbol":"routes","kind":"method","lang":"ruby","code":"def self.routes ; @routes ; end"}
{"repo":"sinatra","file":"test/route_added_hook_test.rb","line":6,"symbol":"procs","kind":"method","lang":"ruby","code":"def self.procs ; @procs ; end"}
{"repo":"sinatra","file":"test/route_added_hook_test.rb","line":7,"symbol":"route_added","kind":"method","lang":"ruby","code":"def self.route_added(verb, path, proc)\n @routes << [verb, path]\n @procs << proc\n end"}
{"repo":"sinatra","file":"test/route_added_hook_test.rb","line":13,"symbol":"RouteAddedHookTest","kind":"class","lang":"ruby","code":"class RouteAddedHookTest < Minitest::Test\n setup do\n RouteAddedTest.routes.clear\n RouteAddedTest.procs.clear\n end\n\n it \"should be notified of an added route\" do\n mock_app(Class.new(Sinatra::Base)) do\n register RouteAddedTest\n get('/') {}\n end\n\n assert_equal [[\"GET\", \"/\"], [\"HEAD\", \"/\"]],\n RouteAddedTest.routes\n end\n\n it \"should include hooks from superclass\" do\n a = Class.new(Class.new(Sinatra::Base))\n b = Class.new(a)\n\n a.register RouteAddedTest\n b.class_eval { post(\"/sub_app_route\") {} }\n\n assert_equal [[\"POST\", \"/sub_app_route\"]],\n RouteAddedTest.routes\n end\n\n it \"should only run once per extension\" do\n mock_app(Class.new(Sinatra::Base)) do\n register RouteAddedTest\n register RouteAddedTest\n get('/') {}\n end\n\n assert_equal [[\"GET\", \"/\"], [\"HEAD\", \"/\"]],\n RouteAddedTest.routes\n end\n\n it \"should pass route blocks as an argument\" do\n mock_app(Class.new(Sinatra::Base)) do\n register RouteAddedTest\n get('/') {}\n end\n\n assert_kind_of Proc, RouteAddedTest.procs.first\n end\nend"}
{"repo":"sinatra","file":"test/routing_test.rb","line":4,"symbol":"route_def","kind":"method","lang":"ruby","doc":"Helper method for easy route pattern matching testing","code":"def route_def(pattern)\n mock_app { get(pattern) { } }\nend"}
{"repo":"sinatra","file":"test/routing_test.rb","line":8,"symbol":"PatternLookAlike","kind":"class","lang":"ruby","code":"class PatternLookAlike\n def to_pattern(*)\n self\n end\n\n def params(input)\n { \"one\" => +\"this\", \"two\" => +\"is\", \"three\" => +\"a\", \"four\" => +\"test\" }\n end\nend"}
{"repo":"sinatra","file":"test/routing_test.rb","line":9,"symbol":"to_pattern","kind":"method","lang":"ruby","code":"def to_pattern(*)\n self\n end"}
{"repo":"sinatra","file":"test/routing_test.rb","line":13,"symbol":"params","kind":"method","lang":"ruby","code":"def params(input)\n { \"one\" => +\"this\", \"two\" => +\"is\", \"three\" => +\"a\", \"four\" => +\"test\" }\n end"}
{"repo":"sinatra","file":"test/routing_test.rb","line":18,"symbol":"RoutingTest","kind":"class","lang":"ruby","code":"class RoutingTest < Minitest::Test\n %w[get put post delete options patch link unlink].each do |verb|\n it \"defines #{verb.upcase} request handlers with #{verb}\" do\n mock_app {\n send verb, '/hello' do\n 'Hello World'\n end\n }\n\n request = Rack::MockRequest.new(@app)\n response = request.request(verb.upcase, '/hello', {})\n assert response.ok?\n assert_equal 'Hello World', response.body\n end\n end\n\n it \"defines HEAD request handlers with HEAD\" do\n mock_app {\n head '/hello' do\n response['X-Hello'] = 'World!'\n 'remove me'\n end\n }\n\n request = Rack::MockRequest.new(@app)\n response = request.request('HEAD', '/hello', {})\n assert response.ok?\n assert_equal 'World!', response['X-Hello']\n assert_equal '', response.body\n end\n\n it \"400s when request params contain conflicting types\" do\n mock_app {\n get('/foo') { }\n }\n\n request = Rack::MockRequest.new(@app)\n response = request.request('GET', '/foo?bar=&bar[]=', {})\n assert response.bad_request?\n end\n\n it \"404s when no route satisfies the request\" do\n mock_app {\n get('/foo') { }\n }\n get '/bar'\n assert_equal "}
{"repo":"sinatra","file":"test/routing_test.rb","line":1516,"symbol":"protect","kind":"method","lang":"ruby","code":"def protect(*args)\n condition {\n unless authorize(params[\"user\"], params[\"password\"])\n halt 403, \"go away\"\n end\n }\n end"}
{"repo":"sinatra","file":"test/routing_test.rb","line":1529,"symbol":"authorize","kind":"method","lang":"ruby","code":"def authorize(username, password)\n username == \"foo\" && password == \"bar\"\n end"}
{"repo":"sinatra","file":"test/sass_test.rb","line":6,"symbol":"SassTest","kind":"class","lang":"ruby","code":"class SassTest < Minitest::Test\n def sass_app(options = {}, &block)\n mock_app do\n set :views, __dir__ + '/views'\n set options\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline Sass strings' do\n sass_app { sass \"#sass\\n background-color: white\\n\" }\n assert ok?\n assert_equal \"#sass {\\n background-color: white;\\n}\", body\n end\n\n it 'defaults content type to css' do\n sass_app { sass \"#sass\\n background-color: white\\n\" }\n assert ok?\n assert_equal \"text/css;charset=utf-8\", response['Content-Type']\n end\n\n it 'defaults allows setting content type per route' do\n sass_app do\n content_type :html\n sass \"#sass\\n background-color: white\\n\"\n end\n assert ok?\n assert_equal \"text/html;charset=utf-8\", response['Content-Type']\n end\n\n it 'defaults allows setting content type globally' do\n sass_app(:sass => { :content_type => 'html' }) {\n sass \"#sass\\n background-color: white\\n\"\n }\n assert ok?\n assert_equal \"text/html;charset=utf-8\", response['Content-Type']\n end\n\n it 'renders .sass files in views path' do\n sass_app { sass :hello }\n assert ok?\n assert_equal \"#sass {\\n background-color: white"}
{"repo":"sinatra","file":"test/sass_test.rb","line":7,"symbol":"sass_app","kind":"method","lang":"ruby","code":"def sass_app(options = {}, &block)\n mock_app do\n set :views, __dir__ + '/views'\n set options\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/scss_test.rb","line":6,"symbol":"ScssTest","kind":"class","lang":"ruby","code":"class ScssTest < Minitest::Test\n def scss_app(options = {}, &block)\n mock_app do\n set :views, __dir__ + '/views'\n set options\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline Scss strings' do\n scss_app { scss \"#scss {\\n background-color: white; }\\n\" }\n assert ok?\n assert_equal \"#scss {\\n background-color: white;\\n}\", body\n end\n\n it 'defaults content type to css' do\n scss_app { scss \"#scss {\\n background-color: white; }\\n\" }\n assert ok?\n assert_equal \"text/css;charset=utf-8\", response['Content-Type']\n end\n\n it 'defaults allows setting content type per route' do\n scss_app do\n content_type :html\n scss \"#scss {\\n background-color: white; }\\n\"\n end\n assert ok?\n assert_equal \"text/html;charset=utf-8\", response['Content-Type']\n end\n\n it 'defaults allows setting content type globally' do\n scss_app(:scss => { :content_type => 'html' }) {\n scss \"#scss {\\n background-color: white; }\\n\"\n }\n assert ok?\n assert_equal \"text/html;charset=utf-8\", response['Content-Type']\n end\n\n it 'renders .scss files in views path' do\n scss_app { scss :hello }\n assert ok?\n assert_equal \"#scss {\\n bac"}
{"repo":"sinatra","file":"test/scss_test.rb","line":7,"symbol":"scss_app","kind":"method","lang":"ruby","code":"def scss_app(options = {}, &block)\n mock_app do\n set :views, __dir__ + '/views'\n set options\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":5,"symbol":"Mock","kind":"class","lang":"ruby","code":"class Mock\n extend Minitest::Assertions\n # Allow assertions in request context\n def self.assertions\n @assertions ||= 0\n end\n\n def self.assertions= assertions\n @assertions = assertions\n end\n\n def self.run(app, options={})\n assert(app < Sinatra::Base)\n assert_equal 9001, options[:Port]\n assert_equal 'foo.local', options[:Host]\n yield new\n end\n\n def stop\n end\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":8,"symbol":"assertions","kind":"method","lang":"ruby","doc":"Allow assertions in request context","code":"def self.assertions\n @assertions ||= 0\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":16,"symbol":"run","kind":"method","lang":"ruby","code":"def self.run(app, options={})\n assert(app < Sinatra::Base)\n assert_equal 9001, options[:Port]\n assert_equal 'foo.local', options[:Host]\n yield new\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":23,"symbol":"stop","kind":"method","lang":"ruby","code":"def stop\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":30,"symbol":"ServerTest","kind":"class","lang":"ruby","code":"class ServerTest < Minitest::Test\n setup do\n mock_app do\n set :server, 'mock'\n set :bind, 'foo.local'\n set :port, 9001\n end\n $stderr = StringIO.new\n end\n\n def teardown\n $stderr = STDERR\n end\n\n it \"locates the appropriate Rack handler and calls ::run\" do\n @app.run!\n end\n\n context \"event hooks\" do\n dummy_class = Class.new do\n def self.start_hook; end\n def self.stop_hook; end\n end\n\n it \"runs the provided code when the server starts\" do\n @app.on_start do\n dummy_class.start_hook\n end\n mock = Minitest::Mock.new\n mock.expect(:call, nil)\n\n dummy_class.stub(:start_hook, mock) do\n @app.run!\n end\n\n assert_mock mock\n end\n\n it \"runs the provided code when the server stops\" do\n @app.on_stop do\n dummy_class.stop_hook\n end\n mock = Minitest::Mock.new\n mock.expect(:call, nil)\n\n dummy_class.stub(:stop_hook, mock) do\n @app.run!\n @app.quit!\n end\n\n assert_mock mock\n end\n end\n\n it \"sets options on the app before running\" do\n @app.run! :sessions => true\n assert @app.sessions?\n end\n\n it \"falls back on the next server handler when"}
{"repo":"sinatra","file":"test/server_test.rb","line":40,"symbol":"teardown","kind":"method","lang":"ruby","code":"def teardown\n $stderr = STDERR\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":50,"symbol":"start_hook","kind":"method","lang":"ruby","code":"def self.start_hook; end"}
{"repo":"sinatra","file":"test/server_test.rb","line":51,"symbol":"stop_hook","kind":"method","lang":"ruby","code":"def self.stop_hook; end"}
{"repo":"sinatra","file":"test/server_test.rb","line":94,"symbol":"MyMiddleware","kind":"class","lang":"ruby","code":"class MyMiddleware\n @@initialized = false\n def initialize(app)\n @@initialized = true\n end\n def self.initialized\n @@initialized\n end\n def call(env)\n end\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":96,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(app)\n @@initialized = true\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":99,"symbol":"initialized","kind":"method","lang":"ruby","code":"def self.initialized\n @@initialized\n end"}
{"repo":"sinatra","file":"test/server_test.rb","line":102,"symbol":"call","kind":"method","lang":"ruby","code":"def call(env)\n end"}
{"repo":"sinatra","file":"test/settings_test.rb","line":3,"symbol":"SettingsTest","kind":"class","lang":"ruby","code":"class SettingsTest < Minitest::Test\n setup do\n @base = Sinatra.new(Sinatra::Base)\n @base.set :environment => :foo, :app_file => nil\n\n @application = Sinatra.new(Sinatra::Application)\n @application.set :environment => :foo, :app_file => nil\n end\n\n it 'sets settings to literal values' do\n @base.set(:foo, 'bar')\n assert @base.respond_to?(:foo)\n assert_equal 'bar', @base.foo\n end\n\n it 'sets settings to Procs' do\n @base.set(:foo, Proc.new { 'baz' })\n assert @base.respond_to?(:foo)\n assert_equal 'baz', @base.foo\n end\n\n it 'sets settings using a block' do\n @base.set(:foo){ 'baz' }\n assert @base.respond_to?(:foo)\n assert_equal 'baz', @base.foo\n end\n\n it 'raises an error with a value and a block' do\n assert_raises ArgumentError do\n @base.set(:fiz, 'boom!'){ 'baz' }\n end\n assert !@base.respond_to?(:fiz)\n end\n\n it 'raises an error without value and block' do\n assert_raises(ArgumentError) { @base.set(:fiz) }\n assert !@base.respond_to?(:fiz)\n end\n\n it 'allows setting a value to the app class' do\n @base.set :base, @base\n assert @base.respond_to?(:base)\n assert_equal @base, @base.base\n end\n\n it 'raises an error wit"}
{"repo":"sinatra","file":"test/settings_test.rb","line":106,"symbol":"foo","kind":"method","lang":"ruby","code":"def foo\n @foo\n end"}
{"repo":"sinatra","file":"test/settings_test.rb","line":458,"symbol":"priv","kind":"method","lang":"ruby","code":"def priv; end"}
{"repo":"sinatra","file":"test/settings_test.rb","line":460,"symbol":"pub","kind":"method","lang":"ruby","code":"def pub; end"}
{"repo":"sinatra","file":"test/settings_test.rb","line":579,"symbol":"MiddlewareTracker","kind":"class","lang":"ruby","code":"class MiddlewareTracker < Rack::Builder\n def self.track\n Rack.send :remove_const, :Builder\n Rack.const_set :Builder, MiddlewareTracker\n MiddlewareTracker.used.clear\n yield\n ensure\n Rack.send :remove_const, :Builder\n Rack.const_set :Builder, MiddlewareTracker.superclass\n end\n\n def self.used\n @used ||= []\n end\n\n def use(middleware, *)\n MiddlewareTracker.used << middleware\n super\n end\n end"}
{"repo":"sinatra","file":"test/settings_test.rb","line":580,"symbol":"track","kind":"method","lang":"ruby","code":"def self.track\n Rack.send :remove_const, :Builder\n Rack.const_set :Builder, MiddlewareTracker\n MiddlewareTracker.used.clear\n yield\n ensure\n Rack.send :remove_const, :Builder\n Rack.const_set :Builder, MiddlewareTracker.superclass\n end"}
{"repo":"sinatra","file":"test/settings_test.rb","line":590,"symbol":"used","kind":"method","lang":"ruby","code":"def self.used\n @used ||= []\n end"}
{"repo":"sinatra","file":"test/settings_test.rb","line":594,"symbol":"use","kind":"method","lang":"ruby","code":"def use(middleware, *)\n MiddlewareTracker.used << middleware\n super\n end"}
{"repo":"sinatra","file":"test/sinatra_test.rb","line":3,"symbol":"SinatraTest","kind":"class","lang":"ruby","code":"class SinatraTest < Minitest::Test\n it 'creates a new Sinatra::Base subclass on new' do\n app = Sinatra.new { get('/') { 'Hello World' } }\n assert_same Sinatra::Base, app.superclass\n end\n\n it \"responds to #template_cache\" do\n assert_kind_of Sinatra::TemplateCache, Sinatra::Base.new!.template_cache\n end\nend"}
{"repo":"sinatra","file":"test/slim_test.rb","line":6,"symbol":"SlimTest","kind":"class","lang":"ruby","code":"class SlimTest < Minitest::Test\n def slim_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline slim strings' do\n slim_app { slim \"h1 Hiya\\n\" }\n assert ok?\n assert_equal \"<h1>Hiya</h1>\", body\n end\n\n it 'renders .slim files in views path' do\n slim_app { slim :hello }\n assert ok?\n assert_equal \"<h1>Hello From Slim</h1>\", body\n end\n\n it \"renders with inline layouts\" do\n mock_app do\n layout { %(h1\\n | THIS. IS. \\n == yield.upcase ) }\n get('/') { slim 'em Sparta' }\n end\n get '/'\n assert ok?\n assert_equal \"<h1>THIS. IS. <EM>SPARTA</EM></h1>\", body\n end\n\n it \"renders with file layouts\" do\n slim_app { slim('| Hello World', :layout => :layout2) }\n assert ok?\n assert_equal \"<h1>Slim Layout!</h1><p>Hello World</p>\", body\n end\n\n it \"raises error if template not found\" do\n mock_app { get('/') { slim(:no_such_template) } }\n assert_raises(Errno::ENOENT) { get('/') }\n end\n\n HTML4_DOCTYPE = \"<!DOCTYPE html PUBLIC \\\"-//W3C//DTD HTML 4.01 Transitional//EN\\\" \\\"http://www.w3.org/TR/html4/loose.dtd\\\">\"\n\n it \"passes slim options to the slim engine\" do\n "}
{"repo":"sinatra","file":"test/slim_test.rb","line":7,"symbol":"slim_app","kind":"method","lang":"ruby","code":"def slim_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/static_test.rb","line":3,"symbol":"StaticTest","kind":"class","lang":"ruby","code":"class StaticTest < Minitest::Test\n setup do\n mock_app do\n set :static, true\n set :public_folder, __dir__\n end\n end\n\n it 'serves GET requests for files in the public directory' do\n get \"/#{File.basename(__FILE__)}\"\n assert ok?\n assert_equal File.read(__FILE__), body\n assert_equal File.size(__FILE__).to_s, response['Content-Length']\n assert response.headers.include?('Last-Modified')\n end\n\n it 'produces a body that can be iterated over multiple times' do\n env = Rack::MockRequest.env_for(\"/#{File.basename(__FILE__)}\")\n _, _, body = @app.call(env)\n buf1, buf2 = [], []\n body.each { |part| buf1 << part }\n body.each { |part| buf2 << part }\n assert_equal buf1.join, buf2.join\n assert_equal File.read(__FILE__), buf1.join\n end\n\n it 'sets the sinatra.static_file env variable if served' do\n env = Rack::MockRequest.env_for(\"/#{File.basename(__FILE__)}\")\n @app.call(env)\n assert_equal File.expand_path(__FILE__), env['sinatra.static_file']\n end\n\n it 'serves HEAD requests for files in the public directory' do\n head \"/#{File.basename(__FILE__)}\"\n assert ok?\n assert_equal '', body\n assert response.headers.include?('Last-M"}
{"repo":"sinatra","file":"test/static_test.rb","line":106,"symbol":"assert_valid_range","kind":"method","lang":"ruby","code":"def assert_valid_range(http_range, range, path, file)\n request = Rack::MockRequest.new(@app)\n response = request.get(\"/#{File.basename(path)}\", 'HTTP_RANGE' => http_range)\n\n should_be = file[range]\n expected_range = \"bytes #{range.begin}-#{range.end}/#{file.length}\"\n\n assert_equal(\n 206,response.status,\n \"Should be HTTP/1.1 206 Partial content\"\n )\n assert_equal(\n should_be.length,\n response.body.length,\n \"Unexpected response length for #{http_range}\"\n )\n assert_equal(\n should_be,\n response.body,\n \"Unexpected response data for #{http_range}\"\n )\n assert_equal(\n should_be.length.to_s,\n response['Content-Length'],\n \"Incorrect Content-Length for #{http_range}\"\n )\n assert_equal(\n expected_range,\n response['Content-Range'],\n \"Incorrect Content-Range for #{http_range}\"\n )\n end"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":3,"symbol":"StreamingTest","kind":"class","lang":"ruby","code":"class StreamingTest < Minitest::Test\n Stream = Sinatra::Helpers::Stream\n\n it 'returns the concatenated body' do\n mock_app do\n get('/') do\n stream do |out|\n out << \"Hello\" << \" \"\n out << \"World!\"\n end\n end\n end\n\n get('/')\n assert_body \"Hello World!\"\n end\n\n it 'always yields strings' do\n stream = Stream.new { |out| out << :foo }\n stream.each { |str| assert_equal 'foo', str }\n end\n\n it 'postpones body generation' do\n step = 0\n\n stream = Stream.new do |out|\n 10.times do\n out << step\n step += 1\n end\n end\n\n stream.each do |s|\n assert_equal s, step.to_s\n step += 1\n end\n end\n\n it 'calls the callback after it is done' do\n step = 0\n final = 0\n stream = Stream.new { |_| 10.times { step += 1 }}\n stream.callback { final = step }\n stream.each {|_|}\n assert_equal 10, final\n end\n\n it 'does not trigger the callback if close is set to :keep_open' do\n step = 0\n final = 0\n stream = Stream.new(Stream, :keep_open) { |_| 10.times { step += 1 } }\n stream.callback { final = step }\n stream.each {|_|}\n assert_equal 0, final\n end\n\n it 'allows adding"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":69,"symbol":"MockScheduler","kind":"class","lang":"ruby","code":"class MockScheduler\n def initialize(*) @schedule, @defer = [], [] end\n def schedule(&block) @schedule << block end\n def defer(&block) @defer << block end\n def schedule!(*) @schedule.pop.call until @schedule.empty? end\n def defer!(*) @defer.pop.call until @defer.empty? end\n end"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":70,"symbol":"initialize","kind":"method","lang":"ruby","code":"def initialize(*) @schedule, @defer = [], [] end"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":71,"symbol":"schedule","kind":"method","lang":"ruby","code":"def schedule(&block) @schedule << block end"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":72,"symbol":"defer","kind":"method","lang":"ruby","code":"def defer(&block) @defer << block end"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":73,"symbol":"schedule!","kind":"method","lang":"ruby","code":"def schedule!(*) @schedule.pop.call until @schedule.empty? end"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":74,"symbol":"defer!","kind":"method","lang":"ruby","code":"def defer!(*) @defer.pop.call until @defer.empty? end"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":131,"symbol":"callback","kind":"method","lang":"ruby","code":"def close.callback; yield end"}
{"repo":"sinatra","file":"test/streaming_test.rb","line":132,"symbol":"errback","kind":"method","lang":"ruby","code":"def close.errback; end"}
{"repo":"sinatra","file":"test/templates_test.rb","line":4,"symbol":"TestTemplate","kind":"class","lang":"ruby","code":"class TestTemplate < Tilt::Template\n def prepare\n end\n\n def evaluate(scope, locals={}, &block)\n inner = block ? block.call : ''\n data + inner\n end\n\n Tilt.register 'test', self\nend"}
{"repo":"sinatra","file":"test/templates_test.rb","line":5,"symbol":"prepare","kind":"method","lang":"ruby","code":"def prepare\n end"}
{"repo":"sinatra","file":"test/templates_test.rb","line":8,"symbol":"evaluate","kind":"method","lang":"ruby","code":"def evaluate(scope, locals={}, &block)\n inner = block ? block.call : ''\n data + inner\n end"}
{"repo":"sinatra","file":"test/templates_test.rb","line":16,"symbol":"TemplatesTest","kind":"class","lang":"ruby","code":"class TemplatesTest < Minitest::Test\n def render_app(base=Sinatra::Base, options = {}, &block)\n base, options = Sinatra::Base, base if base.is_a? Hash\n mock_app(base) do\n set :views, __dir__ + '/views'\n set options\n get('/', &block)\n template(:layout3) { \"Layout 3!\\n\" }\n end\n get '/'\n end\n\n def with_default_layout\n layout = __dir__ + '/views/layout.test'\n File.open(layout, 'wb') { |io| io.write \"Layout!\\n\" }\n yield\n ensure\n File.unlink(layout) rescue nil\n end\n\n it 'falls back to engine layout' do\n mock_app do\n template(:layout3) { 'Layout 3!<%= yield %>' }\n set :erb, :layout => :layout3\n\n get('/') do\n erb('Hello World!', { :layout => true })\n end\n end\n\n get '/'\n assert ok?\n assert_equal \"Layout 3!Hello World!\", body\n end\n\n it 'falls back to default layout if engine layout is true' do\n mock_app do\n template(:layout) { 'Layout!!! <%= yield %>' }\n set :erb, :layout => true\n\n get('/') do\n erb('Hello World!', { :layout => true })\n end\n end\n\n get '/'\n assert ok?\n assert_equal \"Layout!!! Hello World!\", body\n end\n\n it 'renders no layout if layout if fals"}
{"repo":"sinatra","file":"test/templates_test.rb","line":17,"symbol":"render_app","kind":"method","lang":"ruby","code":"def render_app(base=Sinatra::Base, options = {}, &block)\n base, options = Sinatra::Base, base if base.is_a? Hash\n mock_app(base) do\n set :views, __dir__ + '/views'\n set options\n get('/', &block)\n template(:layout3) { \"Layout 3!\\n\" }\n end\n get '/'\n end"}
{"repo":"sinatra","file":"test/templates_test.rb","line":28,"symbol":"with_default_layout","kind":"method","lang":"ruby","code":"def with_default_layout\n layout = __dir__ + '/views/layout.test'\n File.open(layout, 'wb') { |io| io.write \"Layout!\\n\" }\n yield\n ensure\n File.unlink(layout) rescue nil\n end"}
{"repo":"sinatra","file":"test/templates_test.rb","line":363,"symbol":"foo","kind":"method","lang":"ruby","code":"def some_scope.foo() 'World!' end"}
{"repo":"sinatra","file":"test/templates_test.rb","line":376,"symbol":"find_template","kind":"method","lang":"ruby","code":"def find_template(views, name, engine, &block)\n Array(views).each { |v| super(v, name, engine, &block) }\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":40,"symbol":"assertions","kind":"method","lang":"ruby","doc":"Allow assertions in request context","code":"def assertions\n @assertions ||= 0\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":48,"symbol":"include?","kind":"method","lang":"ruby","code":"def include?(middleware)\n @ins.any? { |m| middleware === m }\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":63,"symbol":"example","kind":"method","lang":"ruby","code":"def self.example(desc = nil, &block)\n @example_count = 0 unless instance_variable_defined? :@example_count\n @example_count += 1\n it(desc || \"Example #{@example_count}\", &block)\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":78,"symbol":"mock_app","kind":"method","lang":"ruby","doc":"Sets up a Sinatra::Base subclass defined with the block given. Used in setup or individual spec methods to establish the application.","code":"def mock_app(base=Sinatra::Base, &block)\n @app = Sinatra.new(base, &block)\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":82,"symbol":"app","kind":"method","lang":"ruby","code":"def app\n Rack::Lint.new(@app)\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":86,"symbol":"body","kind":"method","lang":"ruby","code":"def body\n response.body.to_s\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":90,"symbol":"assert_body","kind":"method","lang":"ruby","code":"def assert_body(value)\n if value.respond_to? :to_str\n assert_equal value.lstrip.gsub(/\\s*\\n\\s*/, \"\"), body.lstrip.gsub(/\\s*\\n\\s*/, \"\")\n else\n assert_match value, body\n end\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":98,"symbol":"assert_status","kind":"method","lang":"ruby","code":"def assert_status(expected)\n assert_equal Integer(expected), Integer(status)\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":102,"symbol":"assert_like","kind":"method","lang":"ruby","code":"def assert_like(a,b)\n pattern = /id=['\"][^\"']*[\"']|\\s+/\n assert_equal a.strip.gsub(pattern, \"\"), b.strip.gsub(pattern, \"\")\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":107,"symbol":"assert_include","kind":"method","lang":"ruby","code":"def assert_include(str, substr)\n assert str.include?(substr), \"expected #{str.inspect} to include #{substr.inspect}\"\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":111,"symbol":"options","kind":"method","lang":"ruby","code":"def options(uri, params = {}, env = {}, &block)\n request(uri, env.merge(:method => \"OPTIONS\", :params => params), &block)\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":115,"symbol":"patch","kind":"method","lang":"ruby","code":"def patch(uri, params = {}, env = {}, &block)\n request(uri, env.merge(:method => \"PATCH\", :params => params), &block)\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":119,"symbol":"link","kind":"method","lang":"ruby","code":"def link(uri, params = {}, env = {}, &block)\n request(uri, env.merge(:method => \"LINK\", :params => params), &block)\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":123,"symbol":"unlink","kind":"method","lang":"ruby","code":"def unlink(uri, params = {}, env = {}, &block)\n request(uri, env.merge(:method => \"UNLINK\", :params => params), &block)\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":128,"symbol":"method_missing","kind":"method","lang":"ruby","doc":"Delegate other missing methods to response.","code":"def method_missing(name, *args, &block)\n if response && response.respond_to?(name)\n response.send(name, *args, &block)\n else\n super\n end\n rescue Rack::Test::Error\n super\n end"}
{"repo":"sinatra","file":"test/test_helper.rb","line":139,"symbol":"silence_warnings","kind":"method","lang":"ruby","doc":"Do not output warnings for the duration of the block.","code":"def silence_warnings\n $VERBOSE, v = nil, $VERBOSE\n yield\n ensure\n $VERBOSE = v\n end"}
{"repo":"sinatra","file":"test/yajl_test.rb","line":6,"symbol":"YajlTest","kind":"class","lang":"ruby","code":"class YajlTest < Minitest::Test\n def yajl_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end\n\n it 'renders inline Yajl strings' do\n yajl_app { yajl('json = { :foo => \"bar\" }') }\n assert ok?\n assert_body '{\"foo\":\"bar\"}'\n end\n\n it 'renders .yajl files in views path' do\n yajl_app { yajl(:hello) }\n assert ok?\n assert_body '{\"yajl\":\"hello\"}'\n end\n\n it 'raises error if template not found' do\n mock_app { get('/') { yajl(:no_such_template) } }\n assert_raises(Errno::ENOENT) { get('/') }\n end\n\n it 'accepts a :locals option' do\n yajl_app do\n locals = { :object => { :foo => 'bar' } }\n yajl 'json = object', :locals => locals\n end\n assert ok?\n assert_body '{\"foo\":\"bar\"}'\n end\n\n it 'accepts a :scope option' do\n yajl_app do\n scope = { :object => { :foo => 'bar' } }\n yajl 'json = self[:object]', :scope => scope\n end\n assert ok?\n assert_body '{\"foo\":\"bar\"}'\n end\n\n it 'decorates the json with a callback' do\n yajl_app do\n yajl(\n 'json = { :foo => \"bar\" }',\n { :callback => 'baz' }\n )\n end\n assert ok?\n assert_body 'baz({\"foo\":\""}
{"repo":"sinatra","file":"test/yajl_test.rb","line":7,"symbol":"yajl_app","kind":"method","lang":"ruby","code":"def yajl_app(&block)\n mock_app do\n set :views, __dir__ + '/views'\n get('/', &block)\n end\n get '/'\n end"}