id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
17,000
untra/polyglot
lib/jekyll/polyglot/patches/jekyll/site.rb
Jekyll.Site.coordinate_documents
def coordinate_documents(docs) regex = document_url_regex approved = {} docs.each do |doc| lang = doc.data['lang'] || @default_lang url = doc.url.gsub(regex, '/') doc.data['permalink'] = url next if @file_langs[url] == @active_lang next if @file_langs[url] == @default_lang && lang != @active_lang approved[url] = doc @file_langs[url] = lang end approved.values end
ruby
def coordinate_documents(docs) regex = document_url_regex approved = {} docs.each do |doc| lang = doc.data['lang'] || @default_lang url = doc.url.gsub(regex, '/') doc.data['permalink'] = url next if @file_langs[url] == @active_lang next if @file_langs[url] == @default_lang && lang != @active_lang approved[url] = doc @file_langs[url] = lang end approved.values end
[ "def", "coordinate_documents", "(", "docs", ")", "regex", "=", "document_url_regex", "approved", "=", "{", "}", "docs", ".", "each", "do", "|", "doc", "|", "lang", "=", "doc", ".", "data", "[", "'lang'", "]", "||", "@default_lang", "url", "=", "doc", ".", "url", ".", "gsub", "(", "regex", ",", "'/'", ")", "doc", ".", "data", "[", "'permalink'", "]", "=", "url", "next", "if", "@file_langs", "[", "url", "]", "==", "@active_lang", "next", "if", "@file_langs", "[", "url", "]", "==", "@default_lang", "&&", "lang", "!=", "@active_lang", "approved", "[", "url", "]", "=", "doc", "@file_langs", "[", "url", "]", "=", "lang", "end", "approved", ".", "values", "end" ]
assigns natural permalinks to documents and prioritizes documents with active_lang languages over others
[ "assigns", "natural", "permalinks", "to", "documents", "and", "prioritizes", "documents", "with", "active_lang", "languages", "over", "others" ]
23163148ba91daef1ce536b37a62c1ca67c05e84
https://github.com/untra/polyglot/blob/23163148ba91daef1ce536b37a62c1ca67c05e84/lib/jekyll/polyglot/patches/jekyll/site.rb#L93-L106
17,001
untra/polyglot
lib/jekyll/polyglot/patches/jekyll/site.rb
Jekyll.Site.process_documents
def process_documents(docs) return if @active_lang == @default_lang url = config.fetch('url', false) rel_regex = relative_url_regex abs_regex = absolute_url_regex(url) docs.each do |doc| relativize_urls(doc, rel_regex) if url then relativize_absolute_urls(doc, abs_regex, url) end end end
ruby
def process_documents(docs) return if @active_lang == @default_lang url = config.fetch('url', false) rel_regex = relative_url_regex abs_regex = absolute_url_regex(url) docs.each do |doc| relativize_urls(doc, rel_regex) if url then relativize_absolute_urls(doc, abs_regex, url) end end end
[ "def", "process_documents", "(", "docs", ")", "return", "if", "@active_lang", "==", "@default_lang", "url", "=", "config", ".", "fetch", "(", "'url'", ",", "false", ")", "rel_regex", "=", "relative_url_regex", "abs_regex", "=", "absolute_url_regex", "(", "url", ")", "docs", ".", "each", "do", "|", "doc", "|", "relativize_urls", "(", "doc", ",", "rel_regex", ")", "if", "url", "then", "relativize_absolute_urls", "(", "doc", ",", "abs_regex", ",", "url", ")", "end", "end", "end" ]
performs any necesarry operations on the documents before rendering them
[ "performs", "any", "necesarry", "operations", "on", "the", "documents", "before", "rendering", "them" ]
23163148ba91daef1ce536b37a62c1ca67c05e84
https://github.com/untra/polyglot/blob/23163148ba91daef1ce536b37a62c1ca67c05e84/lib/jekyll/polyglot/patches/jekyll/site.rb#L109-L120
17,002
schneems/maildown
lib/maildown/ext/action_view.rb
ActionView.OptimizedFileSystemResolver.extract_handler_and_format_and_variant
def extract_handler_and_format_and_variant(*args) if args.first.end_with?('md.erb') path = args.shift path = path.gsub(/\.md\.erb\z/, '.md+erb') args.unshift(path) end return original_extract_handler_and_format_and_variant(*args) end
ruby
def extract_handler_and_format_and_variant(*args) if args.first.end_with?('md.erb') path = args.shift path = path.gsub(/\.md\.erb\z/, '.md+erb') args.unshift(path) end return original_extract_handler_and_format_and_variant(*args) end
[ "def", "extract_handler_and_format_and_variant", "(", "*", "args", ")", "if", "args", ".", "first", ".", "end_with?", "(", "'md.erb'", ")", "path", "=", "args", ".", "shift", "path", "=", "path", ".", "gsub", "(", "/", "\\.", "\\.", "\\z", "/", ",", "'.md+erb'", ")", "args", ".", "unshift", "(", "path", ")", "end", "return", "original_extract_handler_and_format_and_variant", "(", "args", ")", "end" ]
Different versions of rails have different method signatures here, path is always first
[ "Different", "versions", "of", "rails", "have", "different", "method", "signatures", "here", "path", "is", "always", "first" ]
fc2220194dc2d32ef8313981503723a9657824ff
https://github.com/schneems/maildown/blob/fc2220194dc2d32ef8313981503723a9657824ff/lib/maildown/ext/action_view.rb#L13-L20
17,003
gocardless/gocardless-pro-ruby
lib/gocardless_pro/api_service.rb
GoCardlessPro.ApiService.make_request
def make_request(method, path, options = {}) raise ArgumentError, 'options must be a hash' unless options.is_a?(Hash) options[:headers] ||= {} options[:headers] = @headers.merge(options[:headers]) Request.new(@connection, method, @path_prefix + path, options).request end
ruby
def make_request(method, path, options = {}) raise ArgumentError, 'options must be a hash' unless options.is_a?(Hash) options[:headers] ||= {} options[:headers] = @headers.merge(options[:headers]) Request.new(@connection, method, @path_prefix + path, options).request end
[ "def", "make_request", "(", "method", ",", "path", ",", "options", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'options must be a hash'", "unless", "options", ".", "is_a?", "(", "Hash", ")", "options", "[", ":headers", "]", "||=", "{", "}", "options", "[", ":headers", "]", "=", "@headers", ".", "merge", "(", "options", "[", ":headers", "]", ")", "Request", ".", "new", "(", "@connection", ",", "method", ",", "@path_prefix", "+", "path", ",", "options", ")", ".", "request", "end" ]
Initialize an APIService @param url [String] the URL to make requests to @param key [String] the API Key ID to use @param secret [String] the API key secret to use @param options [Hash] additional options to use when creating the service Make a request to the API @param method [Symbol] the method to use to make the request @param path [String] the URL (without the base domain) to make the request to @param options [Hash] the options hash
[ "Initialize", "an", "APIService" ]
9473ecfa64eef2de6d5a404357c0db90de57efb1
https://github.com/gocardless/gocardless-pro-ruby/blob/9473ecfa64eef2de6d5a404357c0db90de57efb1/lib/gocardless_pro/api_service.rb#L44-L49
17,004
gocardless/gocardless-pro-ruby
lib/gocardless_pro/paginator.rb
GoCardlessPro.Paginator.enumerator
def enumerator response = get_initial_response Enumerator.new do |yielder| loop do response.records.each { |item| yielder << item } after_cursor = response.after break if after_cursor.nil? @options[:params] ||= {} @options[:params] = @options[:params].merge(after: after_cursor) response = @service.list(@options.merge(after: after_cursor)) end end.lazy end
ruby
def enumerator response = get_initial_response Enumerator.new do |yielder| loop do response.records.each { |item| yielder << item } after_cursor = response.after break if after_cursor.nil? @options[:params] ||= {} @options[:params] = @options[:params].merge(after: after_cursor) response = @service.list(@options.merge(after: after_cursor)) end end.lazy end
[ "def", "enumerator", "response", "=", "get_initial_response", "Enumerator", ".", "new", "do", "|", "yielder", "|", "loop", "do", "response", ".", "records", ".", "each", "{", "|", "item", "|", "yielder", "<<", "item", "}", "after_cursor", "=", "response", ".", "after", "break", "if", "after_cursor", ".", "nil?", "@options", "[", ":params", "]", "||=", "{", "}", "@options", "[", ":params", "]", "=", "@options", "[", ":params", "]", ".", "merge", "(", "after", ":", "after_cursor", ")", "response", "=", "@service", ".", "list", "(", "@options", ".", "merge", "(", "after", ":", "after_cursor", ")", ")", "end", "end", ".", "lazy", "end" ]
initialize a paginator @param options [Hash] @option options :service the service class to use to make requests to @option options :options additional options to send with the requests Get a lazy enumerable for listing data from the API
[ "initialize", "a", "paginator" ]
9473ecfa64eef2de6d5a404357c0db90de57efb1
https://github.com/gocardless/gocardless-pro-ruby/blob/9473ecfa64eef2de6d5a404357c0db90de57efb1/lib/gocardless_pro/paginator.rb#L14-L28
17,005
gocardless/gocardless-pro-ruby
lib/gocardless_pro/client.rb
GoCardlessPro.Client.custom_options
def custom_options(options) return default_options if options.nil? return default_options.merge(options) unless options[:default_headers] opts = default_options.merge(options) opts[:default_headers] = default_options[:default_headers].merge(options[:default_headers]) opts end
ruby
def custom_options(options) return default_options if options.nil? return default_options.merge(options) unless options[:default_headers] opts = default_options.merge(options) opts[:default_headers] = default_options[:default_headers].merge(options[:default_headers]) opts end
[ "def", "custom_options", "(", "options", ")", "return", "default_options", "if", "options", ".", "nil?", "return", "default_options", ".", "merge", "(", "options", ")", "unless", "options", "[", ":default_headers", "]", "opts", "=", "default_options", ".", "merge", "(", "options", ")", "opts", "[", ":default_headers", "]", "=", "default_options", "[", ":default_headers", "]", ".", "merge", "(", "options", "[", ":default_headers", "]", ")", "opts", "end" ]
Get customized options.
[ "Get", "customized", "options", "." ]
9473ecfa64eef2de6d5a404357c0db90de57efb1
https://github.com/gocardless/gocardless-pro-ruby/blob/9473ecfa64eef2de6d5a404357c0db90de57efb1/lib/gocardless_pro/client.rb#L122-L131
17,006
ericqweinstein/ruumba
lib/ruumba/parser.rb
Ruumba.Parser.extract
def extract(contents) file_text, matches = parse(contents) extracted_ruby = +'' last_match = [0, 0] matches.each do |start_index, end_index| handle_region_before(start_index, last_match.last, file_text, extracted_ruby) extracted_ruby << extract_match(file_text, start_index, end_index) last_match = [start_index, end_index] end extracted_ruby << file_text[last_match.last..-1].gsub(/./, ' ') extracted_ruby.gsub!(/[^\S\r\n]+$/, '') # if we replaced <%== with <%= raw, try to shift the columns back to the # left so they match the original again extracted_ruby.gsub!(/ raw/, 'raw') extracted_ruby end
ruby
def extract(contents) file_text, matches = parse(contents) extracted_ruby = +'' last_match = [0, 0] matches.each do |start_index, end_index| handle_region_before(start_index, last_match.last, file_text, extracted_ruby) extracted_ruby << extract_match(file_text, start_index, end_index) last_match = [start_index, end_index] end extracted_ruby << file_text[last_match.last..-1].gsub(/./, ' ') extracted_ruby.gsub!(/[^\S\r\n]+$/, '') # if we replaced <%== with <%= raw, try to shift the columns back to the # left so they match the original again extracted_ruby.gsub!(/ raw/, 'raw') extracted_ruby end
[ "def", "extract", "(", "contents", ")", "file_text", ",", "matches", "=", "parse", "(", "contents", ")", "extracted_ruby", "=", "+", "''", "last_match", "=", "[", "0", ",", "0", "]", "matches", ".", "each", "do", "|", "start_index", ",", "end_index", "|", "handle_region_before", "(", "start_index", ",", "last_match", ".", "last", ",", "file_text", ",", "extracted_ruby", ")", "extracted_ruby", "<<", "extract_match", "(", "file_text", ",", "start_index", ",", "end_index", ")", "last_match", "=", "[", "start_index", ",", "end_index", "]", "end", "extracted_ruby", "<<", "file_text", "[", "last_match", ".", "last", "..", "-", "1", "]", ".", "gsub", "(", "/", "/", ",", "' '", ")", "extracted_ruby", ".", "gsub!", "(", "/", "\\S", "\\r", "\\n", "/", ",", "''", ")", "# if we replaced <%== with <%= raw, try to shift the columns back to the", "# left so they match the original again", "extracted_ruby", ".", "gsub!", "(", "/", "/", ",", "'raw'", ")", "extracted_ruby", "end" ]
Extracts Ruby code from an ERB template. @return [String] The extracted ruby code
[ "Extracts", "Ruby", "code", "from", "an", "ERB", "template", "." ]
9093819d011a2d9f6824d8f4c3789e34f4ff9b98
https://github.com/ericqweinstein/ruumba/blob/9093819d011a2d9f6824d8f4c3789e34f4ff9b98/lib/ruumba/parser.rb#L13-L35
17,007
ericqweinstein/ruumba
lib/ruumba/rake_task.rb
Ruumba.RakeTask.run
def run # Like RuboCop itself, we'll lazy load so the task # doesn't substantially impact Rakefile load time. require 'ruumba' analyzer = Ruumba::Analyzer.new(@options) puts 'Running Ruumba...' exit(analyzer.run(@dir)) end
ruby
def run # Like RuboCop itself, we'll lazy load so the task # doesn't substantially impact Rakefile load time. require 'ruumba' analyzer = Ruumba::Analyzer.new(@options) puts 'Running Ruumba...' exit(analyzer.run(@dir)) end
[ "def", "run", "# Like RuboCop itself, we'll lazy load so the task", "# doesn't substantially impact Rakefile load time.", "require", "'ruumba'", "analyzer", "=", "Ruumba", "::", "Analyzer", ".", "new", "(", "@options", ")", "puts", "'Running Ruumba...'", "exit", "(", "analyzer", ".", "run", "(", "@dir", ")", ")", "end" ]
Executes the custom Rake task. @private
[ "Executes", "the", "custom", "Rake", "task", "." ]
9093819d011a2d9f6824d8f4c3789e34f4ff9b98
https://github.com/ericqweinstein/ruumba/blob/9093819d011a2d9f6824d8f4c3789e34f4ff9b98/lib/ruumba/rake_task.rb#L31-L40
17,008
ericqweinstein/ruumba
lib/ruumba/analyzer.rb
Ruumba.Analyzer.run
def run(files_or_dirs = ARGV) if options[:tmp_folder] analyze(File.expand_path(options[:tmp_folder]), files_or_dirs) else Dir.mktmpdir do |dir| analyze(dir, files_or_dirs) end end end
ruby
def run(files_or_dirs = ARGV) if options[:tmp_folder] analyze(File.expand_path(options[:tmp_folder]), files_or_dirs) else Dir.mktmpdir do |dir| analyze(dir, files_or_dirs) end end end
[ "def", "run", "(", "files_or_dirs", "=", "ARGV", ")", "if", "options", "[", ":tmp_folder", "]", "analyze", "(", "File", ".", "expand_path", "(", "options", "[", ":tmp_folder", "]", ")", ",", "files_or_dirs", ")", "else", "Dir", ".", "mktmpdir", "do", "|", "dir", "|", "analyze", "(", "dir", ",", "files_or_dirs", ")", "end", "end", "end" ]
Performs static analysis on the provided directory. @param [Array<String>] dir The directories / files to analyze.
[ "Performs", "static", "analysis", "on", "the", "provided", "directory", "." ]
9093819d011a2d9f6824d8f4c3789e34f4ff9b98
https://github.com/ericqweinstein/ruumba/blob/9093819d011a2d9f6824d8f4c3789e34f4ff9b98/lib/ruumba/analyzer.rb#L24-L32
17,009
mattbrictson/chandler
lib/chandler/logger.rb
Chandler.Logger.error
def error(message) message = message.red unless message.color? puts(stderr, message) end
ruby
def error(message) message = message.red unless message.color? puts(stderr, message) end
[ "def", "error", "(", "message", ")", "message", "=", "message", ".", "red", "unless", "message", ".", "color?", "puts", "(", "stderr", ",", "message", ")", "end" ]
Logs a message to stderr. Unless otherwise specified, the message will be printed in red.
[ "Logs", "a", "message", "to", "stderr", ".", "Unless", "otherwise", "specified", "the", "message", "will", "be", "printed", "in", "red", "." ]
bb6d38ea19aa8d7a8f175384ac53f2dd1ffc620a
https://github.com/mattbrictson/chandler/blob/bb6d38ea19aa8d7a8f175384ac53f2dd1ffc620a/lib/chandler/logger.rb#L19-L22
17,010
Vantiv/litle-sdk-for-ruby
lib/LitleTransaction.rb
LitleOnline.LitleTransaction.giftCardAuth_reversal
def giftCardAuth_reversal(options) transaction = GiftCardAuthReversal.new transaction.litleTxnId = options['litleTxnId'] transaction.card = GiftCardCardType.from_hash(options,'card') transaction.originalRefCode = options['originalRefCode'] transaction.originalAmount = options['originalAmount'] transaction.originalTxnTime = options['originalTxnTime'] transaction.originalSystemTraceId = options['originalSystemTraceId'] transaction.originalSequenceNumber = options['originalSequenceNumber'] return transaction end
ruby
def giftCardAuth_reversal(options) transaction = GiftCardAuthReversal.new transaction.litleTxnId = options['litleTxnId'] transaction.card = GiftCardCardType.from_hash(options,'card') transaction.originalRefCode = options['originalRefCode'] transaction.originalAmount = options['originalAmount'] transaction.originalTxnTime = options['originalTxnTime'] transaction.originalSystemTraceId = options['originalSystemTraceId'] transaction.originalSequenceNumber = options['originalSequenceNumber'] return transaction end
[ "def", "giftCardAuth_reversal", "(", "options", ")", "transaction", "=", "GiftCardAuthReversal", ".", "new", "transaction", ".", "litleTxnId", "=", "options", "[", "'litleTxnId'", "]", "transaction", ".", "card", "=", "GiftCardCardType", ".", "from_hash", "(", "options", ",", "'card'", ")", "transaction", ".", "originalRefCode", "=", "options", "[", "'originalRefCode'", "]", "transaction", ".", "originalAmount", "=", "options", "[", "'originalAmount'", "]", "transaction", ".", "originalTxnTime", "=", "options", "[", "'originalTxnTime'", "]", "transaction", ".", "originalSystemTraceId", "=", "options", "[", "'originalSystemTraceId'", "]", "transaction", ".", "originalSequenceNumber", "=", "options", "[", "'originalSequenceNumber'", "]", "return", "transaction", "end" ]
XML 11.0
[ "XML", "11", ".", "0" ]
a05590c5cbab688e6ae29cf38fea0eb44aa487e2
https://github.com/Vantiv/litle-sdk-for-ruby/blob/a05590c5cbab688e6ae29cf38fea0eb44aa487e2/lib/LitleTransaction.rb#L185-L195
17,011
Vantiv/litle-sdk-for-ruby
lib/LitleTransaction.rb
LitleOnline.LitleTransaction.fast_access_funding
def fast_access_funding(options) transaction = FastAccessFunding.new transaction.reportGroup = get_report_group(options) transaction.transactionId = options['id'] transaction.customerId = options['customerId'] transaction.fundingSubmerchantId = options['fundingSubmerchantId'] transaction.submerchantName = options['submerchantName'] transaction.fundsTransferId = options['fundsTransferId'] transaction.amount = options['amount'] transaction.card = Card.from_hash(options) transaction.token = CardToken.from_hash(options,'token') transaction.paypage = CardPaypage.from_hash(options,'paypage') return transaction end
ruby
def fast_access_funding(options) transaction = FastAccessFunding.new transaction.reportGroup = get_report_group(options) transaction.transactionId = options['id'] transaction.customerId = options['customerId'] transaction.fundingSubmerchantId = options['fundingSubmerchantId'] transaction.submerchantName = options['submerchantName'] transaction.fundsTransferId = options['fundsTransferId'] transaction.amount = options['amount'] transaction.card = Card.from_hash(options) transaction.token = CardToken.from_hash(options,'token') transaction.paypage = CardPaypage.from_hash(options,'paypage') return transaction end
[ "def", "fast_access_funding", "(", "options", ")", "transaction", "=", "FastAccessFunding", ".", "new", "transaction", ".", "reportGroup", "=", "get_report_group", "(", "options", ")", "transaction", ".", "transactionId", "=", "options", "[", "'id'", "]", "transaction", ".", "customerId", "=", "options", "[", "'customerId'", "]", "transaction", ".", "fundingSubmerchantId", "=", "options", "[", "'fundingSubmerchantId'", "]", "transaction", ".", "submerchantName", "=", "options", "[", "'submerchantName'", "]", "transaction", ".", "fundsTransferId", "=", "options", "[", "'fundsTransferId'", "]", "transaction", ".", "amount", "=", "options", "[", "'amount'", "]", "transaction", ".", "card", "=", "Card", ".", "from_hash", "(", "options", ")", "transaction", ".", "token", "=", "CardToken", ".", "from_hash", "(", "options", ",", "'token'", ")", "transaction", ".", "paypage", "=", "CardPaypage", ".", "from_hash", "(", "options", ",", "'paypage'", ")", "return", "transaction", "end" ]
11.4 Begin
[ "11", ".", "4", "Begin" ]
a05590c5cbab688e6ae29cf38fea0eb44aa487e2
https://github.com/Vantiv/litle-sdk-for-ruby/blob/a05590c5cbab688e6ae29cf38fea0eb44aa487e2/lib/LitleTransaction.rb#L659-L675
17,012
Vantiv/litle-sdk-for-ruby
lib/LitleRequest.rb
LitleOnline.LitleRequest.finish_request
def finish_request File.open(@path_to_request, 'w') do |f| #jam dat header in there f.puts(build_request_header()) #read into the request file from the batches file File.foreach(@path_to_batches) do |li| f.puts li end #finally, let's poot in a header, for old time's sake f.puts '</litleRequest>' end #rename the requests file File.rename(@path_to_request, @path_to_request + COMPLETE_FILE_SUFFIX) #we don't need the master batch file anymore File.delete(@path_to_batches) end
ruby
def finish_request File.open(@path_to_request, 'w') do |f| #jam dat header in there f.puts(build_request_header()) #read into the request file from the batches file File.foreach(@path_to_batches) do |li| f.puts li end #finally, let's poot in a header, for old time's sake f.puts '</litleRequest>' end #rename the requests file File.rename(@path_to_request, @path_to_request + COMPLETE_FILE_SUFFIX) #we don't need the master batch file anymore File.delete(@path_to_batches) end
[ "def", "finish_request", "File", ".", "open", "(", "@path_to_request", ",", "'w'", ")", "do", "|", "f", "|", "#jam dat header in there", "f", ".", "puts", "(", "build_request_header", "(", ")", ")", "#read into the request file from the batches file", "File", ".", "foreach", "(", "@path_to_batches", ")", "do", "|", "li", "|", "f", ".", "puts", "li", "end", "#finally, let's poot in a header, for old time's sake", "f", ".", "puts", "'</litleRequest>'", "end", "#rename the requests file", "File", ".", "rename", "(", "@path_to_request", ",", "@path_to_request", "+", "COMPLETE_FILE_SUFFIX", ")", "#we don't need the master batch file anymore", "File", ".", "delete", "(", "@path_to_batches", ")", "end" ]
Called when you wish to finish adding batches to your request, this method rewrites the aggregate batch file to the final LitleRequest xml doc with the appropos LitleRequest tags.
[ "Called", "when", "you", "wish", "to", "finish", "adding", "batches", "to", "your", "request", "this", "method", "rewrites", "the", "aggregate", "batch", "file", "to", "the", "final", "LitleRequest", "xml", "doc", "with", "the", "appropos", "LitleRequest", "tags", "." ]
a05590c5cbab688e6ae29cf38fea0eb44aa487e2
https://github.com/Vantiv/litle-sdk-for-ruby/blob/a05590c5cbab688e6ae29cf38fea0eb44aa487e2/lib/LitleRequest.rb#L440-L457
17,013
duckinator/inq
lib/inq/cli.rb
Inq.CLI.parse
def parse(argv) parser, options = parse_main(argv) # Options that are mutually-exclusive with everything else. options = {:help => true} if options[:help] options = {:version => true} if options[:version] validate_options!(options) @options = options @help_text = parser.to_s self end
ruby
def parse(argv) parser, options = parse_main(argv) # Options that are mutually-exclusive with everything else. options = {:help => true} if options[:help] options = {:version => true} if options[:version] validate_options!(options) @options = options @help_text = parser.to_s self end
[ "def", "parse", "(", "argv", ")", "parser", ",", "options", "=", "parse_main", "(", "argv", ")", "# Options that are mutually-exclusive with everything else.", "options", "=", "{", ":help", "=>", "true", "}", "if", "options", "[", ":help", "]", "options", "=", "{", ":version", "=>", "true", "}", "if", "options", "[", ":version", "]", "validate_options!", "(", "options", ")", "@options", "=", "options", "@help_text", "=", "parser", ".", "to_s", "self", "end" ]
Parses an Array of command-line arguments into an equivalent Hash. The results of this can be used to control the behavior of the rest of the library. @params argv [Array] An array of command-line arguments, e.g. +ARGV+. @return [Hash] A Hash containing data used to control Inq's behavior.
[ "Parses", "an", "Array", "of", "command", "-", "line", "arguments", "into", "an", "equivalent", "Hash", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/cli.rb#L34-L47
17,014
duckinator/inq
lib/inq/config.rb
Inq.Config.load_site_configs
def load_site_configs(*files) # Allows both: # load_site_configs('foo', 'bar') # load_site_configs(['foo', bar']) # but not: # load_site_configs(['foo'], 'bar') files = files[0] if files.length == 1 && files[0].is_a?(Array) load_files(*files) end
ruby
def load_site_configs(*files) # Allows both: # load_site_configs('foo', 'bar') # load_site_configs(['foo', bar']) # but not: # load_site_configs(['foo'], 'bar') files = files[0] if files.length == 1 && files[0].is_a?(Array) load_files(*files) end
[ "def", "load_site_configs", "(", "*", "files", ")", "# Allows both:", "# load_site_configs('foo', 'bar')", "# load_site_configs(['foo', bar'])", "# but not:", "# load_site_configs(['foo'], 'bar')", "files", "=", "files", "[", "0", "]", "if", "files", ".", "length", "==", "1", "&&", "files", "[", "0", "]", ".", "is_a?", "(", "Array", ")", "load_files", "(", "files", ")", "end" ]
Load the config files as specified via +files+. @param files [Array<String>] The path(s) for config files. @return [Config] The config hash. (+self+)
[ "Load", "the", "config", "files", "as", "specified", "via", "+", "files", "+", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/config.rb#L47-L56
17,015
duckinator/inq
lib/inq/config.rb
Inq.Config.load
def load(*configs) configs.each do |config| config.each do |k, v| if self[k] && self[k].is_a?(Array) self[k] += v else self[k] = v end end end self end
ruby
def load(*configs) configs.each do |config| config.each do |k, v| if self[k] && self[k].is_a?(Array) self[k] += v else self[k] = v end end end self end
[ "def", "load", "(", "*", "configs", ")", "configs", ".", "each", "do", "|", "config", "|", "config", ".", "each", "do", "|", "k", ",", "v", "|", "if", "self", "[", "k", "]", "&&", "self", "[", "k", "]", ".", "is_a?", "(", "Array", ")", "self", "[", "k", "]", "+=", "v", "else", "self", "[", "k", "]", "=", "v", "end", "end", "end", "self", "end" ]
Take a collection of config hashes and cascade them, meaning values in later ones override values in earlier ones. E.g., this results in +{'a'=>'x', 'c'=>'d'}+: load({'a'=>'b'}, {'c'=>'d'}, {'a'=>'x'}) And this results in +{'a'=>['b', 'c']}+: load({'a'=>['b']}, {'a'=>['c']}) @param [Array<Hash>] The configuration hashes. @return [Config] The final configuration value.
[ "Take", "a", "collection", "of", "config", "hashes", "and", "cascade", "them", "meaning", "values", "in", "later", "ones", "override", "values", "in", "earlier", "ones", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/config.rb#L83-L95
17,016
duckinator/inq
lib/inq/config.rb
Inq.Config.load_env
def load_env Inq::Text.puts "Using configuration from environment variables." gh_token = ENV["INQ_GITHUB_TOKEN"] || ENV["HOWIS_GITHUB_TOKEN"] gh_username = ENV["INQ_GITHUB_USERNAME"] || ENV["HOWIS_GITHUB_USERNAME"] raise "INQ_GITHUB_TOKEN environment variable is not set" \ unless gh_token raise "INQ_GITHUB_USERNAME environment variable is not set" \ unless gh_username load({ "sources/github" => { "username" => gh_username, "token" => gh_token, }, }) end
ruby
def load_env Inq::Text.puts "Using configuration from environment variables." gh_token = ENV["INQ_GITHUB_TOKEN"] || ENV["HOWIS_GITHUB_TOKEN"] gh_username = ENV["INQ_GITHUB_USERNAME"] || ENV["HOWIS_GITHUB_USERNAME"] raise "INQ_GITHUB_TOKEN environment variable is not set" \ unless gh_token raise "INQ_GITHUB_USERNAME environment variable is not set" \ unless gh_username load({ "sources/github" => { "username" => gh_username, "token" => gh_token, }, }) end
[ "def", "load_env", "Inq", "::", "Text", ".", "puts", "\"Using configuration from environment variables.\"", "gh_token", "=", "ENV", "[", "\"INQ_GITHUB_TOKEN\"", "]", "||", "ENV", "[", "\"HOWIS_GITHUB_TOKEN\"", "]", "gh_username", "=", "ENV", "[", "\"INQ_GITHUB_USERNAME\"", "]", "||", "ENV", "[", "\"HOWIS_GITHUB_USERNAME\"", "]", "raise", "\"INQ_GITHUB_TOKEN environment variable is not set\"", "unless", "gh_token", "raise", "\"INQ_GITHUB_USERNAME environment variable is not set\"", "unless", "gh_username", "load", "(", "{", "\"sources/github\"", "=>", "{", "\"username\"", "=>", "gh_username", ",", "\"token\"", "=>", "gh_token", ",", "}", ",", "}", ")", "end" ]
Load config info from environment variables. Supported environment variables: - INQ_GITHUB_TOKEN: a GitHub authentication token. - INQ_GITHUB_USERNAME: the GitHub username corresponding to the token. @return [Config] The resulting configuration.
[ "Load", "config", "info", "from", "environment", "variables", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/config.rb#L104-L121
17,017
duckinator/inq
lib/inq/date_time_helpers.rb
Inq.DateTimeHelpers.date_le
def date_le(left, right) left = str_to_dt(left) right = str_to_dt(right) left <= right end
ruby
def date_le(left, right) left = str_to_dt(left) right = str_to_dt(right) left <= right end
[ "def", "date_le", "(", "left", ",", "right", ")", "left", "=", "str_to_dt", "(", "left", ")", "right", "=", "str_to_dt", "(", "right", ")", "left", "<=", "right", "end" ]
Check if +left+ is less than or equal to +right+, where both are string representations of a date. @param left [String] A string representation of a date. @param right [String] A string representation of a date. @return [Boolean] True if +left+ is less-than-or-equal to +right+, otherwise false.
[ "Check", "if", "+", "left", "+", "is", "less", "than", "or", "equal", "to", "+", "right", "+", "where", "both", "are", "string", "representations", "of", "a", "date", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/date_time_helpers.rb#L17-L22
17,018
duckinator/inq
lib/inq/date_time_helpers.rb
Inq.DateTimeHelpers.date_ge
def date_ge(left, right) left = str_to_dt(left) right = str_to_dt(right) left >= right end
ruby
def date_ge(left, right) left = str_to_dt(left) right = str_to_dt(right) left >= right end
[ "def", "date_ge", "(", "left", ",", "right", ")", "left", "=", "str_to_dt", "(", "left", ")", "right", "=", "str_to_dt", "(", "right", ")", "left", ">=", "right", "end" ]
Check if +left+ is greater than or equal to +right+, where both are string representations of a date. @param left [String] A string representation of a date. @param right [String] A string representation of a date. @return [Boolean] True if +left+ is greater-than-or-equal to +right+, otherwise false.
[ "Check", "if", "+", "left", "+", "is", "greater", "than", "or", "equal", "to", "+", "right", "+", "where", "both", "are", "string", "representations", "of", "a", "date", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/date_time_helpers.rb#L31-L36
17,019
duckinator/inq
lib/inq/report_collection.rb
Inq.ReportCollection.metadata
def metadata(repository) end_date = DateTime.strptime(@date, "%Y-%m-%d") friendly_end_date = end_date.strftime("%B %d, %y") { sanitized_repository: repository.tr("/", "-"), repository: repository, date: end_date, friendly_date: friendly_end_date, } end
ruby
def metadata(repository) end_date = DateTime.strptime(@date, "%Y-%m-%d") friendly_end_date = end_date.strftime("%B %d, %y") { sanitized_repository: repository.tr("/", "-"), repository: repository, date: end_date, friendly_date: friendly_end_date, } end
[ "def", "metadata", "(", "repository", ")", "end_date", "=", "DateTime", ".", "strptime", "(", "@date", ",", "\"%Y-%m-%d\"", ")", "friendly_end_date", "=", "end_date", ".", "strftime", "(", "\"%B %d, %y\"", ")", "{", "sanitized_repository", ":", "repository", ".", "tr", "(", "\"/\"", ",", "\"-\"", ")", ",", "repository", ":", "repository", ",", "date", ":", "end_date", ",", "friendly_date", ":", "friendly_end_date", ",", "}", "end" ]
Generates the metadata for the collection of Reports.
[ "Generates", "the", "metadata", "for", "the", "collection", "of", "Reports", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/report_collection.rb#L28-L38
17,020
duckinator/inq
lib/inq/report_collection.rb
Inq.ReportCollection.to_h
def to_h results = {} defaults = @config["default_reports"] || {} @config["repositories"].map { |repo_config| repo = repo_config["repository"] config = config_for(repo) config["reports"].map { |format, report_config| # Sometimes report_data has unused keys, which generates a warning, but # we're okay with it, so we wrap it with silence_warnings {}. filename = silence_warnings { tmp_filename = report_config["filename"] || defaults[format]["filename"] tmp_filename % metadata(repo) } directory = report_config["directory"] || defaults[format]["directory"] file = File.join(directory, filename) # Export +report+ to the specified +format+ with the specified # +frontmatter+. frontmatter = report_config["frontmatter"] || {} if defaults.has_key?(format) && defaults[format].has_key?("frontmatter") frontmatter = defaults[format]["frontmatter"].merge(frontmatter) end frontmatter = nil if frontmatter == {} export = @reports[repo].send("to_#{format}", frontmatter) results[file] = export } } results end
ruby
def to_h results = {} defaults = @config["default_reports"] || {} @config["repositories"].map { |repo_config| repo = repo_config["repository"] config = config_for(repo) config["reports"].map { |format, report_config| # Sometimes report_data has unused keys, which generates a warning, but # we're okay with it, so we wrap it with silence_warnings {}. filename = silence_warnings { tmp_filename = report_config["filename"] || defaults[format]["filename"] tmp_filename % metadata(repo) } directory = report_config["directory"] || defaults[format]["directory"] file = File.join(directory, filename) # Export +report+ to the specified +format+ with the specified # +frontmatter+. frontmatter = report_config["frontmatter"] || {} if defaults.has_key?(format) && defaults[format].has_key?("frontmatter") frontmatter = defaults[format]["frontmatter"].merge(frontmatter) end frontmatter = nil if frontmatter == {} export = @reports[repo].send("to_#{format}", frontmatter) results[file] = export } } results end
[ "def", "to_h", "results", "=", "{", "}", "defaults", "=", "@config", "[", "\"default_reports\"", "]", "||", "{", "}", "@config", "[", "\"repositories\"", "]", ".", "map", "{", "|", "repo_config", "|", "repo", "=", "repo_config", "[", "\"repository\"", "]", "config", "=", "config_for", "(", "repo", ")", "config", "[", "\"reports\"", "]", ".", "map", "{", "|", "format", ",", "report_config", "|", "# Sometimes report_data has unused keys, which generates a warning, but", "# we're okay with it, so we wrap it with silence_warnings {}.", "filename", "=", "silence_warnings", "{", "tmp_filename", "=", "report_config", "[", "\"filename\"", "]", "||", "defaults", "[", "format", "]", "[", "\"filename\"", "]", "tmp_filename", "%", "metadata", "(", "repo", ")", "}", "directory", "=", "report_config", "[", "\"directory\"", "]", "||", "defaults", "[", "format", "]", "[", "\"directory\"", "]", "file", "=", "File", ".", "join", "(", "directory", ",", "filename", ")", "# Export +report+ to the specified +format+ with the specified", "# +frontmatter+.", "frontmatter", "=", "report_config", "[", "\"frontmatter\"", "]", "||", "{", "}", "if", "defaults", ".", "has_key?", "(", "format", ")", "&&", "defaults", "[", "format", "]", ".", "has_key?", "(", "\"frontmatter\"", ")", "frontmatter", "=", "defaults", "[", "format", "]", "[", "\"frontmatter\"", "]", ".", "merge", "(", "frontmatter", ")", "end", "frontmatter", "=", "nil", "if", "frontmatter", "==", "{", "}", "export", "=", "@reports", "[", "repo", "]", ".", "send", "(", "\"to_#{format}\"", ",", "frontmatter", ")", "results", "[", "file", "]", "=", "export", "}", "}", "results", "end" ]
Converts a ReportCollection to a Hash. Also good for giving programmers nightmares, I suspect.
[ "Converts", "a", "ReportCollection", "to", "a", "Hash", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/report_collection.rb#L66-L99
17,021
duckinator/inq
lib/inq/report_collection.rb
Inq.ReportCollection.save_all
def save_all reports = to_h reports.each do |file, report| File.write(file, report) end reports.keys end
ruby
def save_all reports = to_h reports.each do |file, report| File.write(file, report) end reports.keys end
[ "def", "save_all", "reports", "=", "to_h", "reports", ".", "each", "do", "|", "file", ",", "report", "|", "File", ".", "write", "(", "file", ",", "report", ")", "end", "reports", ".", "keys", "end" ]
Save all of the reports to the corresponding files. @return [Array<String>] An array of file paths.
[ "Save", "all", "of", "the", "reports", "to", "the", "corresponding", "files", "." ]
e23a250aca4a62702cb5f3ee87cf26012e5a8344
https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/report_collection.rb#L104-L111
17,022
rails/sprockets-rails
lib/sprockets/railtie.rb
Rails.Application.asset_precompiled?
def asset_precompiled?(logical_path) if precompiled_assets.include?(logical_path) true elsif !config.cache_classes # Check to see if precompile list has been updated precompiled_assets(true).include?(logical_path) else false end end
ruby
def asset_precompiled?(logical_path) if precompiled_assets.include?(logical_path) true elsif !config.cache_classes # Check to see if precompile list has been updated precompiled_assets(true).include?(logical_path) else false end end
[ "def", "asset_precompiled?", "(", "logical_path", ")", "if", "precompiled_assets", ".", "include?", "(", "logical_path", ")", "true", "elsif", "!", "config", ".", "cache_classes", "# Check to see if precompile list has been updated", "precompiled_assets", "(", "true", ")", ".", "include?", "(", "logical_path", ")", "else", "false", "end", "end" ]
Called from asset helpers to alert you if you reference an asset URL that isn't precompiled and hence won't be available in production.
[ "Called", "from", "asset", "helpers", "to", "alert", "you", "if", "you", "reference", "an", "asset", "URL", "that", "isn", "t", "precompiled", "and", "hence", "won", "t", "be", "available", "in", "production", "." ]
bbfcefda3240d924260e3530f896be94cdf23034
https://github.com/rails/sprockets-rails/blob/bbfcefda3240d924260e3530f896be94cdf23034/lib/sprockets/railtie.rb#L34-L43
17,023
rails/sprockets-rails
lib/sprockets/railtie.rb
Rails.Application.precompiled_assets
def precompiled_assets(clear_cache = false) @precompiled_assets = nil if clear_cache @precompiled_assets ||= assets_manifest.find(config.assets.precompile).map(&:logical_path).to_set end
ruby
def precompiled_assets(clear_cache = false) @precompiled_assets = nil if clear_cache @precompiled_assets ||= assets_manifest.find(config.assets.precompile).map(&:logical_path).to_set end
[ "def", "precompiled_assets", "(", "clear_cache", "=", "false", ")", "@precompiled_assets", "=", "nil", "if", "clear_cache", "@precompiled_assets", "||=", "assets_manifest", ".", "find", "(", "config", ".", "assets", ".", "precompile", ")", ".", "map", "(", ":logical_path", ")", ".", "to_set", "end" ]
Lazy-load the precompile list so we don't cause asset compilation at app boot time, but ensure we cache the list so we don't recompute it for each request or test case.
[ "Lazy", "-", "load", "the", "precompile", "list", "so", "we", "don", "t", "cause", "asset", "compilation", "at", "app", "boot", "time", "but", "ensure", "we", "cache", "the", "list", "so", "we", "don", "t", "recompute", "it", "for", "each", "request", "or", "test", "case", "." ]
bbfcefda3240d924260e3530f896be94cdf23034
https://github.com/rails/sprockets-rails/blob/bbfcefda3240d924260e3530f896be94cdf23034/lib/sprockets/railtie.rb#L48-L51
17,024
guilleiguaran/fakeredis
lib/fakeredis/sorted_set_argument_handler.rb
FakeRedis.SortedSetArgumentHandler.handle
def handle(item) case item when "WEIGHTS" self.type = :weights self.weights = [] when "AGGREGATE" self.type = :aggregate when nil # This should never be called, raise a syntax error if we manage to hit it raise(Redis::CommandError, "ERR syntax error") else send "handle_#{type}", item end self end
ruby
def handle(item) case item when "WEIGHTS" self.type = :weights self.weights = [] when "AGGREGATE" self.type = :aggregate when nil # This should never be called, raise a syntax error if we manage to hit it raise(Redis::CommandError, "ERR syntax error") else send "handle_#{type}", item end self end
[ "def", "handle", "(", "item", ")", "case", "item", "when", "\"WEIGHTS\"", "self", ".", "type", "=", ":weights", "self", ".", "weights", "=", "[", "]", "when", "\"AGGREGATE\"", "self", ".", "type", "=", ":aggregate", "when", "nil", "# This should never be called, raise a syntax error if we manage to hit it", "raise", "(", "Redis", "::", "CommandError", ",", "\"ERR syntax error\"", ")", "else", "send", "\"handle_#{type}\"", ",", "item", "end", "self", "end" ]
Decides how to handle an item, depending on where we are in the arguments
[ "Decides", "how", "to", "handle", "an", "item", "depending", "on", "where", "we", "are", "in", "the", "arguments" ]
df7b07f55e3b194ccb7208ed143711b2426d78c4
https://github.com/guilleiguaran/fakeredis/blob/df7b07f55e3b194ccb7208ed143711b2426d78c4/lib/fakeredis/sorted_set_argument_handler.rb#L46-L60
17,025
guilleiguaran/fakeredis
lib/fakeredis/sorted_set_store.rb
FakeRedis.SortedSetStore.computed_values
def computed_values unless defined?(@computed_values) && @computed_values # Do nothing if all weights are 1, as n * 1 is n @computed_values = hashes if weights.all? {|weight| weight == 1 } # Otherwise, multiply the values in each hash by that hash's weighting @computed_values ||= hashes.each_with_index.map do |hash, index| weight = weights[index] Hash[hash.map {|k, v| [k, (v * weight)]}] end end @computed_values end
ruby
def computed_values unless defined?(@computed_values) && @computed_values # Do nothing if all weights are 1, as n * 1 is n @computed_values = hashes if weights.all? {|weight| weight == 1 } # Otherwise, multiply the values in each hash by that hash's weighting @computed_values ||= hashes.each_with_index.map do |hash, index| weight = weights[index] Hash[hash.map {|k, v| [k, (v * weight)]}] end end @computed_values end
[ "def", "computed_values", "unless", "defined?", "(", "@computed_values", ")", "&&", "@computed_values", "# Do nothing if all weights are 1, as n * 1 is n", "@computed_values", "=", "hashes", "if", "weights", ".", "all?", "{", "|", "weight", "|", "weight", "==", "1", "}", "# Otherwise, multiply the values in each hash by that hash's weighting", "@computed_values", "||=", "hashes", ".", "each_with_index", ".", "map", "do", "|", "hash", ",", "index", "|", "weight", "=", "weights", "[", "index", "]", "Hash", "[", "hash", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ",", "(", "v", "*", "weight", ")", "]", "}", "]", "end", "end", "@computed_values", "end" ]
Apply the weightings to the hashes
[ "Apply", "the", "weightings", "to", "the", "hashes" ]
df7b07f55e3b194ccb7208ed143711b2426d78c4
https://github.com/guilleiguaran/fakeredis/blob/df7b07f55e3b194ccb7208ed143711b2426d78c4/lib/fakeredis/sorted_set_store.rb#L27-L38
17,026
guilleiguaran/fakeredis
lib/fakeredis/zset.rb
FakeRedis.ZSet._floatify
def _floatify(str, increment = true) if (( inf = str.to_s.match(/^([+-])?inf/i) )) (inf[1] == "-" ? -1.0 : 1.0) / 0.0 elsif (( number = str.to_s.match(/^\((\d+)/i) )) number[1].to_i + (increment ? 1 : -1) else Float str.to_s end rescue ArgumentError raise Redis::CommandError, "ERR value is not a valid float" end
ruby
def _floatify(str, increment = true) if (( inf = str.to_s.match(/^([+-])?inf/i) )) (inf[1] == "-" ? -1.0 : 1.0) / 0.0 elsif (( number = str.to_s.match(/^\((\d+)/i) )) number[1].to_i + (increment ? 1 : -1) else Float str.to_s end rescue ArgumentError raise Redis::CommandError, "ERR value is not a valid float" end
[ "def", "_floatify", "(", "str", ",", "increment", "=", "true", ")", "if", "(", "(", "inf", "=", "str", ".", "to_s", ".", "match", "(", "/", "/i", ")", ")", ")", "(", "inf", "[", "1", "]", "==", "\"-\"", "?", "-", "1.0", ":", "1.0", ")", "/", "0.0", "elsif", "(", "(", "number", "=", "str", ".", "to_s", ".", "match", "(", "/", "\\(", "\\d", "/i", ")", ")", ")", "number", "[", "1", "]", ".", "to_i", "+", "(", "increment", "?", "1", ":", "-", "1", ")", "else", "Float", "str", ".", "to_s", "end", "rescue", "ArgumentError", "raise", "Redis", "::", "CommandError", ",", "\"ERR value is not a valid float\"", "end" ]
Originally lifted from redis-rb
[ "Originally", "lifted", "from", "redis", "-", "rb" ]
df7b07f55e3b194ccb7208ed143711b2426d78c4
https://github.com/guilleiguaran/fakeredis/blob/df7b07f55e3b194ccb7208ed143711b2426d78c4/lib/fakeredis/zset.rb#L26-L36
17,027
cequel/cequel
lib/cequel/uuids.rb
Cequel.Uuids.uuid
def uuid(value = nil) if value.nil? timeuuid_generator.now elsif value.is_a?(Time) timeuuid_generator.at(value) elsif value.is_a?(DateTime) timeuuid_generator.at(Time.at(value.to_f)) else Type::Timeuuid.instance.cast(value) end end
ruby
def uuid(value = nil) if value.nil? timeuuid_generator.now elsif value.is_a?(Time) timeuuid_generator.at(value) elsif value.is_a?(DateTime) timeuuid_generator.at(Time.at(value.to_f)) else Type::Timeuuid.instance.cast(value) end end
[ "def", "uuid", "(", "value", "=", "nil", ")", "if", "value", ".", "nil?", "timeuuid_generator", ".", "now", "elsif", "value", ".", "is_a?", "(", "Time", ")", "timeuuid_generator", ".", "at", "(", "value", ")", "elsif", "value", ".", "is_a?", "(", "DateTime", ")", "timeuuid_generator", ".", "at", "(", "Time", ".", "at", "(", "value", ".", "to_f", ")", ")", "else", "Type", "::", "Timeuuid", ".", "instance", ".", "cast", "(", "value", ")", "end", "end" ]
Create a UUID @param value [Time,String,Integer] timestamp to assign to the UUID, or numeric or string representation of the UUID @return a UUID appropriate for use with Cequel
[ "Create", "a", "UUID" ]
35e90199470481795f0a6e1604767d65a0f2c604
https://github.com/cequel/cequel/blob/35e90199470481795f0a6e1604767d65a0f2c604/lib/cequel/uuids.rb#L18-L28
17,028
infused/dbf
lib/dbf/table.rb
DBF.Table.find
def find(command, options = {}, &block) case command when Integer record(command) when Array command.map { |i| record(i) } when :all find_all(options, &block) when :first find_first(options) end end
ruby
def find(command, options = {}, &block) case command when Integer record(command) when Array command.map { |i| record(i) } when :all find_all(options, &block) when :first find_first(options) end end
[ "def", "find", "(", "command", ",", "options", "=", "{", "}", ",", "&", "block", ")", "case", "command", "when", "Integer", "record", "(", "command", ")", "when", "Array", "command", ".", "map", "{", "|", "i", "|", "record", "(", "i", ")", "}", "when", ":all", "find_all", "(", "options", ",", "block", ")", "when", ":first", "find_first", "(", "options", ")", "end", "end" ]
Find records using a simple ActiveRecord-like syntax. Examples: table = DBF::Table.new 'mydata.dbf' # Find record number 5 table.find(5) # Find all records for Keith Morrison table.find :all, first_name: "Keith", last_name: "Morrison" # Find first record table.find :first, first_name: "Keith" The <b>command</b> may be a record index, :all, or :first. <b>options</b> is optional and, if specified, should be a hash where the keys correspond to column names in the database. The values will be matched exactly with the value in the database. If you specify more than one key, all values must match in order for the record to be returned. The equivalent SQL would be "WHERE key1 = 'value1' AND key2 = 'value2'". @param [Integer, Symbol] command @param [optional, Hash] options Hash of search parameters @yield [optional, DBF::Record, NilClass]
[ "Find", "records", "using", "a", "simple", "ActiveRecord", "-", "like", "syntax", "." ]
6f60cfe100e854057f112e84fd32656f0ed7f84b
https://github.com/infused/dbf/blob/6f60cfe100e854057f112e84fd32656f0ed7f84b/lib/dbf/table.rb#L148-L159
17,029
infused/dbf
lib/dbf/table.rb
DBF.Table.record
def record(index) seek_to_record(index) return nil if deleted_record? DBF::Record.new(@data.read(record_length), columns, version, @memo) end
ruby
def record(index) seek_to_record(index) return nil if deleted_record? DBF::Record.new(@data.read(record_length), columns, version, @memo) end
[ "def", "record", "(", "index", ")", "seek_to_record", "(", "index", ")", "return", "nil", "if", "deleted_record?", "DBF", "::", "Record", ".", "new", "(", "@data", ".", "read", "(", "record_length", ")", ",", "columns", ",", "version", ",", "@memo", ")", "end" ]
Retrieve a record by index number. The record will be nil if it has been deleted, but not yet pruned from the database. @param [Integer] index @return [DBF::Record, NilClass]
[ "Retrieve", "a", "record", "by", "index", "number", ".", "The", "record", "will", "be", "nil", "if", "it", "has", "been", "deleted", "but", "not", "yet", "pruned", "from", "the", "database", "." ]
6f60cfe100e854057f112e84fd32656f0ed7f84b
https://github.com/infused/dbf/blob/6f60cfe100e854057f112e84fd32656f0ed7f84b/lib/dbf/table.rb#L177-L182
17,030
infused/dbf
lib/dbf/table.rb
DBF.Table.to_csv
def to_csv(path = nil) out_io = path ? File.open(path, 'w') : $stdout csv = CSV.new(out_io, force_quotes: true) csv << column_names each { |record| csv << record.to_a } end
ruby
def to_csv(path = nil) out_io = path ? File.open(path, 'w') : $stdout csv = CSV.new(out_io, force_quotes: true) csv << column_names each { |record| csv << record.to_a } end
[ "def", "to_csv", "(", "path", "=", "nil", ")", "out_io", "=", "path", "?", "File", ".", "open", "(", "path", ",", "'w'", ")", ":", "$stdout", "csv", "=", "CSV", ".", "new", "(", "out_io", ",", "force_quotes", ":", "true", ")", "csv", "<<", "column_names", "each", "{", "|", "record", "|", "csv", "<<", "record", ".", "to_a", "}", "end" ]
Dumps all records to a CSV file. If no filename is given then CSV is output to STDOUT. @param [optional String] path Defaults to STDOUT
[ "Dumps", "all", "records", "to", "a", "CSV", "file", ".", "If", "no", "filename", "is", "given", "then", "CSV", "is", "output", "to", "STDOUT", "." ]
6f60cfe100e854057f112e84fd32656f0ed7f84b
https://github.com/infused/dbf/blob/6f60cfe100e854057f112e84fd32656f0ed7f84b/lib/dbf/table.rb#L190-L195
17,031
deliveroo/routemaster-drain
lib/routemaster/cache.rb
Routemaster.Cache.get
def get(url, version: nil, locale: nil) @client.get(url, headers: headers(version: version, locale: locale)) end
ruby
def get(url, version: nil, locale: nil) @client.get(url, headers: headers(version: version, locale: locale)) end
[ "def", "get", "(", "url", ",", "version", ":", "nil", ",", "locale", ":", "nil", ")", "@client", ".", "get", "(", "url", ",", "headers", ":", "headers", "(", "version", ":", "version", ",", "locale", ":", "locale", ")", ")", "end" ]
Get the response from a URL, from the cache if possible. Stores to the cache on misses. Different versions and locales are stored separately in the cache. @param version [Integer] The version to pass in headers, as `Accept: application/json;v=2` @param locale [String] The language to request in the `Accept-Language` header. @return [Response], which responds to `status`, `headers`, and `body`.
[ "Get", "the", "response", "from", "a", "URL", "from", "the", "cache", "if", "possible", ".", "Stores", "to", "the", "cache", "on", "misses", "." ]
e854e15538d672c06ea5e82d3fde8e243b8d54d5
https://github.com/deliveroo/routemaster-drain/blob/e854e15538d672c06ea5e82d3fde8e243b8d54d5/lib/routemaster/cache.rb#L51-L53
17,032
deliveroo/routemaster-drain
lib/routemaster/redis_broker.rb
Routemaster.RedisBroker.inject
def inject(clients={}) @_injected_clients = true clients.each_pair do |name, client| _close_if_present(@_connections[name]) @_connections[name] = Redis::Namespace.new(DEFAULT_NAMESPACE, redis: client) end end
ruby
def inject(clients={}) @_injected_clients = true clients.each_pair do |name, client| _close_if_present(@_connections[name]) @_connections[name] = Redis::Namespace.new(DEFAULT_NAMESPACE, redis: client) end end
[ "def", "inject", "(", "clients", "=", "{", "}", ")", "@_injected_clients", "=", "true", "clients", ".", "each_pair", "do", "|", "name", ",", "client", "|", "_close_if_present", "(", "@_connections", "[", "name", "]", ")", "@_connections", "[", "name", "]", "=", "Redis", "::", "Namespace", ".", "new", "(", "DEFAULT_NAMESPACE", ",", "redis", ":", "client", ")", "end", "end" ]
Allow to inject pre-built Redis clients Before storing a new connection, ensures that any previously set client is properly closed.
[ "Allow", "to", "inject", "pre", "-", "built", "Redis", "clients" ]
e854e15538d672c06ea5e82d3fde8e243b8d54d5
https://github.com/deliveroo/routemaster-drain/blob/e854e15538d672c06ea5e82d3fde8e243b8d54d5/lib/routemaster/redis_broker.rb#L35-L41
17,033
nevans/resque-pool
features/support/aruba_daemon_support.rb
Aruba.Api.keep_trying
def keep_trying(timeout=10, tries=0) puts "Try: #{tries}" if @announce_env yield rescue RSpec::Expectations::ExpectationNotMetError if tries < timeout sleep 1 tries += 1 retry else raise end end
ruby
def keep_trying(timeout=10, tries=0) puts "Try: #{tries}" if @announce_env yield rescue RSpec::Expectations::ExpectationNotMetError if tries < timeout sleep 1 tries += 1 retry else raise end end
[ "def", "keep_trying", "(", "timeout", "=", "10", ",", "tries", "=", "0", ")", "puts", "\"Try: #{tries}\"", "if", "@announce_env", "yield", "rescue", "RSpec", "::", "Expectations", "::", "ExpectationNotMetError", "if", "tries", "<", "timeout", "sleep", "1", "tries", "+=", "1", "retry", "else", "raise", "end", "end" ]
this is a horrible hack, to make sure that it's done what it needs to do before we do our next step
[ "this", "is", "a", "horrible", "hack", "to", "make", "sure", "that", "it", "s", "done", "what", "it", "needs", "to", "do", "before", "we", "do", "our", "next", "step" ]
62293e48eb75852aa3e0f5f726d158a8614e9259
https://github.com/nevans/resque-pool/blob/62293e48eb75852aa3e0f5f726d158a8614e9259/features/support/aruba_daemon_support.rb#L11-L22
17,034
rharriso/bower-rails
lib/bower-rails/performer.rb
BowerRails.Performer.perform_command
def perform_command(remove_components = true, &block) # Load in bower json file txt = File.read(File.join(root_path, "bower.json")) json = JSON.parse(txt) # Load and merge root .bowerrc dot_bowerrc = JSON.parse(File.read(File.join(root_path, '.bowerrc'))) rescue {} dot_bowerrc["directory"] = components_directory if json.reject{ |key| ['lib', 'vendor'].include? key }.empty? folders = json.keys else raise "Assuming a standard bower package but cannot find the required 'name' key" unless !!json['name'] folders = ['vendor'] end folders.each do |dir| data = json[dir] # Assume using standard bower.json if folder name is not found data = json if data.nil? # Check folder existence and create? dir = File.join(root_path, dir, "assets") FileUtils.mkdir_p dir unless File.directory? dir # Go in to dir to act Dir.chdir(dir) do # Remove old components FileUtils.rm_rf("#{components_directory}/*") if remove_components # Create bower.json File.open("bower.json", "w") do |f| f.write(data.to_json) end # Create .bowerrc File.open(".bowerrc", "w") do |f| f.write(JSON.pretty_generate(dot_bowerrc)) end # Run command yield if block_given? # Remove bower.json FileUtils.rm("bower.json") # Remove .bowerrc FileUtils.rm(".bowerrc") end if data && !data["dependencies"].empty? end end
ruby
def perform_command(remove_components = true, &block) # Load in bower json file txt = File.read(File.join(root_path, "bower.json")) json = JSON.parse(txt) # Load and merge root .bowerrc dot_bowerrc = JSON.parse(File.read(File.join(root_path, '.bowerrc'))) rescue {} dot_bowerrc["directory"] = components_directory if json.reject{ |key| ['lib', 'vendor'].include? key }.empty? folders = json.keys else raise "Assuming a standard bower package but cannot find the required 'name' key" unless !!json['name'] folders = ['vendor'] end folders.each do |dir| data = json[dir] # Assume using standard bower.json if folder name is not found data = json if data.nil? # Check folder existence and create? dir = File.join(root_path, dir, "assets") FileUtils.mkdir_p dir unless File.directory? dir # Go in to dir to act Dir.chdir(dir) do # Remove old components FileUtils.rm_rf("#{components_directory}/*") if remove_components # Create bower.json File.open("bower.json", "w") do |f| f.write(data.to_json) end # Create .bowerrc File.open(".bowerrc", "w") do |f| f.write(JSON.pretty_generate(dot_bowerrc)) end # Run command yield if block_given? # Remove bower.json FileUtils.rm("bower.json") # Remove .bowerrc FileUtils.rm(".bowerrc") end if data && !data["dependencies"].empty? end end
[ "def", "perform_command", "(", "remove_components", "=", "true", ",", "&", "block", ")", "# Load in bower json file", "txt", "=", "File", ".", "read", "(", "File", ".", "join", "(", "root_path", ",", "\"bower.json\"", ")", ")", "json", "=", "JSON", ".", "parse", "(", "txt", ")", "# Load and merge root .bowerrc", "dot_bowerrc", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "File", ".", "join", "(", "root_path", ",", "'.bowerrc'", ")", ")", ")", "rescue", "{", "}", "dot_bowerrc", "[", "\"directory\"", "]", "=", "components_directory", "if", "json", ".", "reject", "{", "|", "key", "|", "[", "'lib'", ",", "'vendor'", "]", ".", "include?", "key", "}", ".", "empty?", "folders", "=", "json", ".", "keys", "else", "raise", "\"Assuming a standard bower package but cannot find the required 'name' key\"", "unless", "!", "!", "json", "[", "'name'", "]", "folders", "=", "[", "'vendor'", "]", "end", "folders", ".", "each", "do", "|", "dir", "|", "data", "=", "json", "[", "dir", "]", "# Assume using standard bower.json if folder name is not found", "data", "=", "json", "if", "data", ".", "nil?", "# Check folder existence and create?", "dir", "=", "File", ".", "join", "(", "root_path", ",", "dir", ",", "\"assets\"", ")", "FileUtils", ".", "mkdir_p", "dir", "unless", "File", ".", "directory?", "dir", "# Go in to dir to act", "Dir", ".", "chdir", "(", "dir", ")", "do", "# Remove old components", "FileUtils", ".", "rm_rf", "(", "\"#{components_directory}/*\"", ")", "if", "remove_components", "# Create bower.json", "File", ".", "open", "(", "\"bower.json\"", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "data", ".", "to_json", ")", "end", "# Create .bowerrc", "File", ".", "open", "(", "\".bowerrc\"", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "JSON", ".", "pretty_generate", "(", "dot_bowerrc", ")", ")", "end", "# Run command", "yield", "if", "block_given?", "# Remove bower.json", "FileUtils", ".", "rm", "(", "\"bower.json\"", ")", "# Remove .bowerrc", "FileUtils", ".", "rm", "(", "\".bowerrc\"", ")", "end", "if", "data", "&&", "!", "data", "[", "\"dependencies\"", "]", ".", "empty?", "end", "end" ]
run the passed bower block in appropriate folders
[ "run", "the", "passed", "bower", "block", "in", "appropriate", "folders" ]
30c6697614149b996f8fb158290bb554990b247d
https://github.com/rharriso/bower-rails/blob/30c6697614149b996f8fb158290bb554990b247d/lib/bower-rails/performer.rb#L62-L114
17,035
drecom/activerecord-turntable
lib/active_record/turntable/connection_proxy.rb
ActiveRecord::Turntable.ConnectionProxy.with_shard
def with_shard(shard) shard = cluster.to_shard(shard) old_shard = current_shard old_fixed = fixed_shard self.current_shard = shard self.fixed_shard = shard yield ensure self.fixed_shard = old_fixed self.current_shard = old_shard end
ruby
def with_shard(shard) shard = cluster.to_shard(shard) old_shard = current_shard old_fixed = fixed_shard self.current_shard = shard self.fixed_shard = shard yield ensure self.fixed_shard = old_fixed self.current_shard = old_shard end
[ "def", "with_shard", "(", "shard", ")", "shard", "=", "cluster", ".", "to_shard", "(", "shard", ")", "old_shard", "=", "current_shard", "old_fixed", "=", "fixed_shard", "self", ".", "current_shard", "=", "shard", "self", ".", "fixed_shard", "=", "shard", "yield", "ensure", "self", ".", "fixed_shard", "=", "old_fixed", "self", ".", "current_shard", "=", "old_shard", "end" ]
Fix connection to given shard in block @param [ActiveRecord::Base, Symbol, ActiveRecord::Turntable::Shard, Numeric, String] shard which you want to fix @param shard [ActiveRecord::Base] AR Object @param shard [Symbol] shard name symbol that defined in turntable.yml @param shard [ActiveRecord::Turntable::Shard] Shard object @param shard [String, Numeric] Raw sharding id
[ "Fix", "connection", "to", "given", "shard", "in", "block" ]
7db85be222f8345c6ed14b97a242a1e1c392992e
https://github.com/drecom/activerecord-turntable/blob/7db85be222f8345c6ed14b97a242a1e1c392992e/lib/active_record/turntable/connection_proxy.rb#L159-L170
17,036
drecom/activerecord-turntable
lib/active_record/turntable/connection_proxy.rb
ActiveRecord::Turntable.ConnectionProxy.with_all
def with_all(continue_on_error = false) cluster.shards.map do |shard| begin with_shard(shard) { yield } rescue Exception => err unless continue_on_error raise err end err end end end
ruby
def with_all(continue_on_error = false) cluster.shards.map do |shard| begin with_shard(shard) { yield } rescue Exception => err unless continue_on_error raise err end err end end end
[ "def", "with_all", "(", "continue_on_error", "=", "false", ")", "cluster", ".", "shards", ".", "map", "do", "|", "shard", "|", "begin", "with_shard", "(", "shard", ")", "{", "yield", "}", "rescue", "Exception", "=>", "err", "unless", "continue_on_error", "raise", "err", "end", "err", "end", "end", "end" ]
Send queries to all shards in this cluster @param [Boolean] continue_on_error when a shard raises error, ignore exception and continue
[ "Send", "queries", "to", "all", "shards", "in", "this", "cluster" ]
7db85be222f8345c6ed14b97a242a1e1c392992e
https://github.com/drecom/activerecord-turntable/blob/7db85be222f8345c6ed14b97a242a1e1c392992e/lib/active_record/turntable/connection_proxy.rb#L201-L214
17,037
drecom/activerecord-turntable
lib/active_record/turntable/connection_proxy.rb
ActiveRecord::Turntable.ConnectionProxy.with_default_and_all
def with_default_and_all(continue_on_error = false) ([default_shard] + cluster.shards).map do |shard| begin with_shard(shard) { yield } rescue Exception => err unless continue_on_error raise err end err end end end
ruby
def with_default_and_all(continue_on_error = false) ([default_shard] + cluster.shards).map do |shard| begin with_shard(shard) { yield } rescue Exception => err unless continue_on_error raise err end err end end end
[ "def", "with_default_and_all", "(", "continue_on_error", "=", "false", ")", "(", "[", "default_shard", "]", "+", "cluster", ".", "shards", ")", ".", "map", "do", "|", "shard", "|", "begin", "with_shard", "(", "shard", ")", "{", "yield", "}", "rescue", "Exception", "=>", "err", "unless", "continue_on_error", "raise", "err", "end", "err", "end", "end", "end" ]
Send queries to default connection and all shards in this cluster @param [Boolean] continue_on_error when a shard raises error, ignore exception and continue
[ "Send", "queries", "to", "default", "connection", "and", "all", "shards", "in", "this", "cluster" ]
7db85be222f8345c6ed14b97a242a1e1c392992e
https://github.com/drecom/activerecord-turntable/blob/7db85be222f8345c6ed14b97a242a1e1c392992e/lib/active_record/turntable/connection_proxy.rb#L218-L231
17,038
toland/patron
lib/patron/response.rb
Patron.Response.parse_headers
def parse_headers(header_data_for_multiple_responses) @headers = {} responses = Patron::HeaderParser.parse(header_data_for_multiple_responses) last_response = responses[-1] # Only use the last response (for proxies and redirects) @status_line = last_response.status_line last_response.headers.each do |line| hdr, val = line.split(":", 2) val.strip! unless val.nil? if @headers.key?(hdr) @headers[hdr] = [@headers[hdr]] unless @headers[hdr].kind_of? Array @headers[hdr] << val else @headers[hdr] = val end end end
ruby
def parse_headers(header_data_for_multiple_responses) @headers = {} responses = Patron::HeaderParser.parse(header_data_for_multiple_responses) last_response = responses[-1] # Only use the last response (for proxies and redirects) @status_line = last_response.status_line last_response.headers.each do |line| hdr, val = line.split(":", 2) val.strip! unless val.nil? if @headers.key?(hdr) @headers[hdr] = [@headers[hdr]] unless @headers[hdr].kind_of? Array @headers[hdr] << val else @headers[hdr] = val end end end
[ "def", "parse_headers", "(", "header_data_for_multiple_responses", ")", "@headers", "=", "{", "}", "responses", "=", "Patron", "::", "HeaderParser", ".", "parse", "(", "header_data_for_multiple_responses", ")", "last_response", "=", "responses", "[", "-", "1", "]", "# Only use the last response (for proxies and redirects)", "@status_line", "=", "last_response", ".", "status_line", "last_response", ".", "headers", ".", "each", "do", "|", "line", "|", "hdr", ",", "val", "=", "line", ".", "split", "(", "\":\"", ",", "2", ")", "val", ".", "strip!", "unless", "val", ".", "nil?", "if", "@headers", ".", "key?", "(", "hdr", ")", "@headers", "[", "hdr", "]", "=", "[", "@headers", "[", "hdr", "]", "]", "unless", "@headers", "[", "hdr", "]", ".", "kind_of?", "Array", "@headers", "[", "hdr", "]", "<<", "val", "else", "@headers", "[", "hdr", "]", "=", "val", "end", "end", "end" ]
Called by the C code to parse and set the headers
[ "Called", "by", "the", "C", "code", "to", "parse", "and", "set", "the", "headers" ]
c48e31cfb93d8359c8c81a9d3fb14269f24b6aac
https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/response.rb#L116-L135
17,039
toland/patron
lib/patron/request.rb
Patron.Request.auth_type=
def auth_type=(type=:basic) @auth_type = case type when :basic, "basic" Request::AuthBasic when :digest, "digest" Request::AuthDigest when :any, "any" Request::AuthAny else raise "#{type.inspect} is an unknown authentication type" end end
ruby
def auth_type=(type=:basic) @auth_type = case type when :basic, "basic" Request::AuthBasic when :digest, "digest" Request::AuthDigest when :any, "any" Request::AuthAny else raise "#{type.inspect} is an unknown authentication type" end end
[ "def", "auth_type", "=", "(", "type", "=", ":basic", ")", "@auth_type", "=", "case", "type", "when", ":basic", ",", "\"basic\"", "Request", "::", "AuthBasic", "when", ":digest", ",", "\"digest\"", "Request", "::", "AuthDigest", "when", ":any", ",", "\"any\"", "Request", "::", "AuthAny", "else", "raise", "\"#{type.inspect} is an unknown authentication type\"", "end", "end" ]
Set the type of authentication to use for this request. @param [String, Symbol]type The type of authentication to use for this request, can be one of :basic, :digest, or :any @example sess.username = "foo" sess.password = "sekrit" sess.auth_type = :digest
[ "Set", "the", "type", "of", "authentication", "to", "use", "for", "this", "request", "." ]
c48e31cfb93d8359c8c81a9d3fb14269f24b6aac
https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/request.rb#L49-L60
17,040
toland/patron
lib/patron/request.rb
Patron.Request.action=
def action=(action) if !VALID_ACTIONS.include?(action.to_s.upcase) raise ArgumentError, "Action must be one of #{VALID_ACTIONS.join(', ')}" end @action = action.downcase.to_sym end
ruby
def action=(action) if !VALID_ACTIONS.include?(action.to_s.upcase) raise ArgumentError, "Action must be one of #{VALID_ACTIONS.join(', ')}" end @action = action.downcase.to_sym end
[ "def", "action", "=", "(", "action", ")", "if", "!", "VALID_ACTIONS", ".", "include?", "(", "action", ".", "to_s", ".", "upcase", ")", "raise", "ArgumentError", ",", "\"Action must be one of #{VALID_ACTIONS.join(', ')}\"", "end", "@action", "=", "action", ".", "downcase", ".", "to_sym", "end" ]
Sets the HTTP verb for the request @param action[String] the name of the HTTP verb
[ "Sets", "the", "HTTP", "verb", "for", "the", "request" ]
c48e31cfb93d8359c8c81a9d3fb14269f24b6aac
https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/request.rb#L84-L89
17,041
toland/patron
lib/patron/session.rb
Patron.Session.handle_cookies
def handle_cookies(file_path = nil) if file_path path = Pathname(file_path).expand_path if !File.exists?(file_path) && !File.writable?(path.dirname) raise ArgumentError, "Can't create file #{path} (permission error)" elsif File.exists?(file_path) && !File.writable?(file_path) raise ArgumentError, "Can't read or write file #{path} (permission error)" end else path = nil end # Apparently calling this with an empty string sets the cookie file, # but calling it with a path to a writable file sets that file to be # the cookie jar (new cookies are written there) add_cookie_file(path.to_s) self end
ruby
def handle_cookies(file_path = nil) if file_path path = Pathname(file_path).expand_path if !File.exists?(file_path) && !File.writable?(path.dirname) raise ArgumentError, "Can't create file #{path} (permission error)" elsif File.exists?(file_path) && !File.writable?(file_path) raise ArgumentError, "Can't read or write file #{path} (permission error)" end else path = nil end # Apparently calling this with an empty string sets the cookie file, # but calling it with a path to a writable file sets that file to be # the cookie jar (new cookies are written there) add_cookie_file(path.to_s) self end
[ "def", "handle_cookies", "(", "file_path", "=", "nil", ")", "if", "file_path", "path", "=", "Pathname", "(", "file_path", ")", ".", "expand_path", "if", "!", "File", ".", "exists?", "(", "file_path", ")", "&&", "!", "File", ".", "writable?", "(", "path", ".", "dirname", ")", "raise", "ArgumentError", ",", "\"Can't create file #{path} (permission error)\"", "elsif", "File", ".", "exists?", "(", "file_path", ")", "&&", "!", "File", ".", "writable?", "(", "file_path", ")", "raise", "ArgumentError", ",", "\"Can't read or write file #{path} (permission error)\"", "end", "else", "path", "=", "nil", "end", "# Apparently calling this with an empty string sets the cookie file,", "# but calling it with a path to a writable file sets that file to be", "# the cookie jar (new cookies are written there)", "add_cookie_file", "(", "path", ".", "to_s", ")", "self", "end" ]
Create a new Session object for performing requests. @param args[Hash] options for the Session (same names as the writable attributes of the Session) @yield self Turn on cookie handling for this session, storing them in memory by default or in +file+ if specified. The `file` must be readable and writable. Calling multiple times will add more files. @todo the cookie jar and cookie file path options should be split @param file_path[String] path to an existing cookie jar file, or nil to store cookies in memory @return self
[ "Create", "a", "new", "Session", "object", "for", "performing", "requests", "." ]
c48e31cfb93d8359c8c81a9d3fb14269f24b6aac
https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/session.rb#L145-L164
17,042
toland/patron
lib/patron/session.rb
Patron.Session.post
def post(url, data, headers = {}) if data.is_a?(Hash) data = data.map {|k,v| urlencode(k.to_s) + '=' + urlencode(v.to_s) }.join('&') headers['Content-Type'] = 'application/x-www-form-urlencoded' end request(:post, url, headers, :data => data) end
ruby
def post(url, data, headers = {}) if data.is_a?(Hash) data = data.map {|k,v| urlencode(k.to_s) + '=' + urlencode(v.to_s) }.join('&') headers['Content-Type'] = 'application/x-www-form-urlencoded' end request(:post, url, headers, :data => data) end
[ "def", "post", "(", "url", ",", "data", ",", "headers", "=", "{", "}", ")", "if", "data", ".", "is_a?", "(", "Hash", ")", "data", "=", "data", ".", "map", "{", "|", "k", ",", "v", "|", "urlencode", "(", "k", ".", "to_s", ")", "+", "'='", "+", "urlencode", "(", "v", ".", "to_s", ")", "}", ".", "join", "(", "'&'", ")", "headers", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded'", "end", "request", "(", ":post", ",", "url", ",", "headers", ",", ":data", "=>", "data", ")", "end" ]
Uploads the passed `data` to the specified `url` using an HTTP POST. @param url[String] the URL to fetch @param data[Hash, #to_s, #to_path] a Hash of form fields/values, or an object that can be converted to a String to create the request body, or an object that responds to #to_path to upload the entire request body from that file @param headers[Hash] the hash of header keys to values @return [Patron::Response]
[ "Uploads", "the", "passed", "data", "to", "the", "specified", "url", "using", "an", "HTTP", "POST", "." ]
c48e31cfb93d8359c8c81a9d3fb14269f24b6aac
https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/session.rb#L275-L281
17,043
toland/patron
lib/patron/session.rb
Patron.Session.post_multipart
def post_multipart(url, data, filename, headers = {}) request(:post, url, headers, {:data => data, :file => filename, :multipart => true}) end
ruby
def post_multipart(url, data, filename, headers = {}) request(:post, url, headers, {:data => data, :file => filename, :multipart => true}) end
[ "def", "post_multipart", "(", "url", ",", "data", ",", "filename", ",", "headers", "=", "{", "}", ")", "request", "(", ":post", ",", "url", ",", "headers", ",", "{", ":data", "=>", "data", ",", ":file", "=>", "filename", ",", ":multipart", "=>", "true", "}", ")", "end" ]
Uploads the contents of `filename` to the specified `url` using an HTTP POST, in combination with given form fields passed in `data`. @param url[String] the URL to fetch @param data[Hash] hash of the form fields @param filename[String] path to the file to be uploaded @param headers[Hash] the hash of header keys to values @return [Patron::Response]
[ "Uploads", "the", "contents", "of", "filename", "to", "the", "specified", "url", "using", "an", "HTTP", "POST", "in", "combination", "with", "given", "form", "fields", "passed", "in", "data", "." ]
c48e31cfb93d8359c8c81a9d3fb14269f24b6aac
https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/session.rb#L302-L304
17,044
toland/patron
lib/patron/session.rb
Patron.Session.build_request
def build_request(action, url, headers, options = {}) # If the Expect header isn't set uploads are really slow headers['Expect'] ||= '' Request.new.tap do |req| req.action = action req.headers = self.headers.merge headers req.automatic_content_encoding = options.fetch :automatic_content_encoding, self.automatic_content_encoding req.timeout = options.fetch :timeout, self.timeout req.connect_timeout = options.fetch :connect_timeout, self.connect_timeout req.dns_cache_timeout = options.fetch :dns_cache_timeout, self.dns_cache_timeout req.low_speed_time = options.fetch :low_speed_time, self.low_speed_time req.low_speed_limit = options.fetch :low_speed_limit, self.low_speed_limit req.force_ipv4 = options.fetch :force_ipv4, self.force_ipv4 req.max_redirects = options.fetch :max_redirects, self.max_redirects req.username = options.fetch :username, self.username req.password = options.fetch :password, self.password req.proxy = options.fetch :proxy, self.proxy req.proxy_type = options.fetch :proxy_type, self.proxy_type req.auth_type = options.fetch :auth_type, self.auth_type req.insecure = options.fetch :insecure, self.insecure req.ssl_version = options.fetch :ssl_version, self.ssl_version req.http_version = options.fetch :http_version, self.http_version req.cacert = options.fetch :cacert, self.cacert req.ignore_content_length = options.fetch :ignore_content_length, self.ignore_content_length req.buffer_size = options.fetch :buffer_size, self.buffer_size req.download_byte_limit = options.fetch :download_byte_limit, self.download_byte_limit req.progress_callback = options.fetch :progress_callback, self.progress_callback req.multipart = options[:multipart] req.upload_data = options[:data] req.file_name = options[:file] base_url = self.base_url.to_s url = url.to_s raise ArgumentError, "Empty URL" if base_url.empty? && url.empty? uri = URI.parse(base_url.empty? ? url : File.join(base_url, url)) query = uri.query.to_s.split('&') query += options[:query].is_a?(Hash) ? Util.build_query_pairs_from_hash(options[:query]) : options[:query].to_s.split('&') uri.query = query.join('&') uri.query = nil if uri.query.empty? url = uri.to_s req.url = url end end
ruby
def build_request(action, url, headers, options = {}) # If the Expect header isn't set uploads are really slow headers['Expect'] ||= '' Request.new.tap do |req| req.action = action req.headers = self.headers.merge headers req.automatic_content_encoding = options.fetch :automatic_content_encoding, self.automatic_content_encoding req.timeout = options.fetch :timeout, self.timeout req.connect_timeout = options.fetch :connect_timeout, self.connect_timeout req.dns_cache_timeout = options.fetch :dns_cache_timeout, self.dns_cache_timeout req.low_speed_time = options.fetch :low_speed_time, self.low_speed_time req.low_speed_limit = options.fetch :low_speed_limit, self.low_speed_limit req.force_ipv4 = options.fetch :force_ipv4, self.force_ipv4 req.max_redirects = options.fetch :max_redirects, self.max_redirects req.username = options.fetch :username, self.username req.password = options.fetch :password, self.password req.proxy = options.fetch :proxy, self.proxy req.proxy_type = options.fetch :proxy_type, self.proxy_type req.auth_type = options.fetch :auth_type, self.auth_type req.insecure = options.fetch :insecure, self.insecure req.ssl_version = options.fetch :ssl_version, self.ssl_version req.http_version = options.fetch :http_version, self.http_version req.cacert = options.fetch :cacert, self.cacert req.ignore_content_length = options.fetch :ignore_content_length, self.ignore_content_length req.buffer_size = options.fetch :buffer_size, self.buffer_size req.download_byte_limit = options.fetch :download_byte_limit, self.download_byte_limit req.progress_callback = options.fetch :progress_callback, self.progress_callback req.multipart = options[:multipart] req.upload_data = options[:data] req.file_name = options[:file] base_url = self.base_url.to_s url = url.to_s raise ArgumentError, "Empty URL" if base_url.empty? && url.empty? uri = URI.parse(base_url.empty? ? url : File.join(base_url, url)) query = uri.query.to_s.split('&') query += options[:query].is_a?(Hash) ? Util.build_query_pairs_from_hash(options[:query]) : options[:query].to_s.split('&') uri.query = query.join('&') uri.query = nil if uri.query.empty? url = uri.to_s req.url = url end end
[ "def", "build_request", "(", "action", ",", "url", ",", "headers", ",", "options", "=", "{", "}", ")", "# If the Expect header isn't set uploads are really slow", "headers", "[", "'Expect'", "]", "||=", "''", "Request", ".", "new", ".", "tap", "do", "|", "req", "|", "req", ".", "action", "=", "action", "req", ".", "headers", "=", "self", ".", "headers", ".", "merge", "headers", "req", ".", "automatic_content_encoding", "=", "options", ".", "fetch", ":automatic_content_encoding", ",", "self", ".", "automatic_content_encoding", "req", ".", "timeout", "=", "options", ".", "fetch", ":timeout", ",", "self", ".", "timeout", "req", ".", "connect_timeout", "=", "options", ".", "fetch", ":connect_timeout", ",", "self", ".", "connect_timeout", "req", ".", "dns_cache_timeout", "=", "options", ".", "fetch", ":dns_cache_timeout", ",", "self", ".", "dns_cache_timeout", "req", ".", "low_speed_time", "=", "options", ".", "fetch", ":low_speed_time", ",", "self", ".", "low_speed_time", "req", ".", "low_speed_limit", "=", "options", ".", "fetch", ":low_speed_limit", ",", "self", ".", "low_speed_limit", "req", ".", "force_ipv4", "=", "options", ".", "fetch", ":force_ipv4", ",", "self", ".", "force_ipv4", "req", ".", "max_redirects", "=", "options", ".", "fetch", ":max_redirects", ",", "self", ".", "max_redirects", "req", ".", "username", "=", "options", ".", "fetch", ":username", ",", "self", ".", "username", "req", ".", "password", "=", "options", ".", "fetch", ":password", ",", "self", ".", "password", "req", ".", "proxy", "=", "options", ".", "fetch", ":proxy", ",", "self", ".", "proxy", "req", ".", "proxy_type", "=", "options", ".", "fetch", ":proxy_type", ",", "self", ".", "proxy_type", "req", ".", "auth_type", "=", "options", ".", "fetch", ":auth_type", ",", "self", ".", "auth_type", "req", ".", "insecure", "=", "options", ".", "fetch", ":insecure", ",", "self", ".", "insecure", "req", ".", "ssl_version", "=", "options", ".", "fetch", ":ssl_version", ",", "self", ".", "ssl_version", "req", ".", "http_version", "=", "options", ".", "fetch", ":http_version", ",", "self", ".", "http_version", "req", ".", "cacert", "=", "options", ".", "fetch", ":cacert", ",", "self", ".", "cacert", "req", ".", "ignore_content_length", "=", "options", ".", "fetch", ":ignore_content_length", ",", "self", ".", "ignore_content_length", "req", ".", "buffer_size", "=", "options", ".", "fetch", ":buffer_size", ",", "self", ".", "buffer_size", "req", ".", "download_byte_limit", "=", "options", ".", "fetch", ":download_byte_limit", ",", "self", ".", "download_byte_limit", "req", ".", "progress_callback", "=", "options", ".", "fetch", ":progress_callback", ",", "self", ".", "progress_callback", "req", ".", "multipart", "=", "options", "[", ":multipart", "]", "req", ".", "upload_data", "=", "options", "[", ":data", "]", "req", ".", "file_name", "=", "options", "[", ":file", "]", "base_url", "=", "self", ".", "base_url", ".", "to_s", "url", "=", "url", ".", "to_s", "raise", "ArgumentError", ",", "\"Empty URL\"", "if", "base_url", ".", "empty?", "&&", "url", ".", "empty?", "uri", "=", "URI", ".", "parse", "(", "base_url", ".", "empty?", "?", "url", ":", "File", ".", "join", "(", "base_url", ",", "url", ")", ")", "query", "=", "uri", ".", "query", ".", "to_s", ".", "split", "(", "'&'", ")", "query", "+=", "options", "[", ":query", "]", ".", "is_a?", "(", "Hash", ")", "?", "Util", ".", "build_query_pairs_from_hash", "(", "options", "[", ":query", "]", ")", ":", "options", "[", ":query", "]", ".", "to_s", ".", "split", "(", "'&'", ")", "uri", ".", "query", "=", "query", ".", "join", "(", "'&'", ")", "uri", ".", "query", "=", "nil", "if", "uri", ".", "query", ".", "empty?", "url", "=", "uri", ".", "to_s", "req", ".", "url", "=", "url", "end", "end" ]
Builds a request object that can be used by ++handle_request++ Note that internally, ++handle_request++ uses instance variables of the Request object, and not it's public methods. @param action[String] the HTTP verb @param url[#to_s] the addition to the base url component, or a complete URL @param headers[Hash] a hash of headers, "Accept" will be automatically set to an empty string if not provided @param options[Hash] any overriding options (will shadow the options from the Session object) @return [Patron::Request] the request that will be passed to ++handle_request++
[ "Builds", "a", "request", "object", "that", "can", "be", "used", "by", "++", "handle_request", "++", "Note", "that", "internally", "++", "handle_request", "++", "uses", "instance", "variables", "of", "the", "Request", "object", "and", "not", "it", "s", "public", "methods", "." ]
c48e31cfb93d8359c8c81a9d3fb14269f24b6aac
https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/session.rb#L357-L400
17,045
xijo/reverse_markdown
lib/reverse_markdown/cleaner.rb
ReverseMarkdown.Cleaner.clean_tag_borders
def clean_tag_borders(string) result = string.gsub(/\s?\*{2,}.*?\*{2,}\s?/) do |match| preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do match.strip.sub('** ', '**').sub(' **', '**') end end result = result.gsub(/\s?\_{2,}.*?\_{2,}\s?/) do |match| preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do match.strip.sub('__ ', '__').sub(' __', '__') end end result = result.gsub(/\s?~{2,}.*?~{2,}\s?/) do |match| preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do match.strip.sub('~~ ', '~~').sub(' ~~', '~~') end end result.gsub(/\s?\[.*?\]\s?/) do |match| preserve_border_whitespaces(match) do match.strip.sub('[ ', '[').sub(' ]', ']') end end end
ruby
def clean_tag_borders(string) result = string.gsub(/\s?\*{2,}.*?\*{2,}\s?/) do |match| preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do match.strip.sub('** ', '**').sub(' **', '**') end end result = result.gsub(/\s?\_{2,}.*?\_{2,}\s?/) do |match| preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do match.strip.sub('__ ', '__').sub(' __', '__') end end result = result.gsub(/\s?~{2,}.*?~{2,}\s?/) do |match| preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do match.strip.sub('~~ ', '~~').sub(' ~~', '~~') end end result.gsub(/\s?\[.*?\]\s?/) do |match| preserve_border_whitespaces(match) do match.strip.sub('[ ', '[').sub(' ]', ']') end end end
[ "def", "clean_tag_borders", "(", "string", ")", "result", "=", "string", ".", "gsub", "(", "/", "\\s", "\\*", "\\*", "\\s", "/", ")", "do", "|", "match", "|", "preserve_border_whitespaces", "(", "match", ",", "default_border", ":", "ReverseMarkdown", ".", "config", ".", "tag_border", ")", "do", "match", ".", "strip", ".", "sub", "(", "'** '", ",", "'**'", ")", ".", "sub", "(", "' **'", ",", "'**'", ")", "end", "end", "result", "=", "result", ".", "gsub", "(", "/", "\\s", "\\_", "\\_", "\\s", "/", ")", "do", "|", "match", "|", "preserve_border_whitespaces", "(", "match", ",", "default_border", ":", "ReverseMarkdown", ".", "config", ".", "tag_border", ")", "do", "match", ".", "strip", ".", "sub", "(", "'__ '", ",", "'__'", ")", ".", "sub", "(", "' __'", ",", "'__'", ")", "end", "end", "result", "=", "result", ".", "gsub", "(", "/", "\\s", "\\s", "/", ")", "do", "|", "match", "|", "preserve_border_whitespaces", "(", "match", ",", "default_border", ":", "ReverseMarkdown", ".", "config", ".", "tag_border", ")", "do", "match", ".", "strip", ".", "sub", "(", "'~~ '", ",", "'~~'", ")", ".", "sub", "(", "' ~~'", ",", "'~~'", ")", "end", "end", "result", ".", "gsub", "(", "/", "\\s", "\\[", "\\]", "\\s", "/", ")", "do", "|", "match", "|", "preserve_border_whitespaces", "(", "match", ")", "do", "match", ".", "strip", ".", "sub", "(", "'[ '", ",", "'['", ")", ".", "sub", "(", "' ]'", ",", "']'", ")", "end", "end", "end" ]
Find non-asterisk content that is enclosed by two or more asterisks. Ensure that only one whitespace occurs in the border area. Same for underscores and brackets.
[ "Find", "non", "-", "asterisk", "content", "that", "is", "enclosed", "by", "two", "or", "more", "asterisks", ".", "Ensure", "that", "only", "one", "whitespace", "occurs", "in", "the", "border", "area", ".", "Same", "for", "underscores", "and", "brackets", "." ]
4a893bc6534ade98171ed4acfc8777e0f0ab7d6c
https://github.com/xijo/reverse_markdown/blob/4a893bc6534ade98171ed4acfc8777e0f0ab7d6c/lib/reverse_markdown/cleaner.rb#L32-L56
17,046
sinatra/mustermann
mustermann-contrib/lib/mustermann/file_utils.rb
Mustermann.FileUtils.glob_map
def glob_map(map = {}, **options, &block) map = Mapper === map ? map : Mapper.new(map, **options) mapped = glob(*map.to_h.keys).map { |f| [f, unescape(map[f])] } block ? mapped.map(&block) : Hash[mapped] end
ruby
def glob_map(map = {}, **options, &block) map = Mapper === map ? map : Mapper.new(map, **options) mapped = glob(*map.to_h.keys).map { |f| [f, unescape(map[f])] } block ? mapped.map(&block) : Hash[mapped] end
[ "def", "glob_map", "(", "map", "=", "{", "}", ",", "**", "options", ",", "&", "block", ")", "map", "=", "Mapper", "===", "map", "?", "map", ":", "Mapper", ".", "new", "(", "map", ",", "**", "options", ")", "mapped", "=", "glob", "(", "map", ".", "to_h", ".", "keys", ")", ".", "map", "{", "|", "f", "|", "[", "f", ",", "unescape", "(", "map", "[", "f", "]", ")", "]", "}", "block", "?", "mapped", ".", "map", "(", "block", ")", ":", "Hash", "[", "mapped", "]", "end" ]
Allows to search for files an map these onto other strings. @example require 'mustermann/file_utils' Mustermann::FileUtils.glob_map(':base.:ext' => ':base.bak.:ext') # => {'example.txt' => 'example.bak.txt'} Mustermann::FileUtils.glob_map(':base.:ext' => :base) { |file, mapped| mapped } # => ['example'] @see Mustermann::Mapper
[ "Allows", "to", "search", "for", "files", "an", "map", "these", "onto", "other", "strings", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L60-L64
17,047
sinatra/mustermann
mustermann-contrib/lib/mustermann/file_utils.rb
Mustermann.FileUtils.cp
def cp(map = {}, recursive: false, **options) utils_opts, opts = split_options(:preserve, :dereference_root, :remove_destination, **options) cp_method = recursive ? :cp_r : :cp glob_map(map, **opts) { |o,n| f.send(cp_method, o, n, **utils_opts) } end
ruby
def cp(map = {}, recursive: false, **options) utils_opts, opts = split_options(:preserve, :dereference_root, :remove_destination, **options) cp_method = recursive ? :cp_r : :cp glob_map(map, **opts) { |o,n| f.send(cp_method, o, n, **utils_opts) } end
[ "def", "cp", "(", "map", "=", "{", "}", ",", "recursive", ":", "false", ",", "**", "options", ")", "utils_opts", ",", "opts", "=", "split_options", "(", ":preserve", ",", ":dereference_root", ",", ":remove_destination", ",", "**", "options", ")", "cp_method", "=", "recursive", "?", ":cp_r", ":", ":cp", "glob_map", "(", "map", ",", "**", "opts", ")", "{", "|", "o", ",", "n", "|", "f", ".", "send", "(", "cp_method", ",", "o", ",", "n", ",", "**", "utils_opts", ")", "}", "end" ]
Copies files based on a pattern mapping. @example require 'mustermann/file_utils' # copies example.txt to example.bak.txt Mustermann::FileUtils.cp(':base.:ext' => ':base.bak.:ext') @see #glob_map
[ "Copies", "files", "based", "on", "a", "pattern", "mapping", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L75-L79
17,048
sinatra/mustermann
mustermann-contrib/lib/mustermann/file_utils.rb
Mustermann.FileUtils.mv
def mv(map = {}, **options) utils_opts, opts = split_options(**options) glob_map(map, **opts) { |o,n| f.mv(o, n, **utils_opts) } end
ruby
def mv(map = {}, **options) utils_opts, opts = split_options(**options) glob_map(map, **opts) { |o,n| f.mv(o, n, **utils_opts) } end
[ "def", "mv", "(", "map", "=", "{", "}", ",", "**", "options", ")", "utils_opts", ",", "opts", "=", "split_options", "(", "**", "options", ")", "glob_map", "(", "map", ",", "**", "opts", ")", "{", "|", "o", ",", "n", "|", "f", ".", "mv", "(", "o", ",", "n", ",", "**", "utils_opts", ")", "}", "end" ]
Moves files based on a pattern mapping. @example require 'mustermann/file_utils' # moves example.txt to example.bak.txt Mustermann::FileUtils.mv(':base.:ext' => ':base.bak.:ext') @see #glob_map
[ "Moves", "files", "based", "on", "a", "pattern", "mapping", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L104-L107
17,049
sinatra/mustermann
mustermann-contrib/lib/mustermann/file_utils.rb
Mustermann.FileUtils.ln
def ln(map = {}, symbolic: false, **options) utils_opts, opts = split_options(**options) link_method = symbolic ? :ln_s : :ln glob_map(map, **opts) { |o,n| f.send(link_method, o, n, **utils_opts) } end
ruby
def ln(map = {}, symbolic: false, **options) utils_opts, opts = split_options(**options) link_method = symbolic ? :ln_s : :ln glob_map(map, **opts) { |o,n| f.send(link_method, o, n, **utils_opts) } end
[ "def", "ln", "(", "map", "=", "{", "}", ",", "symbolic", ":", "false", ",", "**", "options", ")", "utils_opts", ",", "opts", "=", "split_options", "(", "**", "options", ")", "link_method", "=", "symbolic", "?", ":ln_s", ":", ":ln", "glob_map", "(", "map", ",", "**", "opts", ")", "{", "|", "o", ",", "n", "|", "f", ".", "send", "(", "link_method", ",", "o", ",", "n", ",", "**", "utils_opts", ")", "}", "end" ]
Creates links based on a pattern mapping. @example require 'mustermann/file_utils' # creates a link from bin/example to lib/example.rb Mustermann::FileUtils.ln('lib/:name.rb' => 'bin/:name') @see #glob_map
[ "Creates", "links", "based", "on", "a", "pattern", "mapping", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L119-L123
17,050
sinatra/mustermann
mustermann-contrib/lib/mustermann/file_utils.rb
Mustermann.FileUtils.ln_sf
def ln_sf(map = {}, **options) ln(map, symbolic: true, force: true, **options) end
ruby
def ln_sf(map = {}, **options) ln(map, symbolic: true, force: true, **options) end
[ "def", "ln_sf", "(", "map", "=", "{", "}", ",", "**", "options", ")", "ln", "(", "map", ",", "symbolic", ":", "true", ",", "force", ":", "true", ",", "**", "options", ")", "end" ]
Creates symbolic links based on a pattern mapping. Overrides potentailly existing files. @example require 'mustermann/file_utils' # creates a symbolic link from bin/example to lib/example.rb Mustermann::FileUtils.ln_sf('lib/:name.rb' => 'bin/:name') @see #glob_map
[ "Creates", "symbolic", "links", "based", "on", "a", "pattern", "mapping", ".", "Overrides", "potentailly", "existing", "files", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L148-L150
17,051
sinatra/mustermann
mustermann-contrib/lib/mustermann/file_utils.rb
Mustermann.FileUtils.pattern_with_glob_pattern
def pattern_with_glob_pattern(*pattern, **options) options[:uri_decode] ||= false pattern = Mustermann.new(*pattern.flatten, **options) @glob_patterns ||= {} @glob_patterns[pattern] ||= GlobPattern.generate(pattern) [pattern, @glob_patterns[pattern]] end
ruby
def pattern_with_glob_pattern(*pattern, **options) options[:uri_decode] ||= false pattern = Mustermann.new(*pattern.flatten, **options) @glob_patterns ||= {} @glob_patterns[pattern] ||= GlobPattern.generate(pattern) [pattern, @glob_patterns[pattern]] end
[ "def", "pattern_with_glob_pattern", "(", "*", "pattern", ",", "**", "options", ")", "options", "[", ":uri_decode", "]", "||=", "false", "pattern", "=", "Mustermann", ".", "new", "(", "pattern", ".", "flatten", ",", "**", "options", ")", "@glob_patterns", "||=", "{", "}", "@glob_patterns", "[", "pattern", "]", "||=", "GlobPattern", ".", "generate", "(", "pattern", ")", "[", "pattern", ",", "@glob_patterns", "[", "pattern", "]", "]", "end" ]
Create a Mustermann pattern from whatever the input is and turn it into a glob pattern. @!visibility private
[ "Create", "a", "Mustermann", "pattern", "from", "whatever", "the", "input", "is", "and", "turn", "it", "into", "a", "glob", "pattern", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L173-L179
17,052
sinatra/mustermann
mustermann/lib/mustermann/concat.rb
Mustermann.Concat.pump
def pump(string, inject_with: :+, initial: nil, with_size: false) substring = string results = Array(initial) patterns.each do |pattern| result, size = yield(pattern, substring) return unless result results << result size ||= result substring = substring[size..-1] end results = results.inject(inject_with) with_size ? [results, string.size - substring.size] : results end
ruby
def pump(string, inject_with: :+, initial: nil, with_size: false) substring = string results = Array(initial) patterns.each do |pattern| result, size = yield(pattern, substring) return unless result results << result size ||= result substring = substring[size..-1] end results = results.inject(inject_with) with_size ? [results, string.size - substring.size] : results end
[ "def", "pump", "(", "string", ",", "inject_with", ":", ":+", ",", "initial", ":", "nil", ",", "with_size", ":", "false", ")", "substring", "=", "string", "results", "=", "Array", "(", "initial", ")", "patterns", ".", "each", "do", "|", "pattern", "|", "result", ",", "size", "=", "yield", "(", "pattern", ",", "substring", ")", "return", "unless", "result", "results", "<<", "result", "size", "||=", "result", "substring", "=", "substring", "[", "size", "..", "-", "1", "]", "end", "results", "=", "results", ".", "inject", "(", "inject_with", ")", "with_size", "?", "[", "results", ",", "string", ".", "size", "-", "substring", ".", "size", "]", ":", "results", "end" ]
used to generate results for various methods by scanning through an input string @!visibility private
[ "used", "to", "generate", "results", "for", "various", "methods", "by", "scanning", "through", "an", "input", "string" ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/concat.rb#L110-L124
17,053
sinatra/mustermann
mustermann/lib/mustermann/concat.rb
Mustermann.Concat.combined_ast
def combined_ast payload = patterns.map { |p| AST::Node[:group].new(p.to_ast.payload) } AST::Node[:root].new(payload) end
ruby
def combined_ast payload = patterns.map { |p| AST::Node[:group].new(p.to_ast.payload) } AST::Node[:root].new(payload) end
[ "def", "combined_ast", "payload", "=", "patterns", ".", "map", "{", "|", "p", "|", "AST", "::", "Node", "[", ":group", "]", ".", "new", "(", "p", ".", "to_ast", ".", "payload", ")", "}", "AST", "::", "Node", "[", ":root", "]", ".", "new", "(", "payload", ")", "end" ]
generates one big AST from all patterns will not check if patterns support AST generation @!visibility private
[ "generates", "one", "big", "AST", "from", "all", "patterns", "will", "not", "check", "if", "patterns", "support", "AST", "generation" ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/concat.rb#L129-L132
17,054
sinatra/mustermann
mustermann/lib/mustermann/sinatra.rb
Mustermann.Sinatra.|
def |(other) return super unless converted = self.class.try_convert(other, **options) return super unless converted.names.empty? or names.empty? self.class.new(safe_string + "|" + converted.safe_string, **options) end
ruby
def |(other) return super unless converted = self.class.try_convert(other, **options) return super unless converted.names.empty? or names.empty? self.class.new(safe_string + "|" + converted.safe_string, **options) end
[ "def", "|", "(", "other", ")", "return", "super", "unless", "converted", "=", "self", ".", "class", ".", "try_convert", "(", "other", ",", "**", "options", ")", "return", "super", "unless", "converted", ".", "names", ".", "empty?", "or", "names", ".", "empty?", "self", ".", "class", ".", "new", "(", "safe_string", "+", "\"|\"", "+", "converted", ".", "safe_string", ",", "**", "options", ")", "end" ]
Creates a pattern that matches any string matching either one of the patterns. If a string is supplied, it is treated as a fully escaped Sinatra pattern. If the other pattern is also a Sintara pattern, it might join the two to a third sinatra pattern instead of generating a composite for efficiency reasons. This only happens if the sinatra pattern behaves exactly the same as a composite would in regards to matching, parsing, expanding and template generation. @example pattern = Mustermann.new('/foo/:name') | Mustermann.new('/:first/:second') pattern === '/foo/bar' # => true pattern === '/fox/bar' # => true pattern === '/foo' # => false @param [Mustermann::Pattern, String] other the other pattern @return [Mustermann::Pattern] a composite pattern @see Mustermann::Pattern#|
[ "Creates", "a", "pattern", "that", "matches", "any", "string", "matching", "either", "one", "of", "the", "patterns", ".", "If", "a", "string", "is", "supplied", "it", "is", "treated", "as", "a", "fully", "escaped", "Sinatra", "pattern", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/sinatra.rb#L59-L63
17,055
sinatra/mustermann
mustermann-contrib/lib/mustermann/string_scanner.rb
Mustermann.StringScanner.scan_until
def scan_until(pattern, **options) result, prefix = check_until_with_prefix(pattern, **options) track_result(prefix, result) end
ruby
def scan_until(pattern, **options) result, prefix = check_until_with_prefix(pattern, **options) track_result(prefix, result) end
[ "def", "scan_until", "(", "pattern", ",", "**", "options", ")", "result", ",", "prefix", "=", "check_until_with_prefix", "(", "pattern", ",", "**", "options", ")", "track_result", "(", "prefix", ",", "result", ")", "end" ]
Checks if the given pattern matches any substring starting at any position after the current position. If it does, it will advance the current {#position} to the end of the substring and merges any params parsed from the substring into {#params}. @param (see Mustermann.new) @return [Mustermann::StringScanner::ScanResult, nil] the matched substring, nil if it didn't match
[ "Checks", "if", "the", "given", "pattern", "matches", "any", "substring", "starting", "at", "any", "position", "after", "the", "current", "position", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/string_scanner.rb#L173-L176
17,056
sinatra/mustermann
mustermann-contrib/lib/mustermann/string_scanner.rb
Mustermann.StringScanner.unscan
def unscan raise ScanError, 'unscan failed: previous match record not exist' if @history.empty? previous = @history[0..-2] reset previous.each { |r| track_result(*r) } self end
ruby
def unscan raise ScanError, 'unscan failed: previous match record not exist' if @history.empty? previous = @history[0..-2] reset previous.each { |r| track_result(*r) } self end
[ "def", "unscan", "raise", "ScanError", ",", "'unscan failed: previous match record not exist'", "if", "@history", ".", "empty?", "previous", "=", "@history", "[", "0", "..", "-", "2", "]", "reset", "previous", ".", "each", "{", "|", "r", "|", "track_result", "(", "r", ")", "}", "self", "end" ]
Reverts the last operation that advanced the position. Operations advancing the position: {#terminate}, {#scan}, {#scan_until}, {#getch}. @return [Mustermann::StringScanner] the scanner itself
[ "Reverts", "the", "last", "operation", "that", "advanced", "the", "position", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/string_scanner.rb#L182-L188
17,057
sinatra/mustermann
mustermann-contrib/lib/mustermann/string_scanner.rb
Mustermann.StringScanner.check
def check(pattern, **options) params, length = create_pattern(pattern, **options).peek_params(rest) ScanResult.new(self, @position, length, params) if params end
ruby
def check(pattern, **options) params, length = create_pattern(pattern, **options).peek_params(rest) ScanResult.new(self, @position, length, params) if params end
[ "def", "check", "(", "pattern", ",", "**", "options", ")", "params", ",", "length", "=", "create_pattern", "(", "pattern", ",", "**", "options", ")", ".", "peek_params", "(", "rest", ")", "ScanResult", ".", "new", "(", "self", ",", "@position", ",", "length", ",", "params", ")", "if", "params", "end" ]
Checks if the given pattern matches any substring starting at the current position. Does not affect {#position} or {#params}. @param (see Mustermann.new) @return [Mustermann::StringScanner::ScanResult, nil] the matched substring, nil if it didn't match
[ "Checks", "if", "the", "given", "pattern", "matches", "any", "substring", "starting", "at", "the", "current", "position", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/string_scanner.rb#L196-L199
17,058
sinatra/mustermann
mustermann/lib/mustermann/identity.rb
Mustermann.Identity.expand
def expand(behavior = nil, values = {}) return to_s if values.empty? or behavior == :ignore raise ExpandError, "cannot expand with keys %p" % values.keys.sort if behavior == :raise raise ArgumentError, "unknown behavior %p" % behavior if behavior != :append params = values.map { |key, value| @@uri.escape(key.to_s) + "=" + @@uri.escape(value.to_s, /[^\w]/) } separator = @string.include?(??) ? ?& : ?? @string + separator + params.join(?&) end
ruby
def expand(behavior = nil, values = {}) return to_s if values.empty? or behavior == :ignore raise ExpandError, "cannot expand with keys %p" % values.keys.sort if behavior == :raise raise ArgumentError, "unknown behavior %p" % behavior if behavior != :append params = values.map { |key, value| @@uri.escape(key.to_s) + "=" + @@uri.escape(value.to_s, /[^\w]/) } separator = @string.include?(??) ? ?& : ?? @string + separator + params.join(?&) end
[ "def", "expand", "(", "behavior", "=", "nil", ",", "values", "=", "{", "}", ")", "return", "to_s", "if", "values", ".", "empty?", "or", "behavior", "==", ":ignore", "raise", "ExpandError", ",", "\"cannot expand with keys %p\"", "%", "values", ".", "keys", ".", "sort", "if", "behavior", "==", ":raise", "raise", "ArgumentError", ",", "\"unknown behavior %p\"", "%", "behavior", "if", "behavior", "!=", ":append", "params", "=", "values", ".", "map", "{", "|", "key", ",", "value", "|", "@@uri", ".", "escape", "(", "key", ".", "to_s", ")", "+", "\"=\"", "+", "@@uri", ".", "escape", "(", "value", ".", "to_s", ",", "/", "\\w", "/", ")", "}", "separator", "=", "@string", ".", "include?", "(", "??", ")", "?", "?&", ":", "??", "@string", "+", "separator", "+", "params", ".", "join", "(", "?&", ")", "end" ]
Identity patterns support expanding. This implementation does not use {Mustermann::Expander} internally to save memory and compilation time. @example (see Mustermann::Pattern#expand) @param (see Mustermann::Pattern#expand) @return (see Mustermann::Pattern#expand) @raise (see Mustermann::Pattern#expand) @see Mustermann::Pattern#expand @see Mustermann::Expander
[ "Identity", "patterns", "support", "expanding", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/identity.rb#L68-L75
17,059
sinatra/mustermann
mustermann-contrib/lib/mustermann/versions.rb
Mustermann.Versions.new
def new(*args, version: nil, **options) return super(*args, **options) unless versions.any? self[version].new(*args, **options) end
ruby
def new(*args, version: nil, **options) return super(*args, **options) unless versions.any? self[version].new(*args, **options) end
[ "def", "new", "(", "*", "args", ",", "version", ":", "nil", ",", "**", "options", ")", "return", "super", "(", "args", ",", "**", "options", ")", "unless", "versions", ".", "any?", "self", "[", "version", "]", ".", "new", "(", "args", ",", "**", "options", ")", "end" ]
Checks if class has mulitple versions available and picks one that matches the version option. @!visibility private
[ "Checks", "if", "class", "has", "mulitple", "versions", "available", "and", "picks", "one", "that", "matches", "the", "version", "option", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/versions.rb#L9-L12
17,060
sinatra/mustermann
mustermann-contrib/lib/mustermann/versions.rb
Mustermann.Versions.version
def version(*list, inherit_from: nil, &block) superclass = self[inherit_from] || self subclass = Class.new(superclass, &block) list.each { |v| versions[v] = subclass } end
ruby
def version(*list, inherit_from: nil, &block) superclass = self[inherit_from] || self subclass = Class.new(superclass, &block) list.each { |v| versions[v] = subclass } end
[ "def", "version", "(", "*", "list", ",", "inherit_from", ":", "nil", ",", "&", "block", ")", "superclass", "=", "self", "[", "inherit_from", "]", "||", "self", "subclass", "=", "Class", ".", "new", "(", "superclass", ",", "block", ")", "list", ".", "each", "{", "|", "v", "|", "versions", "[", "v", "]", "=", "subclass", "}", "end" ]
Defines a new version. @!visibility private
[ "Defines", "a", "new", "version", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/versions.rb#L22-L26
17,061
sinatra/mustermann
mustermann-contrib/lib/mustermann/versions.rb
Mustermann.Versions.[]
def [](version) return versions.values.last unless version detected = versions.detect { |v,_| version.start_with?(v) } raise ArgumentError, 'unsupported version %p' % version unless detected detected.last end
ruby
def [](version) return versions.values.last unless version detected = versions.detect { |v,_| version.start_with?(v) } raise ArgumentError, 'unsupported version %p' % version unless detected detected.last end
[ "def", "[]", "(", "version", ")", "return", "versions", ".", "values", ".", "last", "unless", "version", "detected", "=", "versions", ".", "detect", "{", "|", "v", ",", "_", "|", "version", ".", "start_with?", "(", "v", ")", "}", "raise", "ArgumentError", ",", "'unsupported version %p'", "%", "version", "unless", "detected", "detected", ".", "last", "end" ]
Resolve a subclass for a given version string. @!visibility private
[ "Resolve", "a", "subclass", "for", "a", "given", "version", "string", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/versions.rb#L30-L35
17,062
sinatra/mustermann
mustermann/lib/mustermann/caster.rb
Mustermann.Caster.cast
def cast(hash) return hash if empty? merge = {} hash.delete_if do |key, value| next unless casted = lazy.map { |e| e.cast(key, value) }.detect { |e| e } casted = { key => casted } unless casted.respond_to? :to_hash merge.update(casted.to_hash) end hash.update(merge) end
ruby
def cast(hash) return hash if empty? merge = {} hash.delete_if do |key, value| next unless casted = lazy.map { |e| e.cast(key, value) }.detect { |e| e } casted = { key => casted } unless casted.respond_to? :to_hash merge.update(casted.to_hash) end hash.update(merge) end
[ "def", "cast", "(", "hash", ")", "return", "hash", "if", "empty?", "merge", "=", "{", "}", "hash", ".", "delete_if", "do", "|", "key", ",", "value", "|", "next", "unless", "casted", "=", "lazy", ".", "map", "{", "|", "e", "|", "e", ".", "cast", "(", "key", ",", "value", ")", "}", ".", "detect", "{", "|", "e", "|", "e", "}", "casted", "=", "{", "key", "=>", "casted", "}", "unless", "casted", ".", "respond_to?", ":to_hash", "merge", ".", "update", "(", "casted", ".", "to_hash", ")", "end", "hash", ".", "update", "(", "merge", ")", "end" ]
Transforms a Hash. @param [Hash] hash pre-transform Hash @return [Hash] post-transform Hash @!visibility private
[ "Transforms", "a", "Hash", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/caster.rb#L45-L54
17,063
sinatra/mustermann
mustermann/lib/mustermann/mapper.rb
Mustermann.Mapper.update
def update(map) map.to_h.each_pair do |input, output| input = Mustermann.new(input, **@options) output = Expander.new(*output, additional_values: @additional_values, **@options) unless output.is_a? Expander @map << [input, output] end end
ruby
def update(map) map.to_h.each_pair do |input, output| input = Mustermann.new(input, **@options) output = Expander.new(*output, additional_values: @additional_values, **@options) unless output.is_a? Expander @map << [input, output] end end
[ "def", "update", "(", "map", ")", "map", ".", "to_h", ".", "each_pair", "do", "|", "input", ",", "output", "|", "input", "=", "Mustermann", ".", "new", "(", "input", ",", "**", "@options", ")", "output", "=", "Expander", ".", "new", "(", "output", ",", "additional_values", ":", "@additional_values", ",", "**", "@options", ")", "unless", "output", ".", "is_a?", "Expander", "@map", "<<", "[", "input", ",", "output", "]", "end", "end" ]
Creates a new mapper. @overload initialize(**options) @param options [Hash] options The options hash @yield block for generating mappings as a hash @yieldreturn [Hash] see {#update} @example require 'mustermann/mapper' Mustermann::Mapper.new(type: :rails) {{ "/:foo" => ["/:foo.html", "/:foo.:format"] }} @overload initialize(**options) @param options [Hash] options The options hash @yield block for generating mappings as a hash @yieldparam mapper [Mustermann::Mapper] the mapper instance @example require 'mustermann/mapper' Mustermann::Mapper.new(type: :rails) do |mapper| mapper["/:foo"] = ["/:foo.html", "/:foo.:format"] end @overload initialize(map = {}, **options) @param map [Hash] see {#update} @param [Hash] options The options hash @example map before options require 'mustermann/mapper' Mustermann::Mapper.new("/:foo" => "/:foo.html", type: :rails) @example map after options require 'mustermann/mapper' Mustermann::Mapper.new(type: :rails, "/:foo" => "/:foo.html") Add multiple mappings. @param map [Hash{String, Pattern: String, Pattern, Arry<String, Pattern>, Expander}] the mapping
[ "Creates", "a", "new", "mapper", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/mapper.rb#L59-L65
17,064
sinatra/mustermann
mustermann/lib/mustermann/mapper.rb
Mustermann.Mapper.convert
def convert(input, values = {}) @map.inject(input) do |current, (pattern, expander)| params = pattern.params(current) params &&= Hash[values.merge(params).map { |k,v| [k.to_s, v] }] expander.expandable?(params) ? expander.expand(params) : current end end
ruby
def convert(input, values = {}) @map.inject(input) do |current, (pattern, expander)| params = pattern.params(current) params &&= Hash[values.merge(params).map { |k,v| [k.to_s, v] }] expander.expandable?(params) ? expander.expand(params) : current end end
[ "def", "convert", "(", "input", ",", "values", "=", "{", "}", ")", "@map", ".", "inject", "(", "input", ")", "do", "|", "current", ",", "(", "pattern", ",", "expander", ")", "|", "params", "=", "pattern", ".", "params", "(", "current", ")", "params", "&&=", "Hash", "[", "values", ".", "merge", "(", "params", ")", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ",", "v", "]", "}", "]", "expander", ".", "expandable?", "(", "params", ")", "?", "expander", ".", "expand", "(", "params", ")", ":", "current", "end", "end" ]
Convert a string according to mappings. You can pass in additional params. @example mapping with and without additional parameters mapper = Mustermann::Mapper.new("/:example" => "(/:prefix)?/:example.html")
[ "Convert", "a", "string", "according", "to", "mappings", ".", "You", "can", "pass", "in", "additional", "params", "." ]
5625972edfddb3d254acd949a1a312cca5167de3
https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/mapper.rb#L77-L83
17,065
typhoeus/ethon
lib/ethon/easy.rb
Ethon.Easy.escape
def escape(value) string_pointer = Curl.easy_escape(handle, value, value.bytesize) returned_string = string_pointer.read_string Curl.free(string_pointer) returned_string end
ruby
def escape(value) string_pointer = Curl.easy_escape(handle, value, value.bytesize) returned_string = string_pointer.read_string Curl.free(string_pointer) returned_string end
[ "def", "escape", "(", "value", ")", "string_pointer", "=", "Curl", ".", "easy_escape", "(", "handle", ",", "value", ",", "value", ".", "bytesize", ")", "returned_string", "=", "string_pointer", ".", "read_string", "Curl", ".", "free", "(", "string_pointer", ")", "returned_string", "end" ]
Clones libcurl session handle. This means that all options that is set in the current handle will be set on duplicated handle. Url escapes the value. @example Url escape. easy.escape(value) @param [ String ] value The value to escape. @return [ String ] The escaped value. @api private
[ "Clones", "libcurl", "session", "handle", ".", "This", "means", "that", "all", "options", "that", "is", "set", "in", "the", "current", "handle", "will", "be", "set", "on", "duplicated", "handle", ".", "Url", "escapes", "the", "value", "." ]
c5c9c6e10114c9939642be522ab05432ca7ec5d2
https://github.com/typhoeus/ethon/blob/c5c9c6e10114c9939642be522ab05432ca7ec5d2/lib/ethon/easy.rb#L285-L290
17,066
abitdodgy/words_counted
lib/words_counted/counter.rb
WordsCounted.Counter.token_frequency
def token_frequency tokens.each_with_object(Hash.new(0)) { |token, hash| hash[token] += 1 }.sort_by_value_desc end
ruby
def token_frequency tokens.each_with_object(Hash.new(0)) { |token, hash| hash[token] += 1 }.sort_by_value_desc end
[ "def", "token_frequency", "tokens", ".", "each_with_object", "(", "Hash", ".", "new", "(", "0", ")", ")", "{", "|", "token", ",", "hash", "|", "hash", "[", "token", "]", "+=", "1", "}", ".", "sort_by_value_desc", "end" ]
Returns a sorted two-dimensional array where each member array is a token and its frequency. The array is sorted by frequency in descending order. @example Counter.new(%w[one two two three three three]).token_frequency # => [ ['three', 3], ['two', 2], ['one', 1] ] @return [Array<Array<String, Integer>>] An array of tokens and their frequencies
[ "Returns", "a", "sorted", "two", "-", "dimensional", "array", "where", "each", "member", "array", "is", "a", "token", "and", "its", "frequency", ".", "The", "array", "is", "sorted", "by", "frequency", "in", "descending", "order", "." ]
5f3ea74249e05f22e16e097ce7cf9b940887e0ae
https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/counter.rb#L66-L68
17,067
abitdodgy/words_counted
lib/words_counted/counter.rb
WordsCounted.Counter.token_lengths
def token_lengths tokens.uniq.each_with_object({}) { |token, hash| hash[token] = token.length }.sort_by_value_desc end
ruby
def token_lengths tokens.uniq.each_with_object({}) { |token, hash| hash[token] = token.length }.sort_by_value_desc end
[ "def", "token_lengths", "tokens", ".", "uniq", ".", "each_with_object", "(", "{", "}", ")", "{", "|", "token", ",", "hash", "|", "hash", "[", "token", "]", "=", "token", ".", "length", "}", ".", "sort_by_value_desc", "end" ]
Returns a sorted two-dimensional array where each member array is a token and its length. The array is sorted by length in descending order. @example Counter.new(%w[one two three four five]).token_lenghts # => [ ['three', 5], ['four', 4], ['five', 4], ['one', 3], ['two', 3] ] @return [Array<Array<String, Integer>>] An array of tokens and their lengths
[ "Returns", "a", "sorted", "two", "-", "dimensional", "array", "where", "each", "member", "array", "is", "a", "token", "and", "its", "length", ".", "The", "array", "is", "sorted", "by", "length", "in", "descending", "order", "." ]
5f3ea74249e05f22e16e097ce7cf9b940887e0ae
https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/counter.rb#L78-L80
17,068
abitdodgy/words_counted
lib/words_counted/counter.rb
WordsCounted.Counter.token_density
def token_density(precision: 2) token_frequency.each_with_object({}) { |(token, freq), hash| hash[token] = (freq / token_count.to_f).round(precision) }.sort_by_value_desc end
ruby
def token_density(precision: 2) token_frequency.each_with_object({}) { |(token, freq), hash| hash[token] = (freq / token_count.to_f).round(precision) }.sort_by_value_desc end
[ "def", "token_density", "(", "precision", ":", "2", ")", "token_frequency", ".", "each_with_object", "(", "{", "}", ")", "{", "|", "(", "token", ",", "freq", ")", ",", "hash", "|", "hash", "[", "token", "]", "=", "(", "freq", "/", "token_count", ".", "to_f", ")", ".", "round", "(", "precision", ")", "}", ".", "sort_by_value_desc", "end" ]
Returns a sorted two-dimensional array where each member array is a token and its density as a float, rounded to a precision of two decimal places. It accepts a precision argument which defaults to `2`. @example Counter.new(%w[Maj. Major Major Major]).token_density # => [ ['major', .75], ['maj', .25] ] @example with `precision` Counter.new(%w[Maj. Major Major Major]).token_density(precision: 4) # => [ ['major', .7500], ['maj', .2500] ] @param [Integer] precision The number of decimal places to round density to @return [Array<Array<String, Float>>] An array of tokens and their densities
[ "Returns", "a", "sorted", "two", "-", "dimensional", "array", "where", "each", "member", "array", "is", "a", "token", "and", "its", "density", "as", "a", "float", "rounded", "to", "a", "precision", "of", "two", "decimal", "places", ".", "It", "accepts", "a", "precision", "argument", "which", "defaults", "to", "2", "." ]
5f3ea74249e05f22e16e097ce7cf9b940887e0ae
https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/counter.rb#L96-L100
17,069
abitdodgy/words_counted
lib/words_counted/tokeniser.rb
WordsCounted.Tokeniser.tokenise
def tokenise(pattern: TOKEN_REGEXP, exclude: nil) filter_proc = filter_to_proc(exclude) @input.scan(pattern).map(&:downcase).reject { |token| filter_proc.call(token) } end
ruby
def tokenise(pattern: TOKEN_REGEXP, exclude: nil) filter_proc = filter_to_proc(exclude) @input.scan(pattern).map(&:downcase).reject { |token| filter_proc.call(token) } end
[ "def", "tokenise", "(", "pattern", ":", "TOKEN_REGEXP", ",", "exclude", ":", "nil", ")", "filter_proc", "=", "filter_to_proc", "(", "exclude", ")", "@input", ".", "scan", "(", "pattern", ")", ".", "map", "(", ":downcase", ")", ".", "reject", "{", "|", "token", "|", "filter_proc", ".", "call", "(", "token", ")", "}", "end" ]
Initialises state with the string to be tokenised. @param [String] input The string to tokenise Converts a string into an array of tokens using a regular expression. If a regexp is not provided a default one is used. See `Tokenizer.TOKEN_REGEXP`. Use `exclude` to remove tokens from the final list. `exclude` can be a string, a regular expression, a lambda, a symbol, or an array of one or more of those types. This allows for powerful and flexible tokenisation strategies. If a symbol is passed, it must name a predicate method. @example WordsCounted::Tokeniser.new("Hello World").tokenise # => ['hello', 'world'] @example With `pattern` WordsCounted::Tokeniser.new("Hello-Mohamad").tokenise(pattern: /[^-]+/) # => ['hello', 'mohamad'] @example With `exclude` as a string WordsCounted::Tokeniser.new("Hello Sami").tokenise(exclude: "hello") # => ['sami'] @example With `exclude` as a regexp WordsCounted::Tokeniser.new("Hello Dani").tokenise(exclude: /hello/i) # => ['dani'] @example With `exclude` as a lambda WordsCounted::Tokeniser.new("Goodbye Sami").tokenise( exclude: ->(token) { token.length > 6 } ) # => ['sami'] @example With `exclude` as a symbol WordsCounted::Tokeniser.new("Hello محمد").tokenise(exclude: :ascii_only?) # => ['محمد'] @example With `exclude` as an array of strings WordsCounted::Tokeniser.new("Goodbye Sami and hello Dani").tokenise( exclude: ["goodbye hello"] ) # => ['sami', 'and', dani'] @example With `exclude` as an array of regular expressions WordsCounted::Tokeniser.new("Goodbye and hello Dani").tokenise( exclude: [/goodbye/i, /and/i] ) # => ['hello', 'dani'] @example With `exclude` as an array of lambdas t = WordsCounted::Tokeniser.new("Special Agent 007") t.tokenise( exclude: [ ->(t) { t.to_i.odd? }, ->(t) { t.length > 5} ] ) # => ['agent'] @example With `exclude` as a mixed array t = WordsCounted::Tokeniser.new("Hello! اسماءنا هي محمد، كارولينا، سامي، وداني") t.tokenise( exclude: [ :ascii_only?, /محمد/, ->(t) { t.length > 6}, "و" ] ) # => ["هي", "سامي", "وداني"] @param [Regexp] pattern The string to tokenise @param [Array<String, Regexp, Lambda, Symbol>, String, Regexp, Lambda, Symbol, nil] exclude The filter to apply @return [Array] The array of filtered tokens
[ "Initialises", "state", "with", "the", "string", "to", "be", "tokenised", "." ]
5f3ea74249e05f22e16e097ce7cf9b940887e0ae
https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/tokeniser.rb#L97-L100
17,070
abitdodgy/words_counted
lib/words_counted/tokeniser.rb
WordsCounted.Tokeniser.filter_to_proc
def filter_to_proc(filter) if filter.respond_to?(:to_a) filter_procs_from_array(filter) elsif filter.respond_to?(:to_str) filter_proc_from_string(filter) elsif regexp_filter = Regexp.try_convert(filter) ->(token) { token =~ regexp_filter } elsif filter.respond_to?(:to_proc) filter.to_proc else raise ArgumentError, "`filter` must be a `String`, `Regexp`, `lambda`, `Symbol`, or an `Array` of any combination of those types" end end
ruby
def filter_to_proc(filter) if filter.respond_to?(:to_a) filter_procs_from_array(filter) elsif filter.respond_to?(:to_str) filter_proc_from_string(filter) elsif regexp_filter = Regexp.try_convert(filter) ->(token) { token =~ regexp_filter } elsif filter.respond_to?(:to_proc) filter.to_proc else raise ArgumentError, "`filter` must be a `String`, `Regexp`, `lambda`, `Symbol`, or an `Array` of any combination of those types" end end
[ "def", "filter_to_proc", "(", "filter", ")", "if", "filter", ".", "respond_to?", "(", ":to_a", ")", "filter_procs_from_array", "(", "filter", ")", "elsif", "filter", ".", "respond_to?", "(", ":to_str", ")", "filter_proc_from_string", "(", "filter", ")", "elsif", "regexp_filter", "=", "Regexp", ".", "try_convert", "(", "filter", ")", "->", "(", "token", ")", "{", "token", "=~", "regexp_filter", "}", "elsif", "filter", ".", "respond_to?", "(", ":to_proc", ")", "filter", ".", "to_proc", "else", "raise", "ArgumentError", ",", "\"`filter` must be a `String`, `Regexp`, `lambda`, `Symbol`, or an `Array` of any combination of those types\"", "end", "end" ]
The following methods convert any arguments into a callable object. The return value of this lambda is then used to determine whether a token should be excluded from the final list. `filter` can be a string, a regular expression, a lambda, a symbol, or an array of any combination of those types. If `filter` is a string, it converts the string into an array, and returns a lambda that returns true if the token is included in the resulting array. @see {Tokeniser#filter_proc_from_string}. If `filter` is a an array, it creates a new array where each element of the origingal is converted to a lambda, and returns a lambda that calls each lambda in the resulting array. If any lambda returns true the token is excluded from the final list. @see {Tokeniser#filter_procs_from_array}. If `filter` is a proc, then the proc is simply called. If `filter` is a regexp, a `lambda` is returned that checks the token for a match. If a symbol is passed, it is converted to a proc. The symbol must name a predicate method. This method depends on `nil` responding `to_a` with an empty array, which avoids having to check if `exclude` was passed. @api private
[ "The", "following", "methods", "convert", "any", "arguments", "into", "a", "callable", "object", ".", "The", "return", "value", "of", "this", "lambda", "is", "then", "used", "to", "determine", "whether", "a", "token", "should", "be", "excluded", "from", "the", "final", "list", "." ]
5f3ea74249e05f22e16e097ce7cf9b940887e0ae
https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/tokeniser.rb#L130-L145
17,071
contentful/contentful_model
lib/contentful_model.rb
ContentfulModel.Configuration.to_hash
def to_hash Hash[instance_variables.map { |name| [name.to_s.delete('@').to_sym, instance_variable_get(name)] }] end
ruby
def to_hash Hash[instance_variables.map { |name| [name.to_s.delete('@').to_sym, instance_variable_get(name)] }] end
[ "def", "to_hash", "Hash", "[", "instance_variables", ".", "map", "{", "|", "name", "|", "[", "name", ".", "to_s", ".", "delete", "(", "'@'", ")", ".", "to_sym", ",", "instance_variable_get", "(", "name", ")", "]", "}", "]", "end" ]
Return the Configuration object as a hash, with symbols as keys. @return [Hash]
[ "Return", "the", "Configuration", "object", "as", "a", "hash", "with", "symbols", "as", "keys", "." ]
b286afd939daae87fdeb1f320f43753dcaae3144
https://github.com/contentful/contentful_model/blob/b286afd939daae87fdeb1f320f43753dcaae3144/lib/contentful_model.rb#L51-L53
17,072
jkraemer/pdf-forms
lib/pdf_forms/pdftk_wrapper.rb
PdfForms.PdftkWrapper.cat
def cat(*args) in_files = [] page_ranges = [] file_handle = "A" output = normalize_path args.pop args.flatten.compact.each do |in_file| if in_file.is_a? Hash path = in_file.keys.first page_ranges.push *in_file.values.first.map {|range| "#{file_handle}#{range}"} else path = in_file page_ranges.push "#{file_handle}" end in_files.push "#{file_handle}=#{normalize_path(path)}" file_handle.next! end call_pdftk in_files, 'cat', page_ranges, 'output', output end
ruby
def cat(*args) in_files = [] page_ranges = [] file_handle = "A" output = normalize_path args.pop args.flatten.compact.each do |in_file| if in_file.is_a? Hash path = in_file.keys.first page_ranges.push *in_file.values.first.map {|range| "#{file_handle}#{range}"} else path = in_file page_ranges.push "#{file_handle}" end in_files.push "#{file_handle}=#{normalize_path(path)}" file_handle.next! end call_pdftk in_files, 'cat', page_ranges, 'output', output end
[ "def", "cat", "(", "*", "args", ")", "in_files", "=", "[", "]", "page_ranges", "=", "[", "]", "file_handle", "=", "\"A\"", "output", "=", "normalize_path", "args", ".", "pop", "args", ".", "flatten", ".", "compact", ".", "each", "do", "|", "in_file", "|", "if", "in_file", ".", "is_a?", "Hash", "path", "=", "in_file", ".", "keys", ".", "first", "page_ranges", ".", "push", "in_file", ".", "values", ".", "first", ".", "map", "{", "|", "range", "|", "\"#{file_handle}#{range}\"", "}", "else", "path", "=", "in_file", "page_ranges", ".", "push", "\"#{file_handle}\"", "end", "in_files", ".", "push", "\"#{file_handle}=#{normalize_path(path)}\"", "file_handle", ".", "next!", "end", "call_pdftk", "in_files", ",", "'cat'", ",", "page_ranges", ",", "'output'", ",", "output", "end" ]
concatenate documents, can optionally specify page ranges args: in_file1, {in_file2 => ["1-2", "4-10"]}, ... , in_file_n, output
[ "concatenate", "documents", "can", "optionally", "specify", "page", "ranges" ]
34518c762a52494893125dad9dc504eac2f88af3
https://github.com/jkraemer/pdf-forms/blob/34518c762a52494893125dad9dc504eac2f88af3/lib/pdf_forms/pdftk_wrapper.rb#L94-L113
17,073
jkraemer/pdf-forms
lib/pdf_forms/data_format.rb
PdfForms.DataFormat.to_pdf_data
def to_pdf_data pdf_data = header @data.each do |key, value| if Hash === value value.each do |sub_key, sub_value| pdf_data << field("#{key}_#{sub_key}", sub_value) end else pdf_data << field(key, value) end end pdf_data << footer return encode_data(pdf_data) end
ruby
def to_pdf_data pdf_data = header @data.each do |key, value| if Hash === value value.each do |sub_key, sub_value| pdf_data << field("#{key}_#{sub_key}", sub_value) end else pdf_data << field(key, value) end end pdf_data << footer return encode_data(pdf_data) end
[ "def", "to_pdf_data", "pdf_data", "=", "header", "@data", ".", "each", "do", "|", "key", ",", "value", "|", "if", "Hash", "===", "value", "value", ".", "each", "do", "|", "sub_key", ",", "sub_value", "|", "pdf_data", "<<", "field", "(", "\"#{key}_#{sub_key}\"", ",", "sub_value", ")", "end", "else", "pdf_data", "<<", "field", "(", "key", ",", "value", ")", "end", "end", "pdf_data", "<<", "footer", "return", "encode_data", "(", "pdf_data", ")", "end" ]
generate PDF content in this data format
[ "generate", "PDF", "content", "in", "this", "data", "format" ]
34518c762a52494893125dad9dc504eac2f88af3
https://github.com/jkraemer/pdf-forms/blob/34518c762a52494893125dad9dc504eac2f88af3/lib/pdf_forms/data_format.rb#L17-L32
17,074
piotrmurach/tty-spinner
lib/tty/spinner.rb
TTY.Spinner.auto_spin
def auto_spin CURSOR_LOCK.synchronize do start sleep_time = 1.0 / @interval spin @thread = Thread.new do sleep(sleep_time) while @started_at if Thread.current['pause'] Thread.stop Thread.current['pause'] = false end spin sleep(sleep_time) end end end ensure if @hide_cursor write(TTY::Cursor.show, false) end end
ruby
def auto_spin CURSOR_LOCK.synchronize do start sleep_time = 1.0 / @interval spin @thread = Thread.new do sleep(sleep_time) while @started_at if Thread.current['pause'] Thread.stop Thread.current['pause'] = false end spin sleep(sleep_time) end end end ensure if @hide_cursor write(TTY::Cursor.show, false) end end
[ "def", "auto_spin", "CURSOR_LOCK", ".", "synchronize", "do", "start", "sleep_time", "=", "1.0", "/", "@interval", "spin", "@thread", "=", "Thread", ".", "new", "do", "sleep", "(", "sleep_time", ")", "while", "@started_at", "if", "Thread", ".", "current", "[", "'pause'", "]", "Thread", ".", "stop", "Thread", ".", "current", "[", "'pause'", "]", "=", "false", "end", "spin", "sleep", "(", "sleep_time", ")", "end", "end", "end", "ensure", "if", "@hide_cursor", "write", "(", "TTY", "::", "Cursor", ".", "show", ",", "false", ")", "end", "end" ]
Start automatic spinning animation @api public
[ "Start", "automatic", "spinning", "animation" ]
876449a4a10831b38aedd92004592efe417c6377
https://github.com/piotrmurach/tty-spinner/blob/876449a4a10831b38aedd92004592efe417c6377/lib/tty/spinner.rb#L240-L262
17,075
piotrmurach/tty-spinner
lib/tty/spinner.rb
TTY.Spinner.run
def run(stop_message = '', &block) job(&block) auto_spin @work = Thread.new { execute_job } @work.join ensure stop(stop_message) end
ruby
def run(stop_message = '', &block) job(&block) auto_spin @work = Thread.new { execute_job } @work.join ensure stop(stop_message) end
[ "def", "run", "(", "stop_message", "=", "''", ",", "&", "block", ")", "job", "(", "block", ")", "auto_spin", "@work", "=", "Thread", ".", "new", "{", "execute_job", "}", "@work", ".", "join", "ensure", "stop", "(", "stop_message", ")", "end" ]
Run spinner while executing job @param [String] stop_message the message displayed when block is finished @yield automatically animate and finish spinner @example spinner.run('Migrated DB') { ... } @api public
[ "Run", "spinner", "while", "executing", "job" ]
876449a4a10831b38aedd92004592efe417c6377
https://github.com/piotrmurach/tty-spinner/blob/876449a4a10831b38aedd92004592efe417c6377/lib/tty/spinner.rb#L304-L312
17,076
piotrmurach/tty-spinner
lib/tty/spinner.rb
TTY.Spinner.spin
def spin synchronize do return if @done emit(:spin) if @hide_cursor && !spinning? write(TTY::Cursor.hide) end data = message.gsub(MATCHER, @frames[@current]) data = replace_tokens(data) write(data, true) @current = (@current + 1) % @length @state = :spinning data end end
ruby
def spin synchronize do return if @done emit(:spin) if @hide_cursor && !spinning? write(TTY::Cursor.hide) end data = message.gsub(MATCHER, @frames[@current]) data = replace_tokens(data) write(data, true) @current = (@current + 1) % @length @state = :spinning data end end
[ "def", "spin", "synchronize", "do", "return", "if", "@done", "emit", "(", ":spin", ")", "if", "@hide_cursor", "&&", "!", "spinning?", "write", "(", "TTY", "::", "Cursor", ".", "hide", ")", "end", "data", "=", "message", ".", "gsub", "(", "MATCHER", ",", "@frames", "[", "@current", "]", ")", "data", "=", "replace_tokens", "(", "data", ")", "write", "(", "data", ",", "true", ")", "@current", "=", "(", "@current", "+", "1", ")", "%", "@length", "@state", "=", ":spinning", "data", "end", "end" ]
Perform a spin @return [String] the printed data @api public
[ "Perform", "a", "spin" ]
876449a4a10831b38aedd92004592efe417c6377
https://github.com/piotrmurach/tty-spinner/blob/876449a4a10831b38aedd92004592efe417c6377/lib/tty/spinner.rb#L352-L368
17,077
piotrmurach/tty-spinner
lib/tty/spinner.rb
TTY.Spinner.fetch_format
def fetch_format(token, property) if FORMATS.key?(token) FORMATS[token][property] else raise ArgumentError, "Unknown format token `:#{token}`" end end
ruby
def fetch_format(token, property) if FORMATS.key?(token) FORMATS[token][property] else raise ArgumentError, "Unknown format token `:#{token}`" end end
[ "def", "fetch_format", "(", "token", ",", "property", ")", "if", "FORMATS", ".", "key?", "(", "token", ")", "FORMATS", "[", "token", "]", "[", "property", "]", "else", "raise", "ArgumentError", ",", "\"Unknown format token `:#{token}`\"", "end", "end" ]
Find frames by token name @param [Symbol] token the name for the frames @return [Array, String] @api private
[ "Find", "frames", "by", "token", "name" ]
876449a4a10831b38aedd92004592efe417c6377
https://github.com/piotrmurach/tty-spinner/blob/876449a4a10831b38aedd92004592efe417c6377/lib/tty/spinner.rb#L547-L553
17,078
felixbuenemann/xlsxtream
lib/xlsxtream/row.rb
Xlsxtream.Row.auto_format
def auto_format(value) case value when TRUE_STRING true when FALSE_STRING false when NUMBER_PATTERN value.include?('.') ? value.to_f : value.to_i when DATE_PATTERN Date.parse(value) rescue value when TIME_PATTERN DateTime.parse(value) rescue value else value end end
ruby
def auto_format(value) case value when TRUE_STRING true when FALSE_STRING false when NUMBER_PATTERN value.include?('.') ? value.to_f : value.to_i when DATE_PATTERN Date.parse(value) rescue value when TIME_PATTERN DateTime.parse(value) rescue value else value end end
[ "def", "auto_format", "(", "value", ")", "case", "value", "when", "TRUE_STRING", "true", "when", "FALSE_STRING", "false", "when", "NUMBER_PATTERN", "value", ".", "include?", "(", "'.'", ")", "?", "value", ".", "to_f", ":", "value", ".", "to_i", "when", "DATE_PATTERN", "Date", ".", "parse", "(", "value", ")", "rescue", "value", "when", "TIME_PATTERN", "DateTime", ".", "parse", "(", "value", ")", "rescue", "value", "else", "value", "end", "end" ]
Detects and casts numbers, date, time in text
[ "Detects", "and", "casts", "numbers", "date", "time", "in", "text" ]
b2e14c9eac716b154f00280041b08a6535abacd1
https://github.com/felixbuenemann/xlsxtream/blob/b2e14c9eac716b154f00280041b08a6535abacd1/lib/xlsxtream/row.rb#L71-L86
17,079
felixbuenemann/xlsxtream
lib/xlsxtream/row.rb
Xlsxtream.Row.time_to_oa_date
def time_to_oa_date(time) time = time.to_time if time.respond_to?(:to_time) # Local dates are stored as UTC by truncating the offset: # 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC # This is done because SpreadsheetML is not timezone aware. (time + time.utc_offset).utc.to_f / 24 / 3600 + 25569 end
ruby
def time_to_oa_date(time) time = time.to_time if time.respond_to?(:to_time) # Local dates are stored as UTC by truncating the offset: # 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC # This is done because SpreadsheetML is not timezone aware. (time + time.utc_offset).utc.to_f / 24 / 3600 + 25569 end
[ "def", "time_to_oa_date", "(", "time", ")", "time", "=", "time", ".", "to_time", "if", "time", ".", "respond_to?", "(", ":to_time", ")", "# Local dates are stored as UTC by truncating the offset:", "# 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC", "# This is done because SpreadsheetML is not timezone aware.", "(", "time", "+", "time", ".", "utc_offset", ")", ".", "utc", ".", "to_f", "/", "24", "/", "3600", "+", "25569", "end" ]
Converts Time objects to OLE Automation Date
[ "Converts", "Time", "objects", "to", "OLE", "Automation", "Date" ]
b2e14c9eac716b154f00280041b08a6535abacd1
https://github.com/felixbuenemann/xlsxtream/blob/b2e14c9eac716b154f00280041b08a6535abacd1/lib/xlsxtream/row.rb#L89-L96
17,080
chef/ffi-yajl
lib/ffi_yajl/map_library_name.rb
FFI_Yajl.MapLibraryName.expanded_library_names
def expanded_library_names library_names.map do |libname| pathname = File.expand_path(File.join(Libyajl2.opt_path, libname)) pathname if File.file?(pathname) end.compact end
ruby
def expanded_library_names library_names.map do |libname| pathname = File.expand_path(File.join(Libyajl2.opt_path, libname)) pathname if File.file?(pathname) end.compact end
[ "def", "expanded_library_names", "library_names", ".", "map", "do", "|", "libname", "|", "pathname", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "Libyajl2", ".", "opt_path", ",", "libname", ")", ")", "pathname", "if", "File", ".", "file?", "(", "pathname", ")", "end", ".", "compact", "end" ]
Array of yajl library names prepended with the libyajl2 path to use to load those directly and bypass the system libyajl by default. Since these are full paths, this API checks to ensure that the file exists on the filesystem. May return an empty array. @api private @return [Array<String>] Array of full paths to libyajl2 gem libraries
[ "Array", "of", "yajl", "library", "names", "prepended", "with", "the", "libyajl2", "path", "to", "use", "to", "load", "those", "directly", "and", "bypass", "the", "system", "libyajl", "by", "default", ".", "Since", "these", "are", "full", "paths", "this", "API", "checks", "to", "ensure", "that", "the", "file", "exists", "on", "the", "filesystem", ".", "May", "return", "an", "empty", "array", "." ]
4b001a89c8c63ef7b39c7fb30a63061add9a44d5
https://github.com/chef/ffi-yajl/blob/4b001a89c8c63ef7b39c7fb30a63061add9a44d5/lib/ffi_yajl/map_library_name.rb#L67-L72
17,081
chef/ffi-yajl
lib/ffi_yajl/map_library_name.rb
FFI_Yajl.MapLibraryName.dlopen_yajl_library
def dlopen_yajl_library found = false ( expanded_library_names + library_names ).each do |libname| begin dlopen(libname) found = true break rescue ArgumentError end end raise "cannot find yajl library for platform" unless found end
ruby
def dlopen_yajl_library found = false ( expanded_library_names + library_names ).each do |libname| begin dlopen(libname) found = true break rescue ArgumentError end end raise "cannot find yajl library for platform" unless found end
[ "def", "dlopen_yajl_library", "found", "=", "false", "(", "expanded_library_names", "+", "library_names", ")", ".", "each", "do", "|", "libname", "|", "begin", "dlopen", "(", "libname", ")", "found", "=", "true", "break", "rescue", "ArgumentError", "end", "end", "raise", "\"cannot find yajl library for platform\"", "unless", "found", "end" ]
Iterate across the expanded library names in the libyajl2-gem and then attempt to load the system libraries. Uses the native dlopen extension that ships in this gem. @api private
[ "Iterate", "across", "the", "expanded", "library", "names", "in", "the", "libyajl2", "-", "gem", "and", "then", "attempt", "to", "load", "the", "system", "libraries", ".", "Uses", "the", "native", "dlopen", "extension", "that", "ships", "in", "this", "gem", "." ]
4b001a89c8c63ef7b39c7fb30a63061add9a44d5
https://github.com/chef/ffi-yajl/blob/4b001a89c8c63ef7b39c7fb30a63061add9a44d5/lib/ffi_yajl/map_library_name.rb#L79-L90
17,082
chef/ffi-yajl
lib/ffi_yajl/map_library_name.rb
FFI_Yajl.MapLibraryName.ffi_open_yajl_library
def ffi_open_yajl_library found = false expanded_library_names.each do |libname| begin ffi_lib libname found = true rescue LoadError end end ffi_lib "yajl" unless found end
ruby
def ffi_open_yajl_library found = false expanded_library_names.each do |libname| begin ffi_lib libname found = true rescue LoadError end end ffi_lib "yajl" unless found end
[ "def", "ffi_open_yajl_library", "found", "=", "false", "expanded_library_names", ".", "each", "do", "|", "libname", "|", "begin", "ffi_lib", "libname", "found", "=", "true", "rescue", "LoadError", "end", "end", "ffi_lib", "\"yajl\"", "unless", "found", "end" ]
Iterate across the expanded library names in the libyajl2-gem and attempt to load them. If they are missing just use `ffi_lib 'yajl'` to accept the FFI default algorithm to find the library. @api private
[ "Iterate", "across", "the", "expanded", "library", "names", "in", "the", "libyajl2", "-", "gem", "and", "attempt", "to", "load", "them", ".", "If", "they", "are", "missing", "just", "use", "ffi_lib", "yajl", "to", "accept", "the", "FFI", "default", "algorithm", "to", "find", "the", "library", "." ]
4b001a89c8c63ef7b39c7fb30a63061add9a44d5
https://github.com/chef/ffi-yajl/blob/4b001a89c8c63ef7b39c7fb30a63061add9a44d5/lib/ffi_yajl/map_library_name.rb#L97-L107
17,083
cookpad/grpc_kit
lib/grpc_kit/server.rb
GrpcKit.Server.graceful_shutdown
def graceful_shutdown(timeout: true) @stopping = true Thread.new do GrpcKit.logger.debug('graceful shutdown') @mutex.synchronize { @sessions.each(&:drain) } begin sec = timeout ? @shutdown_timeout : 0 Timeout.timeout(sec) do sleep 1 until @sessions.empty? end rescue Timeout::Error => _ GrpcKit.logger.error("Graceful shutdown is timeout (#{@shutdown_timeout}sec). Perform shutdown forceibly") shutdown_sessions end end end
ruby
def graceful_shutdown(timeout: true) @stopping = true Thread.new do GrpcKit.logger.debug('graceful shutdown') @mutex.synchronize { @sessions.each(&:drain) } begin sec = timeout ? @shutdown_timeout : 0 Timeout.timeout(sec) do sleep 1 until @sessions.empty? end rescue Timeout::Error => _ GrpcKit.logger.error("Graceful shutdown is timeout (#{@shutdown_timeout}sec). Perform shutdown forceibly") shutdown_sessions end end end
[ "def", "graceful_shutdown", "(", "timeout", ":", "true", ")", "@stopping", "=", "true", "Thread", ".", "new", "do", "GrpcKit", ".", "logger", ".", "debug", "(", "'graceful shutdown'", ")", "@mutex", ".", "synchronize", "{", "@sessions", ".", "each", "(", ":drain", ")", "}", "begin", "sec", "=", "timeout", "?", "@shutdown_timeout", ":", "0", "Timeout", ".", "timeout", "(", "sec", ")", "do", "sleep", "1", "until", "@sessions", ".", "empty?", "end", "rescue", "Timeout", "::", "Error", "=>", "_", "GrpcKit", ".", "logger", ".", "error", "(", "\"Graceful shutdown is timeout (#{@shutdown_timeout}sec). Perform shutdown forceibly\"", ")", "shutdown_sessions", "end", "end", "end" ]
This method is expected to be called in trap context @params timeout [Boolean] timeout error could be raised or not @return [void]
[ "This", "method", "is", "expected", "to", "be", "called", "in", "trap", "context" ]
bc5180e4d05c68c3f85a823418951ef2e22bbb0c
https://github.com/cookpad/grpc_kit/blob/bc5180e4d05c68c3f85a823418951ef2e22bbb0c/lib/grpc_kit/server.rb#L69-L86
17,084
whitequark/ast
lib/ast/node.rb
AST.Node.updated
def updated(type=nil, children=nil, properties=nil) new_type = type || @type new_children = children || @children new_properties = properties || {} if @type == new_type && @children == new_children && properties.nil? self else original_dup.send :initialize, new_type, new_children, new_properties end end
ruby
def updated(type=nil, children=nil, properties=nil) new_type = type || @type new_children = children || @children new_properties = properties || {} if @type == new_type && @children == new_children && properties.nil? self else original_dup.send :initialize, new_type, new_children, new_properties end end
[ "def", "updated", "(", "type", "=", "nil", ",", "children", "=", "nil", ",", "properties", "=", "nil", ")", "new_type", "=", "type", "||", "@type", "new_children", "=", "children", "||", "@children", "new_properties", "=", "properties", "||", "{", "}", "if", "@type", "==", "new_type", "&&", "@children", "==", "new_children", "&&", "properties", ".", "nil?", "self", "else", "original_dup", ".", "send", ":initialize", ",", "new_type", ",", "new_children", ",", "new_properties", "end", "end" ]
Returns a new instance of Node where non-nil arguments replace the corresponding fields of `self`. For example, `Node.new(:foo, [ 1, 2 ]).updated(:bar)` would yield `(bar 1 2)`, and `Node.new(:foo, [ 1, 2 ]).updated(nil, [])` would yield `(foo)`. If the resulting node would be identical to `self`, does nothing. @param [Symbol, nil] type @param [Array, nil] children @param [Hash, nil] properties @return [AST::Node]
[ "Returns", "a", "new", "instance", "of", "Node", "where", "non", "-", "nil", "arguments", "replace", "the", "corresponding", "fields", "of", "self", "." ]
50ff345ab7152bf513865b88e03664570942318b
https://github.com/whitequark/ast/blob/50ff345ab7152bf513865b88e03664570942318b/lib/ast/node.rb#L133-L145
17,085
whitequark/ast
lib/ast/node.rb
AST.Node.to_sexp
def to_sexp(indent=0) indented = " " * indent sexp = "#{indented}(#{fancy_type}" children.each do |child| if child.is_a?(Node) sexp += "\n#{child.to_sexp(indent + 1)}" else sexp += " #{child.inspect}" end end sexp += ")" sexp end
ruby
def to_sexp(indent=0) indented = " " * indent sexp = "#{indented}(#{fancy_type}" children.each do |child| if child.is_a?(Node) sexp += "\n#{child.to_sexp(indent + 1)}" else sexp += " #{child.inspect}" end end sexp += ")" sexp end
[ "def", "to_sexp", "(", "indent", "=", "0", ")", "indented", "=", "\" \"", "*", "indent", "sexp", "=", "\"#{indented}(#{fancy_type}\"", "children", ".", "each", "do", "|", "child", "|", "if", "child", ".", "is_a?", "(", "Node", ")", "sexp", "+=", "\"\\n#{child.to_sexp(indent + 1)}\"", "else", "sexp", "+=", "\" #{child.inspect}\"", "end", "end", "sexp", "+=", "\")\"", "sexp", "end" ]
Converts `self` to a pretty-printed s-expression. @param [Integer] indent Base indentation level. @return [String]
[ "Converts", "self", "to", "a", "pretty", "-", "printed", "s", "-", "expression", "." ]
50ff345ab7152bf513865b88e03664570942318b
https://github.com/whitequark/ast/blob/50ff345ab7152bf513865b88e03664570942318b/lib/ast/node.rb#L185-L200
17,086
whitequark/ast
lib/ast/node.rb
AST.Node.to_sexp_array
def to_sexp_array children_sexp_arrs = children.map do |child| if child.is_a?(Node) child.to_sexp_array else child end end [type, *children_sexp_arrs] end
ruby
def to_sexp_array children_sexp_arrs = children.map do |child| if child.is_a?(Node) child.to_sexp_array else child end end [type, *children_sexp_arrs] end
[ "def", "to_sexp_array", "children_sexp_arrs", "=", "children", ".", "map", "do", "|", "child", "|", "if", "child", ".", "is_a?", "(", "Node", ")", "child", ".", "to_sexp_array", "else", "child", "end", "end", "[", "type", ",", "children_sexp_arrs", "]", "end" ]
Converts `self` to an Array where the first element is the type as a Symbol, and subsequent elements are the same representation of its children. @return [Array<Symbol, [...Array]>]
[ "Converts", "self", "to", "an", "Array", "where", "the", "first", "element", "is", "the", "type", "as", "a", "Symbol", "and", "subsequent", "elements", "are", "the", "same", "representation", "of", "its", "children", "." ]
50ff345ab7152bf513865b88e03664570942318b
https://github.com/whitequark/ast/blob/50ff345ab7152bf513865b88e03664570942318b/lib/ast/node.rb#L235-L245
17,087
stitchfix/pwwka
lib/pwwka/configuration.rb
Pwwka.Configuration.payload_parser
def payload_parser @payload_parser ||= if @receive_raw_payload ->(payload) { payload } else ->(payload) { ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(payload)) } end end
ruby
def payload_parser @payload_parser ||= if @receive_raw_payload ->(payload) { payload } else ->(payload) { ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(payload)) } end end
[ "def", "payload_parser", "@payload_parser", "||=", "if", "@receive_raw_payload", "->", "(", "payload", ")", "{", "payload", "}", "else", "->", "(", "payload", ")", "{", "ActiveSupport", "::", "HashWithIndifferentAccess", ".", "new", "(", "JSON", ".", "parse", "(", "payload", ")", ")", "}", "end", "end" ]
Returns a proc that, when called with the payload, parses it according to the configuration. By default, this will assume the payload is JSON, parse it, and return a HashWithIndifferentAccess.
[ "Returns", "a", "proc", "that", "when", "called", "with", "the", "payload", "parses", "it", "according", "to", "the", "configuration", "." ]
581a5261cabaa3e97cfe286da33ce80ffa2d750a
https://github.com/stitchfix/pwwka/blob/581a5261cabaa3e97cfe286da33ce80ffa2d750a/lib/pwwka/configuration.rb#L131-L139
17,088
stitchfix/pwwka
lib/pwwka/configuration.rb
Pwwka.Configuration.omit_payload_from_log?
def omit_payload_from_log?(level_of_message_with_payload) return true if @receive_raw_payload Pwwka::Logging::LEVELS[Pwwka.configuration.payload_logging.to_sym] > Pwwka::Logging::LEVELS[level_of_message_with_payload.to_sym] end
ruby
def omit_payload_from_log?(level_of_message_with_payload) return true if @receive_raw_payload Pwwka::Logging::LEVELS[Pwwka.configuration.payload_logging.to_sym] > Pwwka::Logging::LEVELS[level_of_message_with_payload.to_sym] end
[ "def", "omit_payload_from_log?", "(", "level_of_message_with_payload", ")", "return", "true", "if", "@receive_raw_payload", "Pwwka", "::", "Logging", "::", "LEVELS", "[", "Pwwka", ".", "configuration", ".", "payload_logging", ".", "to_sym", "]", ">", "Pwwka", "::", "Logging", "::", "LEVELS", "[", "level_of_message_with_payload", ".", "to_sym", "]", "end" ]
True if we should omit the payload from the log ::level_of_message_with_payload the level of the message about to be logged
[ "True", "if", "we", "should", "omit", "the", "payload", "from", "the", "log" ]
581a5261cabaa3e97cfe286da33ce80ffa2d750a
https://github.com/stitchfix/pwwka/blob/581a5261cabaa3e97cfe286da33ce80ffa2d750a/lib/pwwka/configuration.rb#L144-L147
17,089
AirHelp/danger-duplicate_localizable_strings
lib/duplicate_localizable_strings/plugin.rb
Danger.DangerDuplicateLocalizableStrings.localizable_duplicate_entries
def localizable_duplicate_entries localizable_files = (git.modified_files + git.added_files) - git.deleted_files localizable_files.select! { |line| line.end_with?('.strings') } duplicate_entries = [] localizable_files.each do |file| lines = File.readlines(file) # Grab just the keys, translations might be different keys = lines.map { |e| e.split('=').first } # Filter newlines and comments keys = keys.select do |e| e != "\n" && !e.start_with?('/*') && !e.start_with?('//') end # Grab keys that appear more than once duplicate_keys = keys.select { |e| keys.rindex(e) != keys.index(e) } # And make sure we have one entry per duplicate key duplicate_keys = duplicate_keys.uniq duplicate_keys.each do |key| duplicate_entries << { 'file' => file, 'key' => key } end end duplicate_entries end
ruby
def localizable_duplicate_entries localizable_files = (git.modified_files + git.added_files) - git.deleted_files localizable_files.select! { |line| line.end_with?('.strings') } duplicate_entries = [] localizable_files.each do |file| lines = File.readlines(file) # Grab just the keys, translations might be different keys = lines.map { |e| e.split('=').first } # Filter newlines and comments keys = keys.select do |e| e != "\n" && !e.start_with?('/*') && !e.start_with?('//') end # Grab keys that appear more than once duplicate_keys = keys.select { |e| keys.rindex(e) != keys.index(e) } # And make sure we have one entry per duplicate key duplicate_keys = duplicate_keys.uniq duplicate_keys.each do |key| duplicate_entries << { 'file' => file, 'key' => key } end end duplicate_entries end
[ "def", "localizable_duplicate_entries", "localizable_files", "=", "(", "git", ".", "modified_files", "+", "git", ".", "added_files", ")", "-", "git", ".", "deleted_files", "localizable_files", ".", "select!", "{", "|", "line", "|", "line", ".", "end_with?", "(", "'.strings'", ")", "}", "duplicate_entries", "=", "[", "]", "localizable_files", ".", "each", "do", "|", "file", "|", "lines", "=", "File", ".", "readlines", "(", "file", ")", "# Grab just the keys, translations might be different", "keys", "=", "lines", ".", "map", "{", "|", "e", "|", "e", ".", "split", "(", "'='", ")", ".", "first", "}", "# Filter newlines and comments", "keys", "=", "keys", ".", "select", "do", "|", "e", "|", "e", "!=", "\"\\n\"", "&&", "!", "e", ".", "start_with?", "(", "'/*'", ")", "&&", "!", "e", ".", "start_with?", "(", "'//'", ")", "end", "# Grab keys that appear more than once", "duplicate_keys", "=", "keys", ".", "select", "{", "|", "e", "|", "keys", ".", "rindex", "(", "e", ")", "!=", "keys", ".", "index", "(", "e", ")", "}", "# And make sure we have one entry per duplicate key", "duplicate_keys", "=", "duplicate_keys", ".", "uniq", "duplicate_keys", ".", "each", "do", "|", "key", "|", "duplicate_entries", "<<", "{", "'file'", "=>", "file", ",", "'key'", "=>", "key", "}", "end", "end", "duplicate_entries", "end" ]
Returns an array of all detected duplicate entries. An entry is represented by a has with file path under 'file' key and the Localizable.strings key under 'key' key. @return [Array of duplicate Localizable.strings entries]
[ "Returns", "an", "array", "of", "all", "detected", "duplicate", "entries", ".", "An", "entry", "is", "represented", "by", "a", "has", "with", "file", "path", "under", "file", "key", "and", "the", "Localizable", ".", "strings", "key", "under", "key", "key", "." ]
155d82a64bb280d277d9656d2afa2541b0883006
https://github.com/AirHelp/danger-duplicate_localizable_strings/blob/155d82a64bb280d277d9656d2afa2541b0883006/lib/duplicate_localizable_strings/plugin.rb#L20-L47
17,090
nbulaj/proxy_fetcher
lib/proxy_fetcher/document.rb
ProxyFetcher.Document.xpath
def xpath(*args) backend.xpath(*args).map { |node| backend.proxy_node.new(node) } end
ruby
def xpath(*args) backend.xpath(*args).map { |node| backend.proxy_node.new(node) } end
[ "def", "xpath", "(", "*", "args", ")", "backend", ".", "xpath", "(", "args", ")", ".", "map", "{", "|", "node", "|", "backend", ".", "proxy_node", ".", "new", "(", "node", ")", "}", "end" ]
Initialize abstract ProxyFetcher HTML Document @return [Document] Searches elements by XPath selector. @return [Array<ProxyFetcher::Document::Node>] collection of nodes
[ "Initialize", "abstract", "ProxyFetcher", "HTML", "Document" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/document.rb#L36-L38
17,091
nbulaj/proxy_fetcher
lib/proxy_fetcher/document.rb
ProxyFetcher.Document.css
def css(*args) backend.css(*args).map { |node| backend.proxy_node.new(node) } end
ruby
def css(*args) backend.css(*args).map { |node| backend.proxy_node.new(node) } end
[ "def", "css", "(", "*", "args", ")", "backend", ".", "css", "(", "args", ")", ".", "map", "{", "|", "node", "|", "backend", ".", "proxy_node", ".", "new", "(", "node", ")", "}", "end" ]
Searches elements by CSS selector. @return [Array<ProxyFetcher::Document::Node>] collection of nodes
[ "Searches", "elements", "by", "CSS", "selector", "." ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/document.rb#L45-L47
17,092
nbulaj/proxy_fetcher
lib/proxy_fetcher/utils/proxy_validator.rb
ProxyFetcher.ProxyValidator.connectable?
def connectable? ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE @http.head(URL_TO_CHECK, ssl_context: ssl_context).status.success? rescue StandardError false end
ruby
def connectable? ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE @http.head(URL_TO_CHECK, ssl_context: ssl_context).status.success? rescue StandardError false end
[ "def", "connectable?", "ssl_context", "=", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "ssl_context", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "@http", ".", "head", "(", "URL_TO_CHECK", ",", "ssl_context", ":", "ssl_context", ")", ".", "status", ".", "success?", "rescue", "StandardError", "false", "end" ]
Initialize new ProxyValidator instance @param proxy_addr [String] proxy address or IP @param proxy_port [String, Integer] proxy port @return [ProxyValidator] Checks if proxy is connectable (can be used to connect resources via proxy server). @return [Boolean] true if connection to the server using proxy established, otherwise false
[ "Initialize", "new", "ProxyValidator", "instance" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/utils/proxy_validator.rb#L42-L49
17,093
nbulaj/proxy_fetcher
lib/proxy_fetcher/configuration/providers_registry.rb
ProxyFetcher.ProvidersRegistry.class_for
def class_for(provider_name) provider_name = provider_name.to_sym providers.fetch(provider_name) rescue KeyError raise ProxyFetcher::Exceptions::UnknownProvider, provider_name end
ruby
def class_for(provider_name) provider_name = provider_name.to_sym providers.fetch(provider_name) rescue KeyError raise ProxyFetcher::Exceptions::UnknownProvider, provider_name end
[ "def", "class_for", "(", "provider_name", ")", "provider_name", "=", "provider_name", ".", "to_sym", "providers", ".", "fetch", "(", "provider_name", ")", "rescue", "KeyError", "raise", "ProxyFetcher", "::", "Exceptions", "::", "UnknownProvider", ",", "provider_name", "end" ]
Returns a class for specific provider if it is registered in the registry. Otherwise throws an exception. @param provider_name [String, Symbol] provider name @return [Class] provider class @raise [ProxyFetcher::Exceptions::UnknownProvider] provider is unknown
[ "Returns", "a", "class", "for", "specific", "provider", "if", "it", "is", "registered", "in", "the", "registry", ".", "Otherwise", "throws", "an", "exception", "." ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/configuration/providers_registry.rb#L47-L53
17,094
nbulaj/proxy_fetcher
lib/proxy_fetcher/configuration.rb
ProxyFetcher.Configuration.setup_custom_class
def setup_custom_class(klass, required_methods: []) unless klass.respond_to?(*required_methods) raise ProxyFetcher::Exceptions::WrongCustomClass.new(klass, required_methods) end klass end
ruby
def setup_custom_class(klass, required_methods: []) unless klass.respond_to?(*required_methods) raise ProxyFetcher::Exceptions::WrongCustomClass.new(klass, required_methods) end klass end
[ "def", "setup_custom_class", "(", "klass", ",", "required_methods", ":", "[", "]", ")", "unless", "klass", ".", "respond_to?", "(", "required_methods", ")", "raise", "ProxyFetcher", "::", "Exceptions", "::", "WrongCustomClass", ".", "new", "(", "klass", ",", "required_methods", ")", "end", "klass", "end" ]
Checks if custom class has some required class methods
[ "Checks", "if", "custom", "class", "has", "some", "required", "class", "methods" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/configuration.rb#L175-L181
17,095
nbulaj/proxy_fetcher
lib/proxy_fetcher/utils/http_client.rb
ProxyFetcher.HTTPClient.fetch
def fetch response = process_http_request response.body.to_s rescue StandardError => error ProxyFetcher.logger.warn("Failed to process request to #{url} (#{error.message})") '' end
ruby
def fetch response = process_http_request response.body.to_s rescue StandardError => error ProxyFetcher.logger.warn("Failed to process request to #{url} (#{error.message})") '' end
[ "def", "fetch", "response", "=", "process_http_request", "response", ".", "body", ".", "to_s", "rescue", "StandardError", "=>", "error", "ProxyFetcher", ".", "logger", ".", "warn", "(", "\"Failed to process request to #{url} (#{error.message})\"", ")", "''", "end" ]
Initialize HTTP client instance @return [HTTPClient] Fetches resource content by sending HTTP request to it. @return [String] response body
[ "Initialize", "HTTP", "client", "instance" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/utils/http_client.rb#L70-L76
17,096
nbulaj/proxy_fetcher
lib/proxy_fetcher/manager.rb
ProxyFetcher.Manager.refresh_list!
def refresh_list!(filters = nil) @proxies = [] threads = [] lock = Mutex.new ProxyFetcher.config.providers.each do |provider_name| threads << Thread.new do provider = ProxyFetcher::Configuration.providers_registry.class_for(provider_name) provider_filters = filters && filters.fetch(provider_name.to_sym, filters) provider_proxies = provider.fetch_proxies!(provider_filters) lock.synchronize do @proxies.concat(provider_proxies) end end end threads.each(&:join) @proxies end
ruby
def refresh_list!(filters = nil) @proxies = [] threads = [] lock = Mutex.new ProxyFetcher.config.providers.each do |provider_name| threads << Thread.new do provider = ProxyFetcher::Configuration.providers_registry.class_for(provider_name) provider_filters = filters && filters.fetch(provider_name.to_sym, filters) provider_proxies = provider.fetch_proxies!(provider_filters) lock.synchronize do @proxies.concat(provider_proxies) end end end threads.each(&:join) @proxies end
[ "def", "refresh_list!", "(", "filters", "=", "nil", ")", "@proxies", "=", "[", "]", "threads", "=", "[", "]", "lock", "=", "Mutex", ".", "new", "ProxyFetcher", ".", "config", ".", "providers", ".", "each", "do", "|", "provider_name", "|", "threads", "<<", "Thread", ".", "new", "do", "provider", "=", "ProxyFetcher", "::", "Configuration", ".", "providers_registry", ".", "class_for", "(", "provider_name", ")", "provider_filters", "=", "filters", "&&", "filters", ".", "fetch", "(", "provider_name", ".", "to_sym", ",", "filters", ")", "provider_proxies", "=", "provider", ".", "fetch_proxies!", "(", "provider_filters", ")", "lock", ".", "synchronize", "do", "@proxies", ".", "concat", "(", "provider_proxies", ")", "end", "end", "end", "threads", ".", "each", "(", ":join", ")", "@proxies", "end" ]
Initialize ProxyFetcher Manager instance for managing proxies refresh: true - load proxy list from the remote server on initialization refresh: false - just initialize the class, proxy list will be empty ([]) @return [Manager] Update current proxy list using configured providers. @param filters [Hash] providers filters
[ "Initialize", "ProxyFetcher", "Manager", "instance", "for", "managing", "proxies" ]
da2e067acd930886d894490e229ba094f7f5ea53
https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/manager.rb#L31-L52
17,097
zeisler/active_mocker
lib/active_mocker/mock/queries.rb
ActiveMocker.Queries.delete_all
def delete_all(conditions = nil) check_for_limit_scope! collection = conditions.nil? ? to_a.each(&:delete).clear : where(conditions) collection.map(&:delete).count end
ruby
def delete_all(conditions = nil) check_for_limit_scope! collection = conditions.nil? ? to_a.each(&:delete).clear : where(conditions) collection.map(&:delete).count end
[ "def", "delete_all", "(", "conditions", "=", "nil", ")", "check_for_limit_scope!", "collection", "=", "conditions", ".", "nil?", "?", "to_a", ".", "each", "(", ":delete", ")", ".", "clear", ":", "where", "(", "conditions", ")", "collection", ".", "map", "(", ":delete", ")", ".", "count", "end" ]
Deletes the records matching +conditions+ by instantiating each record and calling its +delete+ method. ==== Parameters * +conditions+ - A string, array, or hash that specifies which records to destroy. If omitted, all records are destroyed. ==== Examples PersonMock.destroy_all(status: "inactive") PersonMock.where(age: 0..18).destroy_all If a limit scope is supplied, +delete_all+ raises an ActiveMocker error: Post.limit(100).delete_all # => ActiveMocker::Error: delete_all doesn't support limit scope
[ "Deletes", "the", "records", "matching", "+", "conditions", "+", "by", "instantiating", "each", "record", "and", "calling", "its", "+", "delete", "+", "method", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/queries.rb#L62-L67
17,098
zeisler/active_mocker
lib/active_mocker/mock/queries.rb
ActiveMocker.Queries.find_by
def find_by(conditions = {}) to_a.detect do |record| Find.new(record).is_of(conditions) end end
ruby
def find_by(conditions = {}) to_a.detect do |record| Find.new(record).is_of(conditions) end end
[ "def", "find_by", "(", "conditions", "=", "{", "}", ")", "to_a", ".", "detect", "do", "|", "record", "|", "Find", ".", "new", "(", "record", ")", ".", "is_of", "(", "conditions", ")", "end", "end" ]
Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns <tt>nil</tt>. Post.find_by name: 'Spartacus', rating: 4
[ "Finds", "the", "first", "record", "matching", "the", "specified", "conditions", ".", "There", "is", "no", "implied", "ordering", "so", "if", "order", "matters", "you", "should", "specify", "it", "yourself", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/queries.rb#L192-L196
17,099
zeisler/active_mocker
lib/active_mocker/mock/queries.rb
ActiveMocker.Queries.limit
def limit(num) relation = __new_relation__(all.take(num)) relation.send(:set_from_limit) relation end
ruby
def limit(num) relation = __new_relation__(all.take(num)) relation.send(:set_from_limit) relation end
[ "def", "limit", "(", "num", ")", "relation", "=", "__new_relation__", "(", "all", ".", "take", "(", "num", ")", ")", "relation", ".", "send", "(", ":set_from_limit", ")", "relation", "end" ]
Specifies a limit for the number of records to retrieve. User.limit(10)
[ "Specifies", "a", "limit", "for", "the", "number", "of", "records", "to", "retrieve", "." ]
bb03387df80708817de2f4d7fc9ca2d3f4b161c3
https://github.com/zeisler/active_mocker/blob/bb03387df80708817de2f4d7fc9ca2d3f4b161c3/lib/active_mocker/mock/queries.rb#L268-L272