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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
stevegraham/slanger
lib/slanger/handler.rb
Slanger.Handler.onmessage
def onmessage(msg) msg = Oj.strict_load(msg) msg['data'] = Oj.strict_load(msg['data']) if msg['data'].is_a? String event = msg['event'].gsub(/\Apusher:/, 'pusher_') if event =~ /\Aclient-/ msg['socket_id'] = connection.socket_id Channel.send_client_message msg elsif respond_to? event, true send event, msg end rescue JSON::ParserError error({ code: 5001, message: "Invalid JSON" }) rescue Exception => e error({ code: 500, message: "#{e.message}\n #{e.backtrace.join "\n"}" }) end
ruby
def onmessage(msg) msg = Oj.strict_load(msg) msg['data'] = Oj.strict_load(msg['data']) if msg['data'].is_a? String event = msg['event'].gsub(/\Apusher:/, 'pusher_') if event =~ /\Aclient-/ msg['socket_id'] = connection.socket_id Channel.send_client_message msg elsif respond_to? event, true send event, msg end rescue JSON::ParserError error({ code: 5001, message: "Invalid JSON" }) rescue Exception => e error({ code: 500, message: "#{e.message}\n #{e.backtrace.join "\n"}" }) end
[ "def", "onmessage", "(", "msg", ")", "msg", "=", "Oj", ".", "strict_load", "(", "msg", ")", "msg", "[", "'data'", "]", "=", "Oj", ".", "strict_load", "(", "msg", "[", "'data'", "]", ")", "if", "msg", "[", "'data'", "]", ".", "is_a?", "String", "event", "=", "msg", "[", "'event'", "]", ".", "gsub", "(", "/", "\\A", "/", ",", "'pusher_'", ")", "if", "event", "=~", "/", "\\A", "/", "msg", "[", "'socket_id'", "]", "=", "connection", ".", "socket_id", "Channel", ".", "send_client_message", "msg", "elsif", "respond_to?", "event", ",", "true", "send", "event", ",", "msg", "end", "rescue", "JSON", "::", "ParserError", "error", "(", "{", "code", ":", "5001", ",", "message", ":", "\"Invalid JSON\"", "}", ")", "rescue", "Exception", "=>", "e", "error", "(", "{", "code", ":", "500", ",", "message", ":", "\"#{e.message}\\n #{e.backtrace.join \"\\n\"}\"", "}", ")", "end" ]
Dispatches message handling to method with same name as the event name
[ "Dispatches", "message", "handling", "to", "method", "with", "same", "name", "as", "the", "event", "name" ]
f26f80c675dc4d853bce401743779a6959981af1
https://github.com/stevegraham/slanger/blob/f26f80c675dc4d853bce401743779a6959981af1/lib/slanger/handler.rb#L27-L45
train
stevegraham/slanger
lib/slanger/presence_channel.rb
Slanger.PresenceChannel.dispatch
def dispatch(message, channel) if channel =~ /\Aslanger:/ # Messages received from the Redis channel slanger:* carry info on # subscriptions. Update our subscribers accordingly. update_subscribers message else push Oj.dump(message, mode: :compat) end end
ruby
def dispatch(message, channel) if channel =~ /\Aslanger:/ # Messages received from the Redis channel slanger:* carry info on # subscriptions. Update our subscribers accordingly. update_subscribers message else push Oj.dump(message, mode: :compat) end end
[ "def", "dispatch", "(", "message", ",", "channel", ")", "if", "channel", "=~", "/", "\\A", "/", "# Messages received from the Redis channel slanger:* carry info on", "# subscriptions. Update our subscribers accordingly.", "update_subscribers", "message", "else", "push", "Oj", ".", "dump", "(", "message", ",", "mode", ":", ":compat", ")", "end", "end" ]
Send an event received from Redis to the EventMachine channel
[ "Send", "an", "event", "received", "from", "Redis", "to", "the", "EventMachine", "channel" ]
f26f80c675dc4d853bce401743779a6959981af1
https://github.com/stevegraham/slanger/blob/f26f80c675dc4d853bce401743779a6959981af1/lib/slanger/presence_channel.rb#L18-L26
train
JsonApiClient/json_api_client
lib/json_api_client/schema.rb
JsonApiClient.Schema.add
def add(name, options) @properties[name.to_sym] = Property.new(name.to_sym, options[:type], options[:default]) end
ruby
def add(name, options) @properties[name.to_sym] = Property.new(name.to_sym, options[:type], options[:default]) end
[ "def", "add", "(", "name", ",", "options", ")", "@properties", "[", "name", ".", "to_sym", "]", "=", "Property", ".", "new", "(", "name", ".", "to_sym", ",", "options", "[", ":type", "]", ",", "options", "[", ":default", "]", ")", "end" ]
Add a property to the schema @param name [Symbol] the name of the property @param options [Hash] property options @option options [Symbol] :type The property type @option options [Symbol] :default The default value for the property @return [void]
[ "Add", "a", "property", "to", "the", "schema" ]
e4b763f5579c4fae4b03dcc935b20627f5c14eaa
https://github.com/JsonApiClient/json_api_client/blob/e4b763f5579c4fae4b03dcc935b20627f5c14eaa/lib/json_api_client/schema.rb#L119-L121
train
JsonApiClient/json_api_client
lib/json_api_client/connection.rb
JsonApiClient.Connection.use
def use(middleware, *args, &block) return if faraday.builder.locked? faraday.builder.insert_before(Middleware::ParseJson, middleware, *args, &block) end
ruby
def use(middleware, *args, &block) return if faraday.builder.locked? faraday.builder.insert_before(Middleware::ParseJson, middleware, *args, &block) end
[ "def", "use", "(", "middleware", ",", "*", "args", ",", "&", "block", ")", "return", "if", "faraday", ".", "builder", ".", "locked?", "faraday", ".", "builder", ".", "insert_before", "(", "Middleware", "::", "ParseJson", ",", "middleware", ",", "args", ",", "block", ")", "end" ]
insert middleware before ParseJson - middleware executed in reverse order - inserted middleware will run after json parsed
[ "insert", "middleware", "before", "ParseJson", "-", "middleware", "executed", "in", "reverse", "order", "-", "inserted", "middleware", "will", "run", "after", "json", "parsed" ]
e4b763f5579c4fae4b03dcc935b20627f5c14eaa
https://github.com/JsonApiClient/json_api_client/blob/e4b763f5579c4fae4b03dcc935b20627f5c14eaa/lib/json_api_client/connection.rb#L24-L27
train
JsonApiClient/json_api_client
lib/json_api_client/resource.rb
JsonApiClient.Resource.destroy
def destroy self.last_result_set = self.class.requestor.destroy(self) if last_result_set.has_errors? fill_errors false else mark_as_destroyed! self.relationships.last_result_set = nil _clear_cached_relationships _clear_belongs_to_params true end end
ruby
def destroy self.last_result_set = self.class.requestor.destroy(self) if last_result_set.has_errors? fill_errors false else mark_as_destroyed! self.relationships.last_result_set = nil _clear_cached_relationships _clear_belongs_to_params true end end
[ "def", "destroy", "self", ".", "last_result_set", "=", "self", ".", "class", ".", "requestor", ".", "destroy", "(", "self", ")", "if", "last_result_set", ".", "has_errors?", "fill_errors", "false", "else", "mark_as_destroyed!", "self", ".", "relationships", ".", "last_result_set", "=", "nil", "_clear_cached_relationships", "_clear_belongs_to_params", "true", "end", "end" ]
Try to destroy this resource @return [Boolean] Whether or not the destroy succeeded
[ "Try", "to", "destroy", "this", "resource" ]
e4b763f5579c4fae4b03dcc935b20627f5c14eaa
https://github.com/JsonApiClient/json_api_client/blob/e4b763f5579c4fae4b03dcc935b20627f5c14eaa/lib/json_api_client/resource.rb#L471-L483
train
gjtorikian/html-proofer
lib/html-proofer/url_validator.rb
HTMLProofer.UrlValidator.new_url_query_values?
def new_url_query_values?(uri, paths_with_queries) queries = uri.query_values.keys.join('-') domain_path = extract_domain_path(uri) if paths_with_queries[domain_path].nil? paths_with_queries[domain_path] = [queries] true elsif !paths_with_queries[domain_path].include?(queries) paths_with_queries[domain_path] << queries true else false end end
ruby
def new_url_query_values?(uri, paths_with_queries) queries = uri.query_values.keys.join('-') domain_path = extract_domain_path(uri) if paths_with_queries[domain_path].nil? paths_with_queries[domain_path] = [queries] true elsif !paths_with_queries[domain_path].include?(queries) paths_with_queries[domain_path] << queries true else false end end
[ "def", "new_url_query_values?", "(", "uri", ",", "paths_with_queries", ")", "queries", "=", "uri", ".", "query_values", ".", "keys", ".", "join", "(", "'-'", ")", "domain_path", "=", "extract_domain_path", "(", "uri", ")", "if", "paths_with_queries", "[", "domain_path", "]", ".", "nil?", "paths_with_queries", "[", "domain_path", "]", "=", "[", "queries", "]", "true", "elsif", "!", "paths_with_queries", "[", "domain_path", "]", ".", "include?", "(", "queries", ")", "paths_with_queries", "[", "domain_path", "]", "<<", "queries", "true", "else", "false", "end", "end" ]
remember queries we've seen, ignore future ones
[ "remember", "queries", "we", "ve", "seen", "ignore", "future", "ones" ]
d00955d3b125b9a1649d056bb347ec30e935d847
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/url_validator.rb#L53-L65
train
gjtorikian/html-proofer
lib/html-proofer/url_validator.rb
HTMLProofer.UrlValidator.external_link_checker
def external_link_checker(external_urls) external_urls = Hash[external_urls.sort] count = external_urls.length check_text = pluralize(count, 'external link', 'external links') @logger.log :info, "Checking #{check_text}..." # Route log from Typhoeus/Ethon to our own logger Ethon.logger = @logger establish_queue(external_urls) @hydra.run end
ruby
def external_link_checker(external_urls) external_urls = Hash[external_urls.sort] count = external_urls.length check_text = pluralize(count, 'external link', 'external links') @logger.log :info, "Checking #{check_text}..." # Route log from Typhoeus/Ethon to our own logger Ethon.logger = @logger establish_queue(external_urls) @hydra.run end
[ "def", "external_link_checker", "(", "external_urls", ")", "external_urls", "=", "Hash", "[", "external_urls", ".", "sort", "]", "count", "=", "external_urls", ".", "length", "check_text", "=", "pluralize", "(", "count", ",", "'external link'", ",", "'external links'", ")", "@logger", ".", "log", ":info", ",", "\"Checking #{check_text}...\"", "# Route log from Typhoeus/Ethon to our own logger", "Ethon", ".", "logger", "=", "@logger", "establish_queue", "(", "external_urls", ")", "@hydra", ".", "run", "end" ]
Proofer runs faster if we pull out all the external URLs and run the checks at the end. Otherwise, we're halting the consuming process for every file during `process_files`. In addition, sorting the list lets libcurl keep connections to the same hosts alive. Finally, we'll first make a HEAD request, rather than GETing all the contents. If the HEAD fails, we'll fall back to GET, as some servers are not configured for HEAD. If we've decided to check for hashes, we must do a GET--HEAD is not available as an option.
[ "Proofer", "runs", "faster", "if", "we", "pull", "out", "all", "the", "external", "URLs", "and", "run", "the", "checks", "at", "the", "end", ".", "Otherwise", "we", "re", "halting", "the", "consuming", "process", "for", "every", "file", "during", "process_files", "." ]
d00955d3b125b9a1649d056bb347ec30e935d847
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/url_validator.rb#L90-L103
train
gjtorikian/html-proofer
lib/html-proofer/url_validator.rb
HTMLProofer.UrlValidator.check_hash_in_2xx_response
def check_hash_in_2xx_response(href, effective_url, response, filenames) return false if @options[:only_4xx] return false unless @options[:check_external_hash] return false unless (hash = hash?(href)) body_doc = create_nokogiri(response.body) unencoded_hash = Addressable::URI.unescape(hash) xpath = %(//*[@name="#{hash}"]|/*[@name="#{unencoded_hash}"]|//*[@id="#{hash}"]|//*[@id="#{unencoded_hash}"]) # user-content is a special addition by GitHub. if URI.parse(href).host =~ /github\.com/i xpath << %(|//*[@name="user-content-#{hash}"]|//*[@id="user-content-#{hash}"]) # when linking to a file on GitHub, like #L12-L34, only the first "L" portion # will be identified as a linkable portion if hash =~ /\A(L\d)+/ xpath << %(|//td[@id="#{Regexp.last_match[1]}"]) end end return unless body_doc.xpath(xpath).empty? msg = "External link #{href} failed: #{effective_url} exists, but the hash '#{hash}' does not" add_external_issue(filenames, msg, response.code) @cache.add(href, filenames, response.code, msg) true end
ruby
def check_hash_in_2xx_response(href, effective_url, response, filenames) return false if @options[:only_4xx] return false unless @options[:check_external_hash] return false unless (hash = hash?(href)) body_doc = create_nokogiri(response.body) unencoded_hash = Addressable::URI.unescape(hash) xpath = %(//*[@name="#{hash}"]|/*[@name="#{unencoded_hash}"]|//*[@id="#{hash}"]|//*[@id="#{unencoded_hash}"]) # user-content is a special addition by GitHub. if URI.parse(href).host =~ /github\.com/i xpath << %(|//*[@name="user-content-#{hash}"]|//*[@id="user-content-#{hash}"]) # when linking to a file on GitHub, like #L12-L34, only the first "L" portion # will be identified as a linkable portion if hash =~ /\A(L\d)+/ xpath << %(|//td[@id="#{Regexp.last_match[1]}"]) end end return unless body_doc.xpath(xpath).empty? msg = "External link #{href} failed: #{effective_url} exists, but the hash '#{hash}' does not" add_external_issue(filenames, msg, response.code) @cache.add(href, filenames, response.code, msg) true end
[ "def", "check_hash_in_2xx_response", "(", "href", ",", "effective_url", ",", "response", ",", "filenames", ")", "return", "false", "if", "@options", "[", ":only_4xx", "]", "return", "false", "unless", "@options", "[", ":check_external_hash", "]", "return", "false", "unless", "(", "hash", "=", "hash?", "(", "href", ")", ")", "body_doc", "=", "create_nokogiri", "(", "response", ".", "body", ")", "unencoded_hash", "=", "Addressable", "::", "URI", ".", "unescape", "(", "hash", ")", "xpath", "=", "%(//*[@name=\"#{hash}\"]|/*[@name=\"#{unencoded_hash}\"]|//*[@id=\"#{hash}\"]|//*[@id=\"#{unencoded_hash}\"])", "# user-content is a special addition by GitHub.", "if", "URI", ".", "parse", "(", "href", ")", ".", "host", "=~", "/", "\\.", "/i", "xpath", "<<", "%(|//*[@name=\"user-content-#{hash}\"]|//*[@id=\"user-content-#{hash}\"])", "# when linking to a file on GitHub, like #L12-L34, only the first \"L\" portion", "# will be identified as a linkable portion", "if", "hash", "=~", "/", "\\A", "\\d", "/", "xpath", "<<", "%(|//td[@id=\"#{Regexp.last_match[1]}\"])", "end", "end", "return", "unless", "body_doc", ".", "xpath", "(", "xpath", ")", ".", "empty?", "msg", "=", "\"External link #{href} failed: #{effective_url} exists, but the hash '#{hash}' does not\"", "add_external_issue", "(", "filenames", ",", "msg", ",", "response", ".", "code", ")", "@cache", ".", "add", "(", "href", ",", "filenames", ",", "response", ".", "code", ",", "msg", ")", "true", "end" ]
Even though the response was a success, we may have been asked to check if the hash on the URL exists on the page
[ "Even", "though", "the", "response", "was", "a", "success", "we", "may", "have", "been", "asked", "to", "check", "if", "the", "hash", "on", "the", "URL", "exists", "on", "the", "page" ]
d00955d3b125b9a1649d056bb347ec30e935d847
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/url_validator.rb#L174-L199
train
gjtorikian/html-proofer
lib/html-proofer/runner.rb
HTMLProofer.Runner.check_files
def check_files @external_urls = {} process_files.each do |item| @external_urls.merge!(item[:external_urls]) @failures.concat(item[:failures]) end # TODO: lazy. if we're checking only external links, # we'll just trash all the failed tests. really, we should # just not run those other checks at all. if @options[:external_only] @failures = [] validate_urls elsif !@options[:disable_external] validate_urls end end
ruby
def check_files @external_urls = {} process_files.each do |item| @external_urls.merge!(item[:external_urls]) @failures.concat(item[:failures]) end # TODO: lazy. if we're checking only external links, # we'll just trash all the failed tests. really, we should # just not run those other checks at all. if @options[:external_only] @failures = [] validate_urls elsif !@options[:disable_external] validate_urls end end
[ "def", "check_files", "@external_urls", "=", "{", "}", "process_files", ".", "each", "do", "|", "item", "|", "@external_urls", ".", "merge!", "(", "item", "[", ":external_urls", "]", ")", "@failures", ".", "concat", "(", "item", "[", ":failures", "]", ")", "end", "# TODO: lazy. if we're checking only external links,", "# we'll just trash all the failed tests. really, we should", "# just not run those other checks at all.", "if", "@options", "[", ":external_only", "]", "@failures", "=", "[", "]", "validate_urls", "elsif", "!", "@options", "[", ":disable_external", "]", "validate_urls", "end", "end" ]
Collects any external URLs found in a directory of files. Also collectes every failed test from process_files. Sends the external URLs to Typhoeus for batch processing.
[ "Collects", "any", "external", "URLs", "found", "in", "a", "directory", "of", "files", ".", "Also", "collectes", "every", "failed", "test", "from", "process_files", ".", "Sends", "the", "external", "URLs", "to", "Typhoeus", "for", "batch", "processing", "." ]
d00955d3b125b9a1649d056bb347ec30e935d847
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/runner.rb#L65-L82
train
gjtorikian/html-proofer
lib/html-proofer/runner.rb
HTMLProofer.Runner.process_files
def process_files if @options[:parallel].empty? files.map { |path| check_path(path) } else Parallel.map(files, @options[:parallel]) { |path| check_path(path) } end end
ruby
def process_files if @options[:parallel].empty? files.map { |path| check_path(path) } else Parallel.map(files, @options[:parallel]) { |path| check_path(path) } end end
[ "def", "process_files", "if", "@options", "[", ":parallel", "]", ".", "empty?", "files", ".", "map", "{", "|", "path", "|", "check_path", "(", "path", ")", "}", "else", "Parallel", ".", "map", "(", "files", ",", "@options", "[", ":parallel", "]", ")", "{", "|", "path", "|", "check_path", "(", "path", ")", "}", "end", "end" ]
Walks over each implemented check and runs them on the files, in parallel.
[ "Walks", "over", "each", "implemented", "check", "and", "runs", "them", "on", "the", "files", "in", "parallel", "." ]
d00955d3b125b9a1649d056bb347ec30e935d847
https://github.com/gjtorikian/html-proofer/blob/d00955d3b125b9a1649d056bb347ec30e935d847/lib/html-proofer/runner.rb#L85-L91
train
Fullscreen/yt
lib/yt/request.rb
Yt.Request.set_request_body!
def set_request_body!(request) case @request_format when :json then request.body = (camelize_keys! @body).to_json when :form then request.set_form_data @body when :file then request.body_stream = @body end if @body end
ruby
def set_request_body!(request) case @request_format when :json then request.body = (camelize_keys! @body).to_json when :form then request.set_form_data @body when :file then request.body_stream = @body end if @body end
[ "def", "set_request_body!", "(", "request", ")", "case", "@request_format", "when", ":json", "then", "request", ".", "body", "=", "(", "camelize_keys!", "@body", ")", ".", "to_json", "when", ":form", "then", "request", ".", "set_form_data", "@body", "when", ":file", "then", "request", ".", "body_stream", "=", "@body", "end", "if", "@body", "end" ]
Adds the request body to the request in the appropriate format. if the request body is a JSON Object, transform its keys into camel-case, since this is the common format for JSON APIs.
[ "Adds", "the", "request", "body", "to", "the", "request", "in", "the", "appropriate", "format", ".", "if", "the", "request", "body", "is", "a", "JSON", "Object", "transform", "its", "keys", "into", "camel", "-", "case", "since", "this", "is", "the", "common", "format", "for", "JSON", "APIs", "." ]
bf5c33b977cb162bb7735ad5b80d1abdb5a38215
https://github.com/Fullscreen/yt/blob/bf5c33b977cb162bb7735ad5b80d1abdb5a38215/lib/yt/request.rb#L120-L126
train
Fullscreen/yt
lib/yt/request.rb
Yt.Request.parse_response!
def parse_response! response.body = case @response_format when :xml then Hash.from_xml response.body when :json then JSON response.body end if response.body end
ruby
def parse_response! response.body = case @response_format when :xml then Hash.from_xml response.body when :json then JSON response.body end if response.body end
[ "def", "parse_response!", "response", ".", "body", "=", "case", "@response_format", "when", ":xml", "then", "Hash", ".", "from_xml", "response", ".", "body", "when", ":json", "then", "JSON", "response", ".", "body", "end", "if", "response", ".", "body", "end" ]
Replaces the body of the response with the parsed version of the body, according to the format specified in the Request.
[ "Replaces", "the", "body", "of", "the", "response", "with", "the", "parsed", "version", "of", "the", "body", "according", "to", "the", "format", "specified", "in", "the", "Request", "." ]
bf5c33b977cb162bb7735ad5b80d1abdb5a38215
https://github.com/Fullscreen/yt/blob/bf5c33b977cb162bb7735ad5b80d1abdb5a38215/lib/yt/request.rb#L183-L188
train
Fullscreen/yt
lib/yt/request.rb
Yt.Request.server_errors
def server_errors [ OpenSSL::SSL::SSLError, Errno::ETIMEDOUT, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ECONNRESET, Net::OpenTimeout, SocketError, Net::HTTPServerError ] + extra_server_errors end
ruby
def server_errors [ OpenSSL::SSL::SSLError, Errno::ETIMEDOUT, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ECONNRESET, Net::OpenTimeout, SocketError, Net::HTTPServerError ] + extra_server_errors end
[ "def", "server_errors", "[", "OpenSSL", "::", "SSL", "::", "SSLError", ",", "Errno", "::", "ETIMEDOUT", ",", "Errno", "::", "EHOSTUNREACH", ",", "Errno", "::", "ENETUNREACH", ",", "Errno", "::", "ECONNRESET", ",", "Net", "::", "OpenTimeout", ",", "SocketError", ",", "Net", "::", "HTTPServerError", "]", "+", "extra_server_errors", "end" ]
Returns the list of server errors worth retrying the request once.
[ "Returns", "the", "list", "of", "server", "errors", "worth", "retrying", "the", "request", "once", "." ]
bf5c33b977cb162bb7735ad5b80d1abdb5a38215
https://github.com/Fullscreen/yt/blob/bf5c33b977cb162bb7735ad5b80d1abdb5a38215/lib/yt/request.rb#L205-L216
train
deivid-rodriguez/pry-byebug
lib/byebug/processors/pry_processor.rb
Byebug.PryProcessor.perform
def perform(action, options = {}) return unless %i[ backtrace down finish frame next step up ].include?(action) send("perform_#{action}", options) end
ruby
def perform(action, options = {}) return unless %i[ backtrace down finish frame next step up ].include?(action) send("perform_#{action}", options) end
[ "def", "perform", "(", "action", ",", "options", "=", "{", "}", ")", "return", "unless", "%i[", "backtrace", "down", "finish", "frame", "next", "step", "up", "]", ".", "include?", "(", "action", ")", "send", "(", "\"perform_#{action}\"", ",", "options", ")", "end" ]
Set up a number of navigational commands to be performed by Byebug.
[ "Set", "up", "a", "number", "of", "navigational", "commands", "to", "be", "performed", "by", "Byebug", "." ]
d2923e7a1629c2b860a4ea66a71dec09a4a15763
https://github.com/deivid-rodriguez/pry-byebug/blob/d2923e7a1629c2b860a4ea66a71dec09a4a15763/lib/byebug/processors/pry_processor.rb#L45-L57
train
deivid-rodriguez/pry-byebug
lib/byebug/processors/pry_processor.rb
Byebug.PryProcessor.resume_pry
def resume_pry new_binding = frame._binding run do if defined?(@pry) && @pry @pry.repl(new_binding) else @pry = Pry.start_without_pry_byebug(new_binding) end end end
ruby
def resume_pry new_binding = frame._binding run do if defined?(@pry) && @pry @pry.repl(new_binding) else @pry = Pry.start_without_pry_byebug(new_binding) end end end
[ "def", "resume_pry", "new_binding", "=", "frame", ".", "_binding", "run", "do", "if", "defined?", "(", "@pry", ")", "&&", "@pry", "@pry", ".", "repl", "(", "new_binding", ")", "else", "@pry", "=", "Pry", ".", "start_without_pry_byebug", "(", "new_binding", ")", "end", "end", "end" ]
Resume an existing Pry REPL at the paused point.
[ "Resume", "an", "existing", "Pry", "REPL", "at", "the", "paused", "point", "." ]
d2923e7a1629c2b860a4ea66a71dec09a4a15763
https://github.com/deivid-rodriguez/pry-byebug/blob/d2923e7a1629c2b860a4ea66a71dec09a4a15763/lib/byebug/processors/pry_processor.rb#L110-L120
train
haml/haml
lib/haml/engine.rb
Haml.Engine.render
def render(scope = Object.new, locals = {}, &block) parent = scope.instance_variable_defined?(:@haml_buffer) ? scope.instance_variable_get(:@haml_buffer) : nil buffer = Haml::Buffer.new(parent, @options.for_buffer) if scope.is_a?(Binding) scope_object = eval("self", scope) scope = scope_object.instance_eval{binding} if block_given? else scope_object = scope scope = scope_object.instance_eval{binding} end set_locals(locals.merge(:_hamlout => buffer, :_erbout => buffer.buffer), scope, scope_object) scope_object.extend(Haml::Helpers) scope_object.instance_variable_set(:@haml_buffer, buffer) begin eval(@temple_engine.precompiled_with_return_value, scope, @options.filename, @options.line) rescue ::SyntaxError => e raise SyntaxError, e.message end ensure # Get rid of the current buffer scope_object.instance_variable_set(:@haml_buffer, buffer.upper) if buffer end
ruby
def render(scope = Object.new, locals = {}, &block) parent = scope.instance_variable_defined?(:@haml_buffer) ? scope.instance_variable_get(:@haml_buffer) : nil buffer = Haml::Buffer.new(parent, @options.for_buffer) if scope.is_a?(Binding) scope_object = eval("self", scope) scope = scope_object.instance_eval{binding} if block_given? else scope_object = scope scope = scope_object.instance_eval{binding} end set_locals(locals.merge(:_hamlout => buffer, :_erbout => buffer.buffer), scope, scope_object) scope_object.extend(Haml::Helpers) scope_object.instance_variable_set(:@haml_buffer, buffer) begin eval(@temple_engine.precompiled_with_return_value, scope, @options.filename, @options.line) rescue ::SyntaxError => e raise SyntaxError, e.message end ensure # Get rid of the current buffer scope_object.instance_variable_set(:@haml_buffer, buffer.upper) if buffer end
[ "def", "render", "(", "scope", "=", "Object", ".", "new", ",", "locals", "=", "{", "}", ",", "&", "block", ")", "parent", "=", "scope", ".", "instance_variable_defined?", "(", ":@haml_buffer", ")", "?", "scope", ".", "instance_variable_get", "(", ":@haml_buffer", ")", ":", "nil", "buffer", "=", "Haml", "::", "Buffer", ".", "new", "(", "parent", ",", "@options", ".", "for_buffer", ")", "if", "scope", ".", "is_a?", "(", "Binding", ")", "scope_object", "=", "eval", "(", "\"self\"", ",", "scope", ")", "scope", "=", "scope_object", ".", "instance_eval", "{", "binding", "}", "if", "block_given?", "else", "scope_object", "=", "scope", "scope", "=", "scope_object", ".", "instance_eval", "{", "binding", "}", "end", "set_locals", "(", "locals", ".", "merge", "(", ":_hamlout", "=>", "buffer", ",", ":_erbout", "=>", "buffer", ".", "buffer", ")", ",", "scope", ",", "scope_object", ")", "scope_object", ".", "extend", "(", "Haml", "::", "Helpers", ")", "scope_object", ".", "instance_variable_set", "(", ":@haml_buffer", ",", "buffer", ")", "begin", "eval", "(", "@temple_engine", ".", "precompiled_with_return_value", ",", "scope", ",", "@options", ".", "filename", ",", "@options", ".", "line", ")", "rescue", "::", "SyntaxError", "=>", "e", "raise", "SyntaxError", ",", "e", ".", "message", "end", "ensure", "# Get rid of the current buffer", "scope_object", ".", "instance_variable_set", "(", ":@haml_buffer", ",", "buffer", ".", "upper", ")", "if", "buffer", "end" ]
Processes the template and returns the result as a string. `scope` is the context in which the template is evaluated. If it's a `Binding`, Haml uses it as the second argument to `Kernel#eval`; otherwise, Haml just uses its `#instance_eval` context. Note that Haml modifies the evaluation context (either the scope object or the `self` object of the scope binding). It extends {Haml::Helpers}, and various instance variables are set (all prefixed with `haml_`). For example: s = "foobar" Haml::Engine.new("%p= upcase").render(s) #=> "<p>FOOBAR</p>" # s now extends Haml::Helpers s.respond_to?(:html_attrs) #=> true `locals` is a hash of local variables to make available to the template. For example: Haml::Engine.new("%p= foo").render(Object.new, :foo => "Hello, world!") #=> "<p>Hello, world!</p>" If a block is passed to render, that block is run when `yield` is called within the template. Due to some Ruby quirks, if `scope` is a `Binding` object and a block is given, the evaluation context may not be quite what the user expects. In particular, it's equivalent to passing `eval("self", scope)` as `scope`. This won't have an effect in most cases, but if you're relying on local variables defined in the context of `scope`, they won't work. @param scope [Binding, Object] The context in which the template is evaluated @param locals [{Symbol => Object}] Local variables that will be made available to the template @param block [#to_proc] A block that can be yielded to within the template @return [String] The rendered template
[ "Processes", "the", "template", "and", "returns", "the", "result", "as", "a", "string", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/engine.rb#L112-L136
train
haml/haml
lib/haml/engine.rb
Haml.Engine.render_proc
def render_proc(scope = Object.new, *local_names) if scope.is_a?(Binding) scope_object = eval("self", scope) else scope_object = scope scope = scope_object.instance_eval{binding} end begin str = @temple_engine.precompiled_with_ambles(local_names) eval( "Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {}; #{str}}\n", scope, @options.filename, @options.line ) rescue ::SyntaxError => e raise SyntaxError, e.message end end
ruby
def render_proc(scope = Object.new, *local_names) if scope.is_a?(Binding) scope_object = eval("self", scope) else scope_object = scope scope = scope_object.instance_eval{binding} end begin str = @temple_engine.precompiled_with_ambles(local_names) eval( "Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {}; #{str}}\n", scope, @options.filename, @options.line ) rescue ::SyntaxError => e raise SyntaxError, e.message end end
[ "def", "render_proc", "(", "scope", "=", "Object", ".", "new", ",", "*", "local_names", ")", "if", "scope", ".", "is_a?", "(", "Binding", ")", "scope_object", "=", "eval", "(", "\"self\"", ",", "scope", ")", "else", "scope_object", "=", "scope", "scope", "=", "scope_object", ".", "instance_eval", "{", "binding", "}", "end", "begin", "str", "=", "@temple_engine", ".", "precompiled_with_ambles", "(", "local_names", ")", "eval", "(", "\"Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {}; #{str}}\\n\"", ",", "scope", ",", "@options", ".", "filename", ",", "@options", ".", "line", ")", "rescue", "::", "SyntaxError", "=>", "e", "raise", "SyntaxError", ",", "e", ".", "message", "end", "end" ]
Returns a proc that, when called, renders the template and returns the result as a string. `scope` works the same as it does for render. The first argument of the returned proc is a hash of local variable names to values. However, due to an unfortunate Ruby quirk, the local variables which can be assigned must be pre-declared. This is done with the `local_names` argument. For example: # This works Haml::Engine.new("%p= foo").render_proc(Object.new, :foo).call :foo => "Hello!" #=> "<p>Hello!</p>" # This doesn't Haml::Engine.new("%p= foo").render_proc.call :foo => "Hello!" #=> NameError: undefined local variable or method `foo' The proc doesn't take a block; any yields in the template will fail. @param scope [Binding, Object] The context in which the template is evaluated @param local_names [Array<Symbol>] The names of the locals that can be passed to the proc @return [Proc] The proc that will run the template
[ "Returns", "a", "proc", "that", "when", "called", "renders", "the", "template", "and", "returns", "the", "result", "as", "a", "string", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/engine.rb#L163-L182
train
haml/haml
lib/haml/engine.rb
Haml.Engine.def_method
def def_method(object, name, *local_names) method = object.is_a?(Module) ? :module_eval : :instance_eval object.send(method, "def #{name}(_haml_locals = {}); #{@temple_engine.precompiled_with_ambles(local_names)}; end", @options.filename, @options.line) end
ruby
def def_method(object, name, *local_names) method = object.is_a?(Module) ? :module_eval : :instance_eval object.send(method, "def #{name}(_haml_locals = {}); #{@temple_engine.precompiled_with_ambles(local_names)}; end", @options.filename, @options.line) end
[ "def", "def_method", "(", "object", ",", "name", ",", "*", "local_names", ")", "method", "=", "object", ".", "is_a?", "(", "Module", ")", "?", ":module_eval", ":", ":instance_eval", "object", ".", "send", "(", "method", ",", "\"def #{name}(_haml_locals = {}); #{@temple_engine.precompiled_with_ambles(local_names)}; end\"", ",", "@options", ".", "filename", ",", "@options", ".", "line", ")", "end" ]
Defines a method on `object` with the given name that renders the template and returns the result as a string. If `object` is a class or module, the method will instead be defined as an instance method. For example: t = Time.now Haml::Engine.new("%p\n Today's date is\n .date= self.to_s").def_method(t, :render) t.render #=> "<p>\n Today's date is\n <div class='date'>Fri Nov 23 18:28:29 -0800 2007</div>\n</p>\n" Haml::Engine.new(".upcased= upcase").def_method(String, :upcased_div) "foobar".upcased_div #=> "<div class='upcased'>FOOBAR</div>\n" The first argument of the defined method is a hash of local variable names to values. However, due to an unfortunate Ruby quirk, the local variables which can be assigned must be pre-declared. This is done with the `local_names` argument. For example: # This works obj = Object.new Haml::Engine.new("%p= foo").def_method(obj, :render, :foo) obj.render(:foo => "Hello!") #=> "<p>Hello!</p>" # This doesn't obj = Object.new Haml::Engine.new("%p= foo").def_method(obj, :render) obj.render(:foo => "Hello!") #=> NameError: undefined local variable or method `foo' Note that Haml modifies the evaluation context (either the scope object or the `self` object of the scope binding). It extends {Haml::Helpers}, and various instance variables are set (all prefixed with `haml_`). @param object [Object, Module] The object on which to define the method @param name [String, Symbol] The name of the method to define @param local_names [Array<Symbol>] The names of the locals that can be passed to the proc
[ "Defines", "a", "method", "on", "object", "with", "the", "given", "name", "that", "renders", "the", "template", "and", "returns", "the", "result", "as", "a", "string", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/engine.rb#L222-L227
train
haml/haml
lib/haml/attribute_compiler.rb
Haml.AttributeCompiler.compile_attribute_values
def compile_attribute_values(values) if values.map(&:key).uniq.size == 1 compile_attribute(values.first.key, values) else runtime_build(values) end end
ruby
def compile_attribute_values(values) if values.map(&:key).uniq.size == 1 compile_attribute(values.first.key, values) else runtime_build(values) end end
[ "def", "compile_attribute_values", "(", "values", ")", "if", "values", ".", "map", "(", ":key", ")", ".", "uniq", ".", "size", "==", "1", "compile_attribute", "(", "values", ".", "first", ".", "key", ",", "values", ")", "else", "runtime_build", "(", "values", ")", "end", "end" ]
Compiles attribute values with the similar key to Temple expression. @param values [Array<AttributeValue>] whose `key`s are partially or fully the same from left. @return [Array] Temple expression
[ "Compiles", "attribute", "values", "with", "the", "similar", "key", "to", "Temple", "expression", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/attribute_compiler.rb#L104-L110
train
haml/haml
lib/haml/attribute_compiler.rb
Haml.AttributeCompiler.static_build
def static_build(values) hash_content = values.group_by(&:key).map do |key, values_for_key| "#{frozen_string(key)} => #{merged_value(key, values_for_key)}" end.join(', ') arguments = [@is_html, @attr_wrapper, @escape_attrs, @hyphenate_data_attrs] code = "::Haml::AttributeBuilder.build_attributes"\ "(#{arguments.map { |a| Haml::Util.inspect_obj(a) }.join(', ')}, { #{hash_content} })" [:static, eval(code).to_s] end
ruby
def static_build(values) hash_content = values.group_by(&:key).map do |key, values_for_key| "#{frozen_string(key)} => #{merged_value(key, values_for_key)}" end.join(', ') arguments = [@is_html, @attr_wrapper, @escape_attrs, @hyphenate_data_attrs] code = "::Haml::AttributeBuilder.build_attributes"\ "(#{arguments.map { |a| Haml::Util.inspect_obj(a) }.join(', ')}, { #{hash_content} })" [:static, eval(code).to_s] end
[ "def", "static_build", "(", "values", ")", "hash_content", "=", "values", ".", "group_by", "(", ":key", ")", ".", "map", "do", "|", "key", ",", "values_for_key", "|", "\"#{frozen_string(key)} => #{merged_value(key, values_for_key)}\"", "end", ".", "join", "(", "', '", ")", "arguments", "=", "[", "@is_html", ",", "@attr_wrapper", ",", "@escape_attrs", ",", "@hyphenate_data_attrs", "]", "code", "=", "\"::Haml::AttributeBuilder.build_attributes\"", "\"(#{arguments.map { |a| Haml::Util.inspect_obj(a) }.join(', ')}, { #{hash_content} })\"", "[", ":static", ",", "eval", "(", "code", ")", ".", "to_s", "]", "end" ]
Renders attribute values statically. @param values [Array<AttributeValue>] @return [Array] Temple expression
[ "Renders", "attribute", "values", "statically", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/attribute_compiler.rb#L125-L134
train
haml/haml
lib/haml/attribute_compiler.rb
Haml.AttributeCompiler.compile_attribute
def compile_attribute(key, values) if values.all? { |v| Temple::StaticAnalyzer.static?(v.to_literal) } return static_build(values) end case key when 'id', 'class' compile_id_or_class_attribute(key, values) else compile_common_attribute(key, values) end end
ruby
def compile_attribute(key, values) if values.all? { |v| Temple::StaticAnalyzer.static?(v.to_literal) } return static_build(values) end case key when 'id', 'class' compile_id_or_class_attribute(key, values) else compile_common_attribute(key, values) end end
[ "def", "compile_attribute", "(", "key", ",", "values", ")", "if", "values", ".", "all?", "{", "|", "v", "|", "Temple", "::", "StaticAnalyzer", ".", "static?", "(", "v", ".", "to_literal", ")", "}", "return", "static_build", "(", "values", ")", "end", "case", "key", "when", "'id'", ",", "'class'", "compile_id_or_class_attribute", "(", "key", ",", "values", ")", "else", "compile_common_attribute", "(", "key", ",", "values", ")", "end", "end" ]
Compiles attribute values for one key to Temple expression that generates ` key='value'`. @param key [String] @param values [Array<AttributeValue>] @return [Array] Temple expression
[ "Compiles", "attribute", "values", "for", "one", "key", "to", "Temple", "expression", "that", "generates", "key", "=", "value", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/attribute_compiler.rb#L158-L169
train
haml/haml
lib/haml/util.rb
Haml.Util.parse_haml_magic_comment
def parse_haml_magic_comment(str) scanner = StringScanner.new(str.dup.force_encoding(Encoding::ASCII_8BIT)) bom = scanner.scan(/\xEF\xBB\xBF/n) return bom unless scanner.scan(/-\s*#\s*/n) if coding = try_parse_haml_emacs_magic_comment(scanner) return bom, coding end return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in) return bom, scanner[1] end
ruby
def parse_haml_magic_comment(str) scanner = StringScanner.new(str.dup.force_encoding(Encoding::ASCII_8BIT)) bom = scanner.scan(/\xEF\xBB\xBF/n) return bom unless scanner.scan(/-\s*#\s*/n) if coding = try_parse_haml_emacs_magic_comment(scanner) return bom, coding end return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in) return bom, scanner[1] end
[ "def", "parse_haml_magic_comment", "(", "str", ")", "scanner", "=", "StringScanner", ".", "new", "(", "str", ".", "dup", ".", "force_encoding", "(", "Encoding", "::", "ASCII_8BIT", ")", ")", "bom", "=", "scanner", ".", "scan", "(", "/", "\\xEF", "\\xBB", "\\xBF", "/n", ")", "return", "bom", "unless", "scanner", ".", "scan", "(", "/", "\\s", "\\s", "/n", ")", "if", "coding", "=", "try_parse_haml_emacs_magic_comment", "(", "scanner", ")", "return", "bom", ",", "coding", "end", "return", "bom", "unless", "scanner", ".", "scan", "(", "/", "\\s", "\\w", "/in", ")", "return", "bom", ",", "scanner", "[", "1", "]", "end" ]
Parses a magic comment at the beginning of a Haml file. The parsing rules are basically the same as Ruby's. @return [(Boolean, String or nil)] Whether the document begins with a UTF-8 BOM, and the declared encoding of the document (or nil if none is declared)
[ "Parses", "a", "magic", "comment", "at", "the", "beginning", "of", "a", "Haml", "file", ".", "The", "parsing", "rules", "are", "basically", "the", "same", "as", "Ruby", "s", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/util.rb#L233-L243
train
haml/haml
lib/haml/buffer.rb
Haml.Buffer.rstrip!
def rstrip! if capture_position.nil? buffer.rstrip! return end buffer << buffer.slice!(capture_position..-1).rstrip end
ruby
def rstrip! if capture_position.nil? buffer.rstrip! return end buffer << buffer.slice!(capture_position..-1).rstrip end
[ "def", "rstrip!", "if", "capture_position", ".", "nil?", "buffer", ".", "rstrip!", "return", "end", "buffer", "<<", "buffer", ".", "slice!", "(", "capture_position", "..", "-", "1", ")", ".", "rstrip", "end" ]
Remove the whitespace from the right side of the buffer string. Doesn't do anything if we're at the beginning of a capture_haml block.
[ "Remove", "the", "whitespace", "from", "the", "right", "side", "of", "the", "buffer", "string", ".", "Doesn", "t", "do", "anything", "if", "we", "re", "at", "the", "beginning", "of", "a", "capture_haml", "block", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/buffer.rb#L146-L153
train
haml/haml
lib/haml/helpers.rb
Haml.Helpers.preserve
def preserve(input = nil, &block) return preserve(capture_haml(&block)) if block s = input.to_s.chomp("\n") s.gsub!(/\n/, '&#x000A;') s.delete!("\r") s end
ruby
def preserve(input = nil, &block) return preserve(capture_haml(&block)) if block s = input.to_s.chomp("\n") s.gsub!(/\n/, '&#x000A;') s.delete!("\r") s end
[ "def", "preserve", "(", "input", "=", "nil", ",", "&", "block", ")", "return", "preserve", "(", "capture_haml", "(", "block", ")", ")", "if", "block", "s", "=", "input", ".", "to_s", ".", "chomp", "(", "\"\\n\"", ")", "s", ".", "gsub!", "(", "/", "\\n", "/", ",", "'&#x000A;'", ")", "s", ".", "delete!", "(", "\"\\r\"", ")", "s", "end" ]
Takes any string, finds all the newlines, and converts them to HTML entities so they'll render correctly in whitespace-sensitive tags without screwing up the indentation. @overload preserve(input) Escapes newlines within a string. @param input [String] The string within which to escape all newlines @overload preserve Escapes newlines within a block of Haml code. @yield The block within which to escape newlines
[ "Takes", "any", "string", "finds", "all", "the", "newlines", "and", "converts", "them", "to", "HTML", "entities", "so", "they", "ll", "render", "correctly", "in", "whitespace", "-", "sensitive", "tags", "without", "screwing", "up", "the", "indentation", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/helpers.rb#L132-L138
train
haml/haml
lib/haml/helpers.rb
Haml.Helpers.capture_haml
def capture_haml(*args, &block) buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer with_haml_buffer(buffer) do position = haml_buffer.buffer.length haml_buffer.capture_position = position value = block.call(*args) captured = haml_buffer.buffer.slice!(position..-1) if captured == '' and value != haml_buffer.buffer captured = (value.is_a?(String) ? value : nil) end captured end ensure haml_buffer.capture_position = nil end
ruby
def capture_haml(*args, &block) buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer with_haml_buffer(buffer) do position = haml_buffer.buffer.length haml_buffer.capture_position = position value = block.call(*args) captured = haml_buffer.buffer.slice!(position..-1) if captured == '' and value != haml_buffer.buffer captured = (value.is_a?(String) ? value : nil) end captured end ensure haml_buffer.capture_position = nil end
[ "def", "capture_haml", "(", "*", "args", ",", "&", "block", ")", "buffer", "=", "eval", "(", "'if defined? _hamlout then _hamlout else nil end'", ",", "block", ".", "binding", ")", "||", "haml_buffer", "with_haml_buffer", "(", "buffer", ")", "do", "position", "=", "haml_buffer", ".", "buffer", ".", "length", "haml_buffer", ".", "capture_position", "=", "position", "value", "=", "block", ".", "call", "(", "args", ")", "captured", "=", "haml_buffer", ".", "buffer", ".", "slice!", "(", "position", "..", "-", "1", ")", "if", "captured", "==", "''", "and", "value", "!=", "haml_buffer", ".", "buffer", "captured", "=", "(", "value", ".", "is_a?", "(", "String", ")", "?", "value", ":", "nil", ")", "end", "captured", "end", "ensure", "haml_buffer", ".", "capture_position", "=", "nil", "end" ]
Captures the result of a block of Haml code, gets rid of the excess indentation, and returns it as a string. For example, after the following, .foo - foo = capture_haml(13) do |a| %p= a the local variable `foo` would be assigned to `"<p>13</p>\n"`. @param args [Array] Arguments to pass into the block @yield [args] A block of Haml code that will be converted to a string @yieldparam args [Array] `args`
[ "Captures", "the", "result", "of", "a", "block", "of", "Haml", "code", "gets", "rid", "of", "the", "excess", "indentation", "and", "returns", "it", "as", "a", "string", ".", "For", "example", "after", "the", "following" ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/helpers.rb#L372-L390
train
haml/haml
lib/haml/helpers.rb
Haml.Helpers.haml_internal_concat
def haml_internal_concat(text = "", newline = true, indent = true) if haml_buffer.tabulation == 0 haml_buffer.buffer << "#{text}#{"\n" if newline}" else haml_buffer.buffer << %[#{haml_indent if indent}#{text.to_s.gsub("\n", "\n#{haml_indent}")}#{"\n" if newline}] end end
ruby
def haml_internal_concat(text = "", newline = true, indent = true) if haml_buffer.tabulation == 0 haml_buffer.buffer << "#{text}#{"\n" if newline}" else haml_buffer.buffer << %[#{haml_indent if indent}#{text.to_s.gsub("\n", "\n#{haml_indent}")}#{"\n" if newline}] end end
[ "def", "haml_internal_concat", "(", "text", "=", "\"\"", ",", "newline", "=", "true", ",", "indent", "=", "true", ")", "if", "haml_buffer", ".", "tabulation", "==", "0", "haml_buffer", ".", "buffer", "<<", "\"#{text}#{\"\\n\" if newline}\"", "else", "haml_buffer", ".", "buffer", "<<", "%[#{haml_indent if indent}#{text.to_s.gsub(\"\\n\", \"\\n#{haml_indent}\")}#{\"\\n\" if newline}]", "end", "end" ]
Internal method to write directly to the buffer with control of whether the first line should be indented, and if there should be a final newline. Lines added will have the proper indentation. This can be controlled for the first line. Used by #haml_concat and #haml_tag. @param text [#to_s] The text to output @param newline [Boolean] Whether to add a newline after the text @param indent [Boolean] Whether to add indentation to the first line
[ "Internal", "method", "to", "write", "directly", "to", "the", "buffer", "with", "control", "of", "whether", "the", "first", "line", "should", "be", "indented", "and", "if", "there", "should", "be", "a", "final", "newline", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/helpers.rb#L412-L418
train
haml/haml
lib/haml/helpers.rb
Haml.Helpers.with_haml_buffer
def with_haml_buffer(buffer) @haml_buffer, old_buffer = buffer, @haml_buffer old_buffer.active, old_was_active = false, old_buffer.active? if old_buffer @haml_buffer.active, was_active = true, @haml_buffer.active? yield ensure @haml_buffer.active = was_active old_buffer.active = old_was_active if old_buffer @haml_buffer = old_buffer end
ruby
def with_haml_buffer(buffer) @haml_buffer, old_buffer = buffer, @haml_buffer old_buffer.active, old_was_active = false, old_buffer.active? if old_buffer @haml_buffer.active, was_active = true, @haml_buffer.active? yield ensure @haml_buffer.active = was_active old_buffer.active = old_was_active if old_buffer @haml_buffer = old_buffer end
[ "def", "with_haml_buffer", "(", "buffer", ")", "@haml_buffer", ",", "old_buffer", "=", "buffer", ",", "@haml_buffer", "old_buffer", ".", "active", ",", "old_was_active", "=", "false", ",", "old_buffer", ".", "active?", "if", "old_buffer", "@haml_buffer", ".", "active", ",", "was_active", "=", "true", ",", "@haml_buffer", ".", "active?", "yield", "ensure", "@haml_buffer", ".", "active", "=", "was_active", "old_buffer", ".", "active", "=", "old_was_active", "if", "old_buffer", "@haml_buffer", "=", "old_buffer", "end" ]
Runs a block of code with the given buffer as the currently active buffer. @param buffer [Haml::Buffer] The Haml buffer to use temporarily @yield A block in which the given buffer should be used
[ "Runs", "a", "block", "of", "code", "with", "the", "given", "buffer", "as", "the", "currently", "active", "buffer", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/helpers.rb#L659-L668
train
haml/haml
lib/haml/helpers.rb
Haml.Helpers.haml_bind_proc
def haml_bind_proc(&proc) _hamlout = haml_buffer #double assignment is to avoid warnings _erbout = _erbout = _hamlout.buffer proc { |*args| proc.call(*args) } end
ruby
def haml_bind_proc(&proc) _hamlout = haml_buffer #double assignment is to avoid warnings _erbout = _erbout = _hamlout.buffer proc { |*args| proc.call(*args) } end
[ "def", "haml_bind_proc", "(", "&", "proc", ")", "_hamlout", "=", "haml_buffer", "#double assignment is to avoid warnings", "_erbout", "=", "_erbout", "=", "_hamlout", ".", "buffer", "proc", "{", "|", "*", "args", "|", "proc", ".", "call", "(", "args", ")", "}", "end" ]
Gives a proc the same local `_hamlout` and `_erbout` variables that the current template has. @param proc [#call] The proc to bind @return [Proc] A new proc with the new variables bound
[ "Gives", "a", "proc", "the", "same", "local", "_hamlout", "and", "_erbout", "variables", "that", "the", "current", "template", "has", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/helpers.rb#L682-L687
train
haml/haml
lib/haml/parser.rb
Haml.Parser.process_indent
def process_indent(line) return unless line.tabs <= @template_tabs && @template_tabs > 0 to_close = @template_tabs - line.tabs to_close.times {|i| close unless to_close - 1 - i == 0 && continuation_script?(line.text)} end
ruby
def process_indent(line) return unless line.tabs <= @template_tabs && @template_tabs > 0 to_close = @template_tabs - line.tabs to_close.times {|i| close unless to_close - 1 - i == 0 && continuation_script?(line.text)} end
[ "def", "process_indent", "(", "line", ")", "return", "unless", "line", ".", "tabs", "<=", "@template_tabs", "&&", "@template_tabs", ">", "0", "to_close", "=", "@template_tabs", "-", "line", ".", "tabs", "to_close", ".", "times", "{", "|", "i", "|", "close", "unless", "to_close", "-", "1", "-", "i", "==", "0", "&&", "continuation_script?", "(", "line", ".", "text", ")", "}", "end" ]
Processes and deals with lowering indentation.
[ "Processes", "and", "deals", "with", "lowering", "indentation", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/parser.rb#L233-L238
train
haml/haml
lib/haml/parser.rb
Haml.Parser.process_line
def process_line(line) case line.text[0] when DIV_CLASS; push div(line) when DIV_ID return push plain(line) if %w[{ @ $].include?(line.text[1]) push div(line) when ELEMENT; push tag(line) when COMMENT; push comment(line.text[1..-1].lstrip) when SANITIZE return push plain(line.strip!(3), :escape_html) if line.text[1, 2] == '==' return push script(line.strip!(2), :escape_html) if line.text[1] == SCRIPT return push flat_script(line.strip!(2), :escape_html) if line.text[1] == FLAT_SCRIPT return push plain(line.strip!(1), :escape_html) if line.text[1] == ?\s || line.text[1..2] == '#{' push plain(line) when SCRIPT return push plain(line.strip!(2)) if line.text[1] == SCRIPT line.text = line.text[1..-1] push script(line) when FLAT_SCRIPT; push flat_script(line.strip!(1)) when SILENT_SCRIPT return push haml_comment(line.text[2..-1]) if line.text[1] == SILENT_COMMENT push silent_script(line) when FILTER; push filter(line.text[1..-1].downcase) when DOCTYPE return push doctype(line.text) if line.text[0, 3] == '!!!' return push plain(line.strip!(3), false) if line.text[1, 2] == '==' return push script(line.strip!(2), false) if line.text[1] == SCRIPT return push flat_script(line.strip!(2), false) if line.text[1] == FLAT_SCRIPT return push plain(line.strip!(1), false) if line.text[1] == ?\s || line.text[1..2] == '#{' push plain(line) when ESCAPE line.text = line.text[1..-1] push plain(line) else; push plain(line) end end
ruby
def process_line(line) case line.text[0] when DIV_CLASS; push div(line) when DIV_ID return push plain(line) if %w[{ @ $].include?(line.text[1]) push div(line) when ELEMENT; push tag(line) when COMMENT; push comment(line.text[1..-1].lstrip) when SANITIZE return push plain(line.strip!(3), :escape_html) if line.text[1, 2] == '==' return push script(line.strip!(2), :escape_html) if line.text[1] == SCRIPT return push flat_script(line.strip!(2), :escape_html) if line.text[1] == FLAT_SCRIPT return push plain(line.strip!(1), :escape_html) if line.text[1] == ?\s || line.text[1..2] == '#{' push plain(line) when SCRIPT return push plain(line.strip!(2)) if line.text[1] == SCRIPT line.text = line.text[1..-1] push script(line) when FLAT_SCRIPT; push flat_script(line.strip!(1)) when SILENT_SCRIPT return push haml_comment(line.text[2..-1]) if line.text[1] == SILENT_COMMENT push silent_script(line) when FILTER; push filter(line.text[1..-1].downcase) when DOCTYPE return push doctype(line.text) if line.text[0, 3] == '!!!' return push plain(line.strip!(3), false) if line.text[1, 2] == '==' return push script(line.strip!(2), false) if line.text[1] == SCRIPT return push flat_script(line.strip!(2), false) if line.text[1] == FLAT_SCRIPT return push plain(line.strip!(1), false) if line.text[1] == ?\s || line.text[1..2] == '#{' push plain(line) when ESCAPE line.text = line.text[1..-1] push plain(line) else; push plain(line) end end
[ "def", "process_line", "(", "line", ")", "case", "line", ".", "text", "[", "0", "]", "when", "DIV_CLASS", ";", "push", "div", "(", "line", ")", "when", "DIV_ID", "return", "push", "plain", "(", "line", ")", "if", "%w[", "{", "@", "$", "]", ".", "include?", "(", "line", ".", "text", "[", "1", "]", ")", "push", "div", "(", "line", ")", "when", "ELEMENT", ";", "push", "tag", "(", "line", ")", "when", "COMMENT", ";", "push", "comment", "(", "line", ".", "text", "[", "1", "..", "-", "1", "]", ".", "lstrip", ")", "when", "SANITIZE", "return", "push", "plain", "(", "line", ".", "strip!", "(", "3", ")", ",", ":escape_html", ")", "if", "line", ".", "text", "[", "1", ",", "2", "]", "==", "'=='", "return", "push", "script", "(", "line", ".", "strip!", "(", "2", ")", ",", ":escape_html", ")", "if", "line", ".", "text", "[", "1", "]", "==", "SCRIPT", "return", "push", "flat_script", "(", "line", ".", "strip!", "(", "2", ")", ",", ":escape_html", ")", "if", "line", ".", "text", "[", "1", "]", "==", "FLAT_SCRIPT", "return", "push", "plain", "(", "line", ".", "strip!", "(", "1", ")", ",", ":escape_html", ")", "if", "line", ".", "text", "[", "1", "]", "==", "?\\s", "||", "line", ".", "text", "[", "1", "..", "2", "]", "==", "'#{'", "push", "plain", "(", "line", ")", "when", "SCRIPT", "return", "push", "plain", "(", "line", ".", "strip!", "(", "2", ")", ")", "if", "line", ".", "text", "[", "1", "]", "==", "SCRIPT", "line", ".", "text", "=", "line", ".", "text", "[", "1", "..", "-", "1", "]", "push", "script", "(", "line", ")", "when", "FLAT_SCRIPT", ";", "push", "flat_script", "(", "line", ".", "strip!", "(", "1", ")", ")", "when", "SILENT_SCRIPT", "return", "push", "haml_comment", "(", "line", ".", "text", "[", "2", "..", "-", "1", "]", ")", "if", "line", ".", "text", "[", "1", "]", "==", "SILENT_COMMENT", "push", "silent_script", "(", "line", ")", "when", "FILTER", ";", "push", "filter", "(", "line", ".", "text", "[", "1", "..", "-", "1", "]", ".", "downcase", ")", "when", "DOCTYPE", "return", "push", "doctype", "(", "line", ".", "text", ")", "if", "line", ".", "text", "[", "0", ",", "3", "]", "==", "'!!!'", "return", "push", "plain", "(", "line", ".", "strip!", "(", "3", ")", ",", "false", ")", "if", "line", ".", "text", "[", "1", ",", "2", "]", "==", "'=='", "return", "push", "script", "(", "line", ".", "strip!", "(", "2", ")", ",", "false", ")", "if", "line", ".", "text", "[", "1", "]", "==", "SCRIPT", "return", "push", "flat_script", "(", "line", ".", "strip!", "(", "2", ")", ",", "false", ")", "if", "line", ".", "text", "[", "1", "]", "==", "FLAT_SCRIPT", "return", "push", "plain", "(", "line", ".", "strip!", "(", "1", ")", ",", "false", ")", "if", "line", ".", "text", "[", "1", "]", "==", "?\\s", "||", "line", ".", "text", "[", "1", "..", "2", "]", "==", "'#{'", "push", "plain", "(", "line", ")", "when", "ESCAPE", "line", ".", "text", "=", "line", ".", "text", "[", "1", "..", "-", "1", "]", "push", "plain", "(", "line", ")", "else", ";", "push", "plain", "(", "line", ")", "end", "end" ]
Processes a single line of Haml. This method doesn't return anything; it simply processes the line and adds the appropriate code to `@precompiled`.
[ "Processes", "a", "single", "line", "of", "Haml", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/parser.rb#L252-L287
train
haml/haml
lib/haml/parser.rb
Haml.Parser.comment
def comment(text) if text[0..1] == '![' revealed = true text = text[1..-1] else revealed = false end conditional, text = balance(text, ?[, ?]) if text[0] == ?[ text.strip! if contains_interpolation?(text) parse = true text = unescape_interpolation(text) else parse = false end if block_opened? && !text.empty? raise SyntaxError.new(Haml::Error.message(:illegal_nesting_content), @next_line.index) end ParseNode.new(:comment, @line.index + 1, :conditional => conditional, :text => text, :revealed => revealed, :parse => parse) end
ruby
def comment(text) if text[0..1] == '![' revealed = true text = text[1..-1] else revealed = false end conditional, text = balance(text, ?[, ?]) if text[0] == ?[ text.strip! if contains_interpolation?(text) parse = true text = unescape_interpolation(text) else parse = false end if block_opened? && !text.empty? raise SyntaxError.new(Haml::Error.message(:illegal_nesting_content), @next_line.index) end ParseNode.new(:comment, @line.index + 1, :conditional => conditional, :text => text, :revealed => revealed, :parse => parse) end
[ "def", "comment", "(", "text", ")", "if", "text", "[", "0", "..", "1", "]", "==", "'!['", "revealed", "=", "true", "text", "=", "text", "[", "1", "..", "-", "1", "]", "else", "revealed", "=", "false", "end", "conditional", ",", "text", "=", "balance", "(", "text", ",", "?[", ",", "?]", ")", "if", "text", "[", "0", "]", "==", "?[", "text", ".", "strip!", "if", "contains_interpolation?", "(", "text", ")", "parse", "=", "true", "text", "=", "unescape_interpolation", "(", "text", ")", "else", "parse", "=", "false", "end", "if", "block_opened?", "&&", "!", "text", ".", "empty?", "raise", "SyntaxError", ".", "new", "(", "Haml", "::", "Error", ".", "message", "(", ":illegal_nesting_content", ")", ",", "@next_line", ".", "index", ")", "end", "ParseNode", ".", "new", "(", ":comment", ",", "@line", ".", "index", "+", "1", ",", ":conditional", "=>", "conditional", ",", ":text", "=>", "text", ",", ":revealed", "=>", "revealed", ",", ":parse", "=>", "parse", ")", "end" ]
Renders an XHTML comment.
[ "Renders", "an", "XHTML", "comment", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/parser.rb#L467-L490
train
haml/haml
lib/haml/parser.rb
Haml.Parser.doctype
def doctype(text) raise SyntaxError.new(Error.message(:illegal_nesting_header), @next_line.index) if block_opened? version, type, encoding = text[3..-1].strip.downcase.scan(DOCTYPE_REGEX)[0] ParseNode.new(:doctype, @line.index + 1, :version => version, :type => type, :encoding => encoding) end
ruby
def doctype(text) raise SyntaxError.new(Error.message(:illegal_nesting_header), @next_line.index) if block_opened? version, type, encoding = text[3..-1].strip.downcase.scan(DOCTYPE_REGEX)[0] ParseNode.new(:doctype, @line.index + 1, :version => version, :type => type, :encoding => encoding) end
[ "def", "doctype", "(", "text", ")", "raise", "SyntaxError", ".", "new", "(", "Error", ".", "message", "(", ":illegal_nesting_header", ")", ",", "@next_line", ".", "index", ")", "if", "block_opened?", "version", ",", "type", ",", "encoding", "=", "text", "[", "3", "..", "-", "1", "]", ".", "strip", ".", "downcase", ".", "scan", "(", "DOCTYPE_REGEX", ")", "[", "0", "]", "ParseNode", ".", "new", "(", ":doctype", ",", "@line", ".", "index", "+", "1", ",", ":version", "=>", "version", ",", ":type", "=>", "type", ",", ":encoding", "=>", "encoding", ")", "end" ]
Renders an XHTML doctype or XML shebang.
[ "Renders", "an", "XHTML", "doctype", "or", "XML", "shebang", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/parser.rb#L493-L497
train
haml/haml
lib/haml/parser.rb
Haml.Parser.parse_tag
def parse_tag(text) match = text.scan(/%([-:\w]+)([-:\w.#\@]*)(.+)?/)[0] raise SyntaxError.new(Error.message(:invalid_tag, text)) unless match tag_name, attributes, rest = match if !attributes.empty? && (attributes =~ /[.#](\.|#|\z)/) raise SyntaxError.new(Error.message(:illegal_element)) end new_attributes_hash = old_attributes_hash = last_line = nil object_ref = :nil attributes_hashes = {} while rest && !rest.empty? case rest[0] when ?{ break if old_attributes_hash old_attributes_hash, rest, last_line = parse_old_attributes(rest) attributes_hashes[:old] = old_attributes_hash when ?( break if new_attributes_hash new_attributes_hash, rest, last_line = parse_new_attributes(rest) attributes_hashes[:new] = new_attributes_hash when ?[ break unless object_ref == :nil object_ref, rest = balance(rest, ?[, ?]) else; break end end if rest && !rest.empty? nuke_whitespace, action, value = rest.scan(/(<>|><|[><])?([=\/\~&!])?(.*)?/)[0] if nuke_whitespace nuke_outer_whitespace = nuke_whitespace.include? '>' nuke_inner_whitespace = nuke_whitespace.include? '<' end end if @options.remove_whitespace nuke_outer_whitespace = true nuke_inner_whitespace = true end if value.nil? value = '' else value.strip! end [tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace, nuke_inner_whitespace, action, value, last_line || @line.index + 1] end
ruby
def parse_tag(text) match = text.scan(/%([-:\w]+)([-:\w.#\@]*)(.+)?/)[0] raise SyntaxError.new(Error.message(:invalid_tag, text)) unless match tag_name, attributes, rest = match if !attributes.empty? && (attributes =~ /[.#](\.|#|\z)/) raise SyntaxError.new(Error.message(:illegal_element)) end new_attributes_hash = old_attributes_hash = last_line = nil object_ref = :nil attributes_hashes = {} while rest && !rest.empty? case rest[0] when ?{ break if old_attributes_hash old_attributes_hash, rest, last_line = parse_old_attributes(rest) attributes_hashes[:old] = old_attributes_hash when ?( break if new_attributes_hash new_attributes_hash, rest, last_line = parse_new_attributes(rest) attributes_hashes[:new] = new_attributes_hash when ?[ break unless object_ref == :nil object_ref, rest = balance(rest, ?[, ?]) else; break end end if rest && !rest.empty? nuke_whitespace, action, value = rest.scan(/(<>|><|[><])?([=\/\~&!])?(.*)?/)[0] if nuke_whitespace nuke_outer_whitespace = nuke_whitespace.include? '>' nuke_inner_whitespace = nuke_whitespace.include? '<' end end if @options.remove_whitespace nuke_outer_whitespace = true nuke_inner_whitespace = true end if value.nil? value = '' else value.strip! end [tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace, nuke_inner_whitespace, action, value, last_line || @line.index + 1] end
[ "def", "parse_tag", "(", "text", ")", "match", "=", "text", ".", "scan", "(", "/", "\\w", "\\w", "\\@", "/", ")", "[", "0", "]", "raise", "SyntaxError", ".", "new", "(", "Error", ".", "message", "(", ":invalid_tag", ",", "text", ")", ")", "unless", "match", "tag_name", ",", "attributes", ",", "rest", "=", "match", "if", "!", "attributes", ".", "empty?", "&&", "(", "attributes", "=~", "/", "\\.", "\\z", "/", ")", "raise", "SyntaxError", ".", "new", "(", "Error", ".", "message", "(", ":illegal_element", ")", ")", "end", "new_attributes_hash", "=", "old_attributes_hash", "=", "last_line", "=", "nil", "object_ref", "=", ":nil", "attributes_hashes", "=", "{", "}", "while", "rest", "&&", "!", "rest", ".", "empty?", "case", "rest", "[", "0", "]", "when", "?{", "break", "if", "old_attributes_hash", "old_attributes_hash", ",", "rest", ",", "last_line", "=", "parse_old_attributes", "(", "rest", ")", "attributes_hashes", "[", ":old", "]", "=", "old_attributes_hash", "when", "?(", "break", "if", "new_attributes_hash", "new_attributes_hash", ",", "rest", ",", "last_line", "=", "parse_new_attributes", "(", "rest", ")", "attributes_hashes", "[", ":new", "]", "=", "new_attributes_hash", "when", "?[", "break", "unless", "object_ref", "==", ":nil", "object_ref", ",", "rest", "=", "balance", "(", "rest", ",", "?[", ",", "?]", ")", "else", ";", "break", "end", "end", "if", "rest", "&&", "!", "rest", ".", "empty?", "nuke_whitespace", ",", "action", ",", "value", "=", "rest", ".", "scan", "(", "/", "\\/", "\\~", "/", ")", "[", "0", "]", "if", "nuke_whitespace", "nuke_outer_whitespace", "=", "nuke_whitespace", ".", "include?", "'>'", "nuke_inner_whitespace", "=", "nuke_whitespace", ".", "include?", "'<'", "end", "end", "if", "@options", ".", "remove_whitespace", "nuke_outer_whitespace", "=", "true", "nuke_inner_whitespace", "=", "true", "end", "if", "value", ".", "nil?", "value", "=", "''", "else", "value", ".", "strip!", "end", "[", "tag_name", ",", "attributes", ",", "attributes_hashes", ",", "object_ref", ",", "nuke_outer_whitespace", ",", "nuke_inner_whitespace", ",", "action", ",", "value", ",", "last_line", "||", "@line", ".", "index", "+", "1", "]", "end" ]
Parses a line into tag_name, attributes, attributes_hash, object_ref, action, value
[ "Parses", "a", "line", "into", "tag_name", "attributes", "attributes_hash", "object_ref", "action", "value" ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/parser.rb#L596-L646
train
haml/haml
lib/haml/parser.rb
Haml.Parser.is_multiline?
def is_multiline?(text) text && text.length > 1 && text[-1] == MULTILINE_CHAR_VALUE && text[-2] == ?\s && text !~ BLOCK_WITH_SPACES end
ruby
def is_multiline?(text) text && text.length > 1 && text[-1] == MULTILINE_CHAR_VALUE && text[-2] == ?\s && text !~ BLOCK_WITH_SPACES end
[ "def", "is_multiline?", "(", "text", ")", "text", "&&", "text", ".", "length", ">", "1", "&&", "text", "[", "-", "1", "]", "==", "MULTILINE_CHAR_VALUE", "&&", "text", "[", "-", "2", "]", "==", "?\\s", "&&", "text", "!~", "BLOCK_WITH_SPACES", "end" ]
Checks whether or not `line` is in a multiline sequence.
[ "Checks", "whether", "or", "not", "line", "is", "in", "a", "multiline", "sequence", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/parser.rb#L780-L782
train
haml/haml
lib/haml/compiler.rb
Haml.Compiler.push_silent
def push_silent(text, can_suppress = false) flush_merged_text return if can_suppress && @options.suppress_eval? newline = (text == "end") ? ";" : "\n" @temple << [:code, "#{resolve_newlines}#{text}#{newline}"] @output_line = @output_line + text.count("\n") + newline.count("\n") end
ruby
def push_silent(text, can_suppress = false) flush_merged_text return if can_suppress && @options.suppress_eval? newline = (text == "end") ? ";" : "\n" @temple << [:code, "#{resolve_newlines}#{text}#{newline}"] @output_line = @output_line + text.count("\n") + newline.count("\n") end
[ "def", "push_silent", "(", "text", ",", "can_suppress", "=", "false", ")", "flush_merged_text", "return", "if", "can_suppress", "&&", "@options", ".", "suppress_eval?", "newline", "=", "(", "text", "==", "\"end\"", ")", "?", "\";\"", ":", "\"\\n\"", "@temple", "<<", "[", ":code", ",", "\"#{resolve_newlines}#{text}#{newline}\"", "]", "@output_line", "=", "@output_line", "+", "text", ".", "count", "(", "\"\\n\"", ")", "+", "newline", ".", "count", "(", "\"\\n\"", ")", "end" ]
Evaluates `text` in the context of the scope object, but does not output the result.
[ "Evaluates", "text", "in", "the", "context", "of", "the", "scope", "object", "but", "does", "not", "output", "the", "result", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/compiler.rb#L219-L225
train
haml/haml
lib/haml/compiler.rb
Haml.Compiler.rstrip_buffer!
def rstrip_buffer!(index = -1) last = @to_merge[index] if last.nil? push_silent("_hamlout.rstrip!", false) return end case last.first when :text last[1] = last[1].rstrip if last[1].empty? @to_merge.slice! index rstrip_buffer! index end when :script last[1].gsub!(/\(haml_temp, (.*?)\);$/, '(haml_temp.rstrip, \1);') rstrip_buffer! index - 1 else raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Compiler@to_merge.") end end
ruby
def rstrip_buffer!(index = -1) last = @to_merge[index] if last.nil? push_silent("_hamlout.rstrip!", false) return end case last.first when :text last[1] = last[1].rstrip if last[1].empty? @to_merge.slice! index rstrip_buffer! index end when :script last[1].gsub!(/\(haml_temp, (.*?)\);$/, '(haml_temp.rstrip, \1);') rstrip_buffer! index - 1 else raise SyntaxError.new("[HAML BUG] Undefined entry in Haml::Compiler@to_merge.") end end
[ "def", "rstrip_buffer!", "(", "index", "=", "-", "1", ")", "last", "=", "@to_merge", "[", "index", "]", "if", "last", ".", "nil?", "push_silent", "(", "\"_hamlout.rstrip!\"", ",", "false", ")", "return", "end", "case", "last", ".", "first", "when", ":text", "last", "[", "1", "]", "=", "last", "[", "1", "]", ".", "rstrip", "if", "last", "[", "1", "]", ".", "empty?", "@to_merge", ".", "slice!", "index", "rstrip_buffer!", "index", "end", "when", ":script", "last", "[", "1", "]", ".", "gsub!", "(", "/", "\\(", "\\)", "/", ",", "'(haml_temp.rstrip, \\1);'", ")", "rstrip_buffer!", "index", "-", "1", "else", "raise", "SyntaxError", ".", "new", "(", "\"[HAML BUG] Undefined entry in Haml::Compiler@to_merge.\"", ")", "end", "end" ]
Get rid of and whitespace at the end of the buffer or the merged text
[ "Get", "rid", "of", "and", "whitespace", "at", "the", "end", "of", "the", "buffer", "or", "the", "merged", "text" ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/compiler.rb#L309-L329
train
haml/haml
lib/haml/filters.rb
Haml.Filters.remove_filter
def remove_filter(name) defined.delete name.to_s.downcase if constants.map(&:to_s).include?(name.to_s) remove_const name.to_sym end end
ruby
def remove_filter(name) defined.delete name.to_s.downcase if constants.map(&:to_s).include?(name.to_s) remove_const name.to_sym end end
[ "def", "remove_filter", "(", "name", ")", "defined", ".", "delete", "name", ".", "to_s", ".", "downcase", "if", "constants", ".", "map", "(", ":to_s", ")", ".", "include?", "(", "name", ".", "to_s", ")", "remove_const", "name", ".", "to_sym", "end", "end" ]
Removes a filter from Haml. If the filter was removed, it returns the Module that was removed upon success, or nil on failure. If you try to redefine a filter, Haml will raise an error. Use this method first to explicitly remove the filter before redefining it. @return Module The filter module that has been removed @since 4.0
[ "Removes", "a", "filter", "from", "Haml", ".", "If", "the", "filter", "was", "removed", "it", "returns", "the", "Module", "that", "was", "removed", "upon", "success", "or", "nil", "on", "failure", ".", "If", "you", "try", "to", "redefine", "a", "filter", "Haml", "will", "raise", "an", "error", ".", "Use", "this", "method", "first", "to", "explicitly", "remove", "the", "filter", "before", "redefining", "it", "." ]
9aa0fbe4a91b999978927be569d2ad0cd39076f1
https://github.com/haml/haml/blob/9aa0fbe4a91b999978927be569d2ad0cd39076f1/lib/haml/filters.rb#L68-L73
train
watir/watir
lib/watir/wait.rb
Watir.Waitable.wait_until
def wait_until(depr_timeout = nil, depr_message = nil, timeout: nil, message: nil, interval: nil, **opt, &blk) if depr_message || depr_timeout Watir.logger.deprecate 'Using arguments for #wait_until', 'keywords', ids: [:timeout_arguments] timeout = depr_timeout message = depr_message end message ||= proc { |obj| "waiting for true condition on #{obj.inspect}" } # TODO: Consider throwing argument error for mixing block & options proc = create_proc(opt, &blk) Wait.until(timeout: timeout, message: message, interval: interval, object: self, &proc) self end
ruby
def wait_until(depr_timeout = nil, depr_message = nil, timeout: nil, message: nil, interval: nil, **opt, &blk) if depr_message || depr_timeout Watir.logger.deprecate 'Using arguments for #wait_until', 'keywords', ids: [:timeout_arguments] timeout = depr_timeout message = depr_message end message ||= proc { |obj| "waiting for true condition on #{obj.inspect}" } # TODO: Consider throwing argument error for mixing block & options proc = create_proc(opt, &blk) Wait.until(timeout: timeout, message: message, interval: interval, object: self, &proc) self end
[ "def", "wait_until", "(", "depr_timeout", "=", "nil", ",", "depr_message", "=", "nil", ",", "timeout", ":", "nil", ",", "message", ":", "nil", ",", "interval", ":", "nil", ",", "**", "opt", ",", "&", "blk", ")", "if", "depr_message", "||", "depr_timeout", "Watir", ".", "logger", ".", "deprecate", "'Using arguments for #wait_until'", ",", "'keywords'", ",", "ids", ":", "[", ":timeout_arguments", "]", "timeout", "=", "depr_timeout", "message", "=", "depr_message", "end", "message", "||=", "proc", "{", "|", "obj", "|", "\"waiting for true condition on #{obj.inspect}\"", "}", "# TODO: Consider throwing argument error for mixing block & options", "proc", "=", "create_proc", "(", "opt", ",", "blk", ")", "Wait", ".", "until", "(", "timeout", ":", "timeout", ",", "message", ":", "message", ",", "interval", ":", "interval", ",", "object", ":", "self", ",", "proc", ")", "self", "end" ]
Waits until the condition is true. @example browser.wait_until(timeout: 2) do |browser| browser.windows.size == 1 end @example browser.text_field(name: "new_user_first_name").wait_until(&:present?).click browser.text_field(name: "new_user_first_name").wait_until(message: 'foo') { |field| field.present? } browser.text_field(name: "new_user_first_name").wait_until(timeout: 60, &:present?) browser.text_field(name: "new_user_first_name").wait_until(timeout: 60, name: 'new_user_first_name') @param [Integer] timeout seconds to wait before timing out @param [String] message error message for when times out
[ "Waits", "until", "the", "condition", "is", "true", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/wait.rb#L114-L128
train
watir/watir
lib/watir/wait.rb
Watir.Waitable.wait_until_present
def wait_until_present(depr_timeout = nil, timeout: nil, interval: nil, message: nil) timeout = depr_timeout if depr_timeout Watir.logger.deprecate "#{self.class}#wait_until_present", "#{self.class}#wait_until(&:present?)", ids: [:wait_until_present] message ||= proc { |obj| "waiting for #{obj.inspect} to become present" } wait_until(timeout: timeout, interval: interval, message: message, element_reset: true, &:present?) end
ruby
def wait_until_present(depr_timeout = nil, timeout: nil, interval: nil, message: nil) timeout = depr_timeout if depr_timeout Watir.logger.deprecate "#{self.class}#wait_until_present", "#{self.class}#wait_until(&:present?)", ids: [:wait_until_present] message ||= proc { |obj| "waiting for #{obj.inspect} to become present" } wait_until(timeout: timeout, interval: interval, message: message, element_reset: true, &:present?) end
[ "def", "wait_until_present", "(", "depr_timeout", "=", "nil", ",", "timeout", ":", "nil", ",", "interval", ":", "nil", ",", "message", ":", "nil", ")", "timeout", "=", "depr_timeout", "if", "depr_timeout", "Watir", ".", "logger", ".", "deprecate", "\"#{self.class}#wait_until_present\"", ",", "\"#{self.class}#wait_until(&:present?)\"", ",", "ids", ":", "[", ":wait_until_present", "]", "message", "||=", "proc", "{", "|", "obj", "|", "\"waiting for #{obj.inspect} to become present\"", "}", "wait_until", "(", "timeout", ":", "timeout", ",", "interval", ":", "interval", ",", "message", ":", "message", ",", "element_reset", ":", "true", ",", ":present?", ")", "end" ]
Waits until the element is present. Element is always relocated, so this can be used in the case of an element going away and returning @example browser.text_field(name: "new_user_first_name").wait_until_present @param [Integer] timeout seconds to wait before timing out @param [Float] interval seconds to wait before each try @param [String] message error message for when times out @see Watir::Wait @see Watir::Element#present?
[ "Waits", "until", "the", "element", "is", "present", ".", "Element", "is", "always", "relocated", "so", "this", "can", "be", "used", "in", "the", "case", "of", "an", "element", "going", "away", "and", "returning" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/wait.rb#L176-L184
train
watir/watir
lib/watir/wait.rb
Watir.Waitable.wait_while_present
def wait_while_present(depr_timeout = nil, timeout: nil, interval: nil, message: nil) timeout = depr_timeout if depr_timeout Watir.logger.deprecate "#{self.class}#wait_while_present", "#{self.class}#wait_while(&:present?)", ids: [:wait_while_present] message ||= proc { |obj| "waiting for #{obj.inspect} not to be present" } wait_while(timeout: timeout, interval: interval, message: message, element_reset: true, &:present?) end
ruby
def wait_while_present(depr_timeout = nil, timeout: nil, interval: nil, message: nil) timeout = depr_timeout if depr_timeout Watir.logger.deprecate "#{self.class}#wait_while_present", "#{self.class}#wait_while(&:present?)", ids: [:wait_while_present] message ||= proc { |obj| "waiting for #{obj.inspect} not to be present" } wait_while(timeout: timeout, interval: interval, message: message, element_reset: true, &:present?) end
[ "def", "wait_while_present", "(", "depr_timeout", "=", "nil", ",", "timeout", ":", "nil", ",", "interval", ":", "nil", ",", "message", ":", "nil", ")", "timeout", "=", "depr_timeout", "if", "depr_timeout", "Watir", ".", "logger", ".", "deprecate", "\"#{self.class}#wait_while_present\"", ",", "\"#{self.class}#wait_while(&:present?)\"", ",", "ids", ":", "[", ":wait_while_present", "]", "message", "||=", "proc", "{", "|", "obj", "|", "\"waiting for #{obj.inspect} not to be present\"", "}", "wait_while", "(", "timeout", ":", "timeout", ",", "interval", ":", "interval", ",", "message", ":", "message", ",", "element_reset", ":", "true", ",", ":present?", ")", "end" ]
Waits while the element is present. Element is always relocated, so this can be used in the case of the element changing attributes @example browser.text_field(name: "abrakadbra").wait_while_present @param [Integer] timeout seconds to wait before timing out @param [Float] interval seconds to wait before each try @param [String] message error message for when times out @see Watir::Wait @see Watir::Element#present?
[ "Waits", "while", "the", "element", "is", "present", ".", "Element", "is", "always", "relocated", "so", "this", "can", "be", "used", "in", "the", "case", "of", "the", "element", "changing", "attributes" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/wait.rb#L201-L209
train
watir/watir
lib/watir/user_editable.rb
Watir.UserEditable.set!
def set!(*args) msg = '#set! does not support special keys, use #set instead' raise ArgumentError, msg if args.any? { |v| v.is_a?(::Symbol) } input_value = args.join set input_value[0] return content_editable_set!(*args) if @content_editable element_call { execute_js(:setValue, @element, input_value[0..-2]) } append(input_value[-1]) return if value == input_value raise Exception::Error, "#set! value: '#{value}' does not match expected input: '#{input_value}'" end
ruby
def set!(*args) msg = '#set! does not support special keys, use #set instead' raise ArgumentError, msg if args.any? { |v| v.is_a?(::Symbol) } input_value = args.join set input_value[0] return content_editable_set!(*args) if @content_editable element_call { execute_js(:setValue, @element, input_value[0..-2]) } append(input_value[-1]) return if value == input_value raise Exception::Error, "#set! value: '#{value}' does not match expected input: '#{input_value}'" end
[ "def", "set!", "(", "*", "args", ")", "msg", "=", "'#set! does not support special keys, use #set instead'", "raise", "ArgumentError", ",", "msg", "if", "args", ".", "any?", "{", "|", "v", "|", "v", ".", "is_a?", "(", "::", "Symbol", ")", "}", "input_value", "=", "args", ".", "join", "set", "input_value", "[", "0", "]", "return", "content_editable_set!", "(", "args", ")", "if", "@content_editable", "element_call", "{", "execute_js", "(", ":setValue", ",", "@element", ",", "input_value", "[", "0", "..", "-", "2", "]", ")", "}", "append", "(", "input_value", "[", "-", "1", "]", ")", "return", "if", "value", "==", "input_value", "raise", "Exception", "::", "Error", ",", "\"#set! value: '#{value}' does not match expected input: '#{input_value}'\"", "end" ]
Uses JavaScript to enter most of the given value. Selenium is used to enter the first and last characters @param [String, Symbol] args
[ "Uses", "JavaScript", "to", "enter", "most", "of", "the", "given", "value", ".", "Selenium", "is", "used", "to", "enter", "the", "first", "and", "last", "characters" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/user_editable.rb#L24-L37
train
watir/watir
lib/watir/elements/iframe.rb
Watir.IFrame.execute_script
def execute_script(script, *args) args.map! do |e| e.is_a?(Element) ? e.wait_until(&:exists?).wd : e end returned = driver.execute_script(script, *args) browser.wrap_elements_in(self, returned) end
ruby
def execute_script(script, *args) args.map! do |e| e.is_a?(Element) ? e.wait_until(&:exists?).wd : e end returned = driver.execute_script(script, *args) browser.wrap_elements_in(self, returned) end
[ "def", "execute_script", "(", "script", ",", "*", "args", ")", "args", ".", "map!", "do", "|", "e", "|", "e", ".", "is_a?", "(", "Element", ")", "?", "e", ".", "wait_until", "(", ":exists?", ")", ".", "wd", ":", "e", "end", "returned", "=", "driver", ".", "execute_script", "(", "script", ",", "args", ")", "browser", ".", "wrap_elements_in", "(", "self", ",", "returned", ")", "end" ]
Executes JavaScript snippet in context of frame. @see Watir::Browser#execute_script
[ "Executes", "JavaScript", "snippet", "in", "context", "of", "frame", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/iframe.rb#L47-L54
train
watir/watir
lib/watir/js_execution.rb
Watir.JSExecution.fire_event
def fire_event(event_name) event_name = event_name.to_s.sub(/^on/, '').downcase element_call { execute_js :fireEvent, @element, event_name } end
ruby
def fire_event(event_name) event_name = event_name.to_s.sub(/^on/, '').downcase element_call { execute_js :fireEvent, @element, event_name } end
[ "def", "fire_event", "(", "event_name", ")", "event_name", "=", "event_name", ".", "to_s", ".", "sub", "(", "/", "/", ",", "''", ")", ".", "downcase", "element_call", "{", "execute_js", ":fireEvent", ",", "@element", ",", "event_name", "}", "end" ]
Simulates JavaScript events on element. Note that you may omit "on" from event name. @example browser.button(name: "new_user_button").fire_event :click browser.button(name: "new_user_button").fire_event "mousemove" browser.button(name: "new_user_button").fire_event "onmouseover" @param [String, Symbol] event_name
[ "Simulates", "JavaScript", "events", "on", "element", ".", "Note", "that", "you", "may", "omit", "on", "from", "event", "name", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/js_execution.rb#L22-L26
train
watir/watir
lib/watir/elements/select.rb
Watir.Select.include?
def include?(str_or_rx) option(text: str_or_rx).exist? || option(label: str_or_rx).exist? end
ruby
def include?(str_or_rx) option(text: str_or_rx).exist? || option(label: str_or_rx).exist? end
[ "def", "include?", "(", "str_or_rx", ")", "option", "(", "text", ":", "str_or_rx", ")", ".", "exist?", "||", "option", "(", "label", ":", "str_or_rx", ")", ".", "exist?", "end" ]
Returns true if the select list has one or more options where text or label matches the given value. @param [String, Regexp] str_or_rx @return [Boolean]
[ "Returns", "true", "if", "the", "select", "list", "has", "one", "or", "more", "options", "where", "text", "or", "label", "matches", "the", "given", "value", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/select.rb#L20-L22
train
watir/watir
lib/watir/elements/select.rb
Watir.Select.select
def select(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by v } results.first end
ruby
def select(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by v } results.first end
[ "def", "select", "(", "*", "str_or_rx", ")", "results", "=", "str_or_rx", ".", "flatten", ".", "map", "{", "|", "v", "|", "select_by", "v", "}", "results", ".", "first", "end" ]
Select the option whose text or label matches the given string. @param [String, Regexp] str_or_rx @raise [Watir::Exception::NoValueFoundException] if the value does not exist. @return [String] The text of the option selected. If multiple options match, returns the first match.
[ "Select", "the", "option", "whose", "text", "or", "label", "matches", "the", "given", "string", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/select.rb#L32-L35
train
watir/watir
lib/watir/elements/select.rb
Watir.Select.select_all
def select_all(*str_or_rx) results = str_or_rx.flatten.map { |v| select_all_by v } results.first end
ruby
def select_all(*str_or_rx) results = str_or_rx.flatten.map { |v| select_all_by v } results.first end
[ "def", "select_all", "(", "*", "str_or_rx", ")", "results", "=", "str_or_rx", ".", "flatten", ".", "map", "{", "|", "v", "|", "select_all_by", "v", "}", "results", ".", "first", "end" ]
Select all options whose text or label matches the given string. @param [String, Regexp] str_or_rx @raise [Watir::Exception::NoValueFoundException] if the value does not exist. @return [String] The text of the first option selected.
[ "Select", "all", "options", "whose", "text", "or", "label", "matches", "the", "given", "string", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/select.rb#L45-L48
train
watir/watir
lib/watir/elements/select.rb
Watir.Select.select!
def select!(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by!(v, :single) } results.first end
ruby
def select!(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by!(v, :single) } results.first end
[ "def", "select!", "(", "*", "str_or_rx", ")", "results", "=", "str_or_rx", ".", "flatten", ".", "map", "{", "|", "v", "|", "select_by!", "(", "v", ",", ":single", ")", "}", "results", ".", "first", "end" ]
Uses JavaScript to select the option whose text matches the given string. @param [String, Regexp] str_or_rx @raise [Watir::Exception::NoValueFoundException] if the value does not exist.
[ "Uses", "JavaScript", "to", "select", "the", "option", "whose", "text", "matches", "the", "given", "string", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/select.rb#L57-L60
train
watir/watir
lib/watir/elements/select.rb
Watir.Select.select_all!
def select_all!(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by!(v, :multiple) } results.first end
ruby
def select_all!(*str_or_rx) results = str_or_rx.flatten.map { |v| select_by!(v, :multiple) } results.first end
[ "def", "select_all!", "(", "*", "str_or_rx", ")", "results", "=", "str_or_rx", ".", "flatten", ".", "map", "{", "|", "v", "|", "select_by!", "(", "v", ",", ":multiple", ")", "}", "results", ".", "first", "end" ]
Uses JavaScript to select all options whose text matches the given string. @param [String, Regexp] str_or_rx @raise [Watir::Exception::NoValueFoundException] if the value does not exist.
[ "Uses", "JavaScript", "to", "select", "all", "options", "whose", "text", "matches", "the", "given", "string", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/select.rb#L69-L72
train
watir/watir
lib/watir/elements/file_field.rb
Watir.FileField.value=
def value=(path) path = path.gsub(File::SEPARATOR, File::ALT_SEPARATOR) if File::ALT_SEPARATOR element_call { @element.send_keys path } end
ruby
def value=(path) path = path.gsub(File::SEPARATOR, File::ALT_SEPARATOR) if File::ALT_SEPARATOR element_call { @element.send_keys path } end
[ "def", "value", "=", "(", "path", ")", "path", "=", "path", ".", "gsub", "(", "File", "::", "SEPARATOR", ",", "File", "::", "ALT_SEPARATOR", ")", "if", "File", "::", "ALT_SEPARATOR", "element_call", "{", "@element", ".", "send_keys", "path", "}", "end" ]
Sets the file field to the given path @param [String] path
[ "Sets", "the", "file", "field", "to", "the", "given", "path" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/file_field.rb#L22-L25
train
watir/watir
lib/watir/navigation.rb
Watir.Navigation.goto
def goto(uri) uri = "http://#{uri}" unless uri =~ URI::DEFAULT_PARSER.make_regexp @driver.navigate.to uri @after_hooks.run uri end
ruby
def goto(uri) uri = "http://#{uri}" unless uri =~ URI::DEFAULT_PARSER.make_regexp @driver.navigate.to uri @after_hooks.run uri end
[ "def", "goto", "(", "uri", ")", "uri", "=", "\"http://#{uri}\"", "unless", "uri", "=~", "URI", "::", "DEFAULT_PARSER", ".", "make_regexp", "@driver", ".", "navigate", ".", "to", "uri", "@after_hooks", ".", "run", "uri", "end" ]
Goes to the given URL. @example browser.goto "watir.github.io" @param [String] uri The url. @return [String] The url you end up at.
[ "Goes", "to", "the", "given", "URL", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/navigation.rb#L13-L20
train
watir/watir
lib/watir/logger.rb
Watir.Logger.warn
def warn(message, ids: [], &block) msg = ids.empty? ? '' : "[#{ids.map!(&:to_s).map(&:inspect).join(', ')}] " msg += message @logger.warn(msg, &block) unless (@ignored & ids).any? end
ruby
def warn(message, ids: [], &block) msg = ids.empty? ? '' : "[#{ids.map!(&:to_s).map(&:inspect).join(', ')}] " msg += message @logger.warn(msg, &block) unless (@ignored & ids).any? end
[ "def", "warn", "(", "message", ",", "ids", ":", "[", "]", ",", "&", "block", ")", "msg", "=", "ids", ".", "empty?", "?", "''", ":", "\"[#{ids.map!(&:to_s).map(&:inspect).join(', ')}] \"", "msg", "+=", "message", "@logger", ".", "warn", "(", "msg", ",", "block", ")", "unless", "(", "@ignored", "&", "ids", ")", ".", "any?", "end" ]
Only log a warn message if it is not set to be ignored.
[ "Only", "log", "a", "warn", "message", "if", "it", "is", "not", "set", "to", "be", "ignored", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/logger.rb#L48-L52
train
watir/watir
lib/watir/logger.rb
Watir.Logger.deprecate
def deprecate(old, new, reference: '', ids: []) return if @ignored.include?('deprecations') || (@ignored & ids.map!(&:to_s)).any? msg = ids.empty? ? '' : "[#{ids.map(&:inspect).join(', ')}] " ref_msg = reference.empty? ? '.' : "; see explanation for this deprecation: #{reference}." warn "[DEPRECATION] #{msg}#{old} is deprecated. Use #{new} instead#{ref_msg}" end
ruby
def deprecate(old, new, reference: '', ids: []) return if @ignored.include?('deprecations') || (@ignored & ids.map!(&:to_s)).any? msg = ids.empty? ? '' : "[#{ids.map(&:inspect).join(', ')}] " ref_msg = reference.empty? ? '.' : "; see explanation for this deprecation: #{reference}." warn "[DEPRECATION] #{msg}#{old} is deprecated. Use #{new} instead#{ref_msg}" end
[ "def", "deprecate", "(", "old", ",", "new", ",", "reference", ":", "''", ",", "ids", ":", "[", "]", ")", "return", "if", "@ignored", ".", "include?", "(", "'deprecations'", ")", "||", "(", "@ignored", "&", "ids", ".", "map!", "(", ":to_s", ")", ")", ".", "any?", "msg", "=", "ids", ".", "empty?", "?", "''", ":", "\"[#{ids.map(&:inspect).join(', ')}] \"", "ref_msg", "=", "reference", ".", "empty?", "?", "'.'", ":", "\"; see explanation for this deprecation: #{reference}.\"", "warn", "\"[DEPRECATION] #{msg}#{old} is deprecated. Use #{new} instead#{ref_msg}\"", "end" ]
Marks code as deprecated with replacement. @param [String] old @param [String] new
[ "Marks", "code", "as", "deprecated", "with", "replacement", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/logger.rb#L91-L97
train
watir/watir
lib/watir/attribute_helper.rb
Watir.AttributeHelper.attribute
def attribute(type, method, attr) typed_attributes[type] << [method, attr] define_attribute(type, method, attr) end
ruby
def attribute(type, method, attr) typed_attributes[type] << [method, attr] define_attribute(type, method, attr) end
[ "def", "attribute", "(", "type", ",", "method", ",", "attr", ")", "typed_attributes", "[", "type", "]", "<<", "[", "method", ",", "attr", "]", "define_attribute", "(", "type", ",", "method", ",", "attr", ")", "end" ]
YARD macro to generated friendly documentation for attributes. @macro [attach] attribute @method $2 @return [$1] value of $3 property
[ "YARD", "macro", "to", "generated", "friendly", "documentation", "for", "attributes", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/attribute_helper.rb#L48-L51
train
watir/watir
lib/watir/browser.rb
Watir.Browser.execute_script
def execute_script(script, *args) args.map! do |e| e.is_a?(Element) ? e.wait_until(&:exists?).wd : e end wrap_elements_in(self, @driver.execute_script(script, *args)) end
ruby
def execute_script(script, *args) args.map! do |e| e.is_a?(Element) ? e.wait_until(&:exists?).wd : e end wrap_elements_in(self, @driver.execute_script(script, *args)) end
[ "def", "execute_script", "(", "script", ",", "*", "args", ")", "args", ".", "map!", "do", "|", "e", "|", "e", ".", "is_a?", "(", "Element", ")", "?", "e", ".", "wait_until", "(", ":exists?", ")", ".", "wd", ":", "e", "end", "wrap_elements_in", "(", "self", ",", "@driver", ".", "execute_script", "(", "script", ",", "args", ")", ")", "end" ]
Executes JavaScript snippet. If you are going to use the value snippet returns, make sure to use `return` explicitly. @example Check that Ajax requests are completed with jQuery browser.execute_script("return jQuery.active") == 0 #=> true @param [String] script JavaScript snippet to execute @param args Arguments will be available in the given script in the 'arguments' pseudo-array
[ "Executes", "JavaScript", "snippet", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/browser.rb#L216-L222
train
watir/watir
lib/watir/window.rb
Watir.Window.resize_to
def resize_to(width, height) Selenium::WebDriver::Dimension.new(Integer(width), Integer(height)).tap do |dimension| use { @driver.manage.window.size = dimension } end end
ruby
def resize_to(width, height) Selenium::WebDriver::Dimension.new(Integer(width), Integer(height)).tap do |dimension| use { @driver.manage.window.size = dimension } end end
[ "def", "resize_to", "(", "width", ",", "height", ")", "Selenium", "::", "WebDriver", "::", "Dimension", ".", "new", "(", "Integer", "(", "width", ")", ",", "Integer", "(", "height", ")", ")", ".", "tap", "do", "|", "dimension", "|", "use", "{", "@driver", ".", "manage", ".", "window", ".", "size", "=", "dimension", "}", "end", "end" ]
Resizes window to given width and height. @example browser.window.resize_to 1600, 1200 @param [Integer] width @param [Integer] height
[ "Resizes", "window", "to", "given", "width", "and", "height", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/window.rb#L63-L67
train
watir/watir
lib/watir/window.rb
Watir.Window.move_to
def move_to(x_coord, y_coord) Selenium::WebDriver::Point.new(Integer(x_coord), Integer(y_coord)).tap do |point| use { @driver.manage.window.position = point } end end
ruby
def move_to(x_coord, y_coord) Selenium::WebDriver::Point.new(Integer(x_coord), Integer(y_coord)).tap do |point| use { @driver.manage.window.position = point } end end
[ "def", "move_to", "(", "x_coord", ",", "y_coord", ")", "Selenium", "::", "WebDriver", "::", "Point", ".", "new", "(", "Integer", "(", "x_coord", ")", ",", "Integer", "(", "y_coord", ")", ")", ".", "tap", "do", "|", "point", "|", "use", "{", "@driver", ".", "manage", ".", "window", ".", "position", "=", "point", "}", "end", "end" ]
Moves window to given x and y coordinates. @example browser.window.move_to 300, 200 @param [Integer] x_coord @param [Integer] y_coord
[ "Moves", "window", "to", "given", "x", "and", "y", "coordinates", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/window.rb#L79-L83
train
watir/watir
lib/watir/cookies.rb
Watir.Cookies.to_a
def to_a @control.all_cookies.map do |e| e.merge(expires: e[:expires] ? e[:expires].to_time : nil) end end
ruby
def to_a @control.all_cookies.map do |e| e.merge(expires: e[:expires] ? e[:expires].to_time : nil) end end
[ "def", "to_a", "@control", ".", "all_cookies", ".", "map", "do", "|", "e", "|", "e", ".", "merge", "(", "expires", ":", "e", "[", ":expires", "]", "?", "e", "[", ":expires", "]", ".", "to_time", ":", "nil", ")", "end", "end" ]
Returns array of cookies. @example browser.cookies.to_a #=> {:name=>"my_session", :value=>"BAh7B0kiD3Nlc3Npb25faWQGOgZFRkk", :domain=>"mysite.com"} @return [Array<Hash>]
[ "Returns", "array", "of", "cookies", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/cookies.rb#L19-L23
train
watir/watir
lib/watir/cookies.rb
Watir.Cookies.add
def add(name, value, opts = {}) cookie = { name: name, value: value } cookie[:secure] = opts[:secure] if opts.key?(:secure) cookie[:path] = opts[:path] if opts.key?(:path) expires = opts[:expires] if expires cookie[:expires] = expires.is_a?(String) ? ::Time.parse(expires) : expires end cookie[:domain] = opts[:domain] if opts.key?(:domain) @control.add_cookie cookie end
ruby
def add(name, value, opts = {}) cookie = { name: name, value: value } cookie[:secure] = opts[:secure] if opts.key?(:secure) cookie[:path] = opts[:path] if opts.key?(:path) expires = opts[:expires] if expires cookie[:expires] = expires.is_a?(String) ? ::Time.parse(expires) : expires end cookie[:domain] = opts[:domain] if opts.key?(:domain) @control.add_cookie cookie end
[ "def", "add", "(", "name", ",", "value", ",", "opts", "=", "{", "}", ")", "cookie", "=", "{", "name", ":", "name", ",", "value", ":", "value", "}", "cookie", "[", ":secure", "]", "=", "opts", "[", ":secure", "]", "if", "opts", ".", "key?", "(", ":secure", ")", "cookie", "[", ":path", "]", "=", "opts", "[", ":path", "]", "if", "opts", ".", "key?", "(", ":path", ")", "expires", "=", "opts", "[", ":expires", "]", "if", "expires", "cookie", "[", ":expires", "]", "=", "expires", ".", "is_a?", "(", "String", ")", "?", "::", "Time", ".", "parse", "(", "expires", ")", ":", "expires", "end", "cookie", "[", ":domain", "]", "=", "opts", "[", ":domain", "]", "if", "opts", ".", "key?", "(", ":domain", ")", "@control", ".", "add_cookie", "cookie", "end" ]
Adds new cookie. @example browser.cookies.add 'my_session', 'BAh7B0kiD3Nlc3Npb25faWQGOgZFRkk', secure: true @param [String] name @param [String] value @param [Hash] opts @option opts [Boolean] :secure @option opts [String] :path @option opts [Time, DateTime, NilClass] :expires @option opts [String] :domain
[ "Adds", "new", "cookie", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/cookies.rb#L55-L69
train
watir/watir
lib/watir/cookies.rb
Watir.Cookies.load
def load(file = '.cookies') YAML.safe_load(IO.read(file), [::Symbol, ::Time]).each do |c| add(c.delete(:name), c.delete(:value), c) end end
ruby
def load(file = '.cookies') YAML.safe_load(IO.read(file), [::Symbol, ::Time]).each do |c| add(c.delete(:name), c.delete(:value), c) end end
[ "def", "load", "(", "file", "=", "'.cookies'", ")", "YAML", ".", "safe_load", "(", "IO", ".", "read", "(", "file", ")", ",", "[", "::", "Symbol", ",", "::", "Time", "]", ")", ".", "each", "do", "|", "c", "|", "add", "(", "c", ".", "delete", "(", ":name", ")", ",", "c", ".", "delete", "(", ":value", ")", ",", "c", ")", "end", "end" ]
Load cookies from file @example browser.cookies.load '.cookies' @param [String] file
[ "Load", "cookies", "from", "file" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/cookies.rb#L117-L121
train
watir/watir
lib/watir/elements/table.rb
Watir.Table.headers
def headers(row = nil) row ||= rows.first header_type = row.th.exist? ? 'th' : 'td' row.send("#{header_type}s") end
ruby
def headers(row = nil) row ||= rows.first header_type = row.th.exist? ? 'th' : 'td' row.send("#{header_type}s") end
[ "def", "headers", "(", "row", "=", "nil", ")", "row", "||=", "rows", ".", "first", "header_type", "=", "row", ".", "th", ".", "exist?", "?", "'th'", ":", "'td'", "row", ".", "send", "(", "\"#{header_type}s\"", ")", "end" ]
Returns first row of Table with proper subtype @return [TableCellCollection]
[ "Returns", "first", "row", "of", "Table", "with", "proper", "subtype" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/table.rb#L44-L48
train
watir/watir
lib/watir/radio_set.rb
Watir.RadioSet.select
def select(str_or_rx) %i[value label].each do |key| radio = radio(key => str_or_rx) next unless radio.exist? radio.click unless radio.selected? return key == :value ? radio.value : radio.text end raise UnknownObjectException, "Unable to locate radio matching #{str_or_rx.inspect}" end
ruby
def select(str_or_rx) %i[value label].each do |key| radio = radio(key => str_or_rx) next unless radio.exist? radio.click unless radio.selected? return key == :value ? radio.value : radio.text end raise UnknownObjectException, "Unable to locate radio matching #{str_or_rx.inspect}" end
[ "def", "select", "(", "str_or_rx", ")", "%i[", "value", "label", "]", ".", "each", "do", "|", "key", "|", "radio", "=", "radio", "(", "key", "=>", "str_or_rx", ")", "next", "unless", "radio", ".", "exist?", "radio", ".", "click", "unless", "radio", ".", "selected?", "return", "key", "==", ":value", "?", "radio", ".", "value", ":", "radio", ".", "text", "end", "raise", "UnknownObjectException", ",", "\"Unable to locate radio matching #{str_or_rx.inspect}\"", "end" ]
Select the radio button whose value or label matches the given string. @param [String, Regexp] str_or_rx @raise [Watir::Exception::UnknownObjectException] if the Radio does not exist. @return [String] The value or text of the radio selected.
[ "Select", "the", "radio", "button", "whose", "value", "or", "label", "matches", "the", "given", "string", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/radio_set.rb#L132-L141
train
watir/watir
lib/watir/radio_set.rb
Watir.RadioSet.selected?
def selected?(str_or_rx) found = frame.radio(label: str_or_rx) return found.selected? if found.exist? raise UnknownObjectException, "Unable to locate radio matching #{str_or_rx.inspect}" end
ruby
def selected?(str_or_rx) found = frame.radio(label: str_or_rx) return found.selected? if found.exist? raise UnknownObjectException, "Unable to locate radio matching #{str_or_rx.inspect}" end
[ "def", "selected?", "(", "str_or_rx", ")", "found", "=", "frame", ".", "radio", "(", "label", ":", "str_or_rx", ")", "return", "found", ".", "selected?", "if", "found", ".", "exist?", "raise", "UnknownObjectException", ",", "\"Unable to locate radio matching #{str_or_rx.inspect}\"", "end" ]
Returns true if any of the radio button label matches the given value. @param [String, Regexp] str_or_rx @raise [Watir::Exception::UnknownObjectException] if the options do not exist @return [Boolean]
[ "Returns", "true", "if", "any", "of", "the", "radio", "button", "label", "matches", "the", "given", "value", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/radio_set.rb#L151-L156
train
watir/watir
lib/watir/has_window.rb
Watir.HasWindow.windows
def windows(*args) all = @driver.window_handles.map { |handle| Window.new(self, handle: handle) } if args.empty? all else filter_windows extract_selector(args), all end end
ruby
def windows(*args) all = @driver.window_handles.map { |handle| Window.new(self, handle: handle) } if args.empty? all else filter_windows extract_selector(args), all end end
[ "def", "windows", "(", "*", "args", ")", "all", "=", "@driver", ".", "window_handles", ".", "map", "{", "|", "handle", "|", "Window", ".", "new", "(", "self", ",", "handle", ":", "handle", ")", "}", "if", "args", ".", "empty?", "all", "else", "filter_windows", "extract_selector", "(", "args", ")", ",", "all", "end", "end" ]
Returns browser windows array. @example browser.windows(title: 'closeable window') @return [Array<Window>]
[ "Returns", "browser", "windows", "array", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/has_window.rb#L12-L20
train
watir/watir
lib/watir/has_window.rb
Watir.HasWindow.window
def window(*args, &blk) win = Window.new self, extract_selector(args) win.use(&blk) if block_given? win end
ruby
def window(*args, &blk) win = Window.new self, extract_selector(args) win.use(&blk) if block_given? win end
[ "def", "window", "(", "*", "args", ",", "&", "blk", ")", "win", "=", "Window", ".", "new", "self", ",", "extract_selector", "(", "args", ")", "win", ".", "use", "(", "blk", ")", "if", "block_given?", "win", "end" ]
Returns browser window. @example browser.window(title: 'closeable window') @return [Window]
[ "Returns", "browser", "window", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/has_window.rb#L31-L37
train
watir/watir
lib/watir/scroll.rb
Watir.Scroll.to
def to(param = :top) args = @object.is_a?(Watir::Element) ? element_scroll(param) : browser_scroll(param) raise ArgumentError, "Don't know how to scroll #{@object} to: #{param}!" if args.nil? @object.browser.execute_script(*args) self end
ruby
def to(param = :top) args = @object.is_a?(Watir::Element) ? element_scroll(param) : browser_scroll(param) raise ArgumentError, "Don't know how to scroll #{@object} to: #{param}!" if args.nil? @object.browser.execute_script(*args) self end
[ "def", "to", "(", "param", "=", ":top", ")", "args", "=", "@object", ".", "is_a?", "(", "Watir", "::", "Element", ")", "?", "element_scroll", "(", "param", ")", ":", "browser_scroll", "(", "param", ")", "raise", "ArgumentError", ",", "\"Don't know how to scroll #{@object} to: #{param}!\"", "if", "args", ".", "nil?", "@object", ".", "browser", ".", "execute_script", "(", "args", ")", "self", "end" ]
Scrolls to specified location. @param [Symbol] param
[ "Scrolls", "to", "specified", "location", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/scroll.rb#L26-L32
train
watir/watir
lib/watir/adjacent.rb
Watir.Adjacent.children
def children(opt = {}) raise ArgumentError, '#children can not take an index value' if opt[:index] xpath_adjacent(opt.merge(adjacent: :child, plural: true)) end
ruby
def children(opt = {}) raise ArgumentError, '#children can not take an index value' if opt[:index] xpath_adjacent(opt.merge(adjacent: :child, plural: true)) end
[ "def", "children", "(", "opt", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'#children can not take an index value'", "if", "opt", "[", ":index", "]", "xpath_adjacent", "(", "opt", ".", "merge", "(", "adjacent", ":", ":child", ",", "plural", ":", "true", ")", ")", "end" ]
Returns collection of elements of direct children of current element. @example children = browser.select_list(id: "new_user_languages").children children == browser.select_list(id: "new_user_languages").options.to_a #=> true
[ "Returns", "collection", "of", "elements", "of", "direct", "children", "of", "current", "element", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/adjacent.rb#L105-L109
train
watir/watir
lib/watir/legacy_wait.rb
Watir.EventuallyPresent.when_present
def when_present(timeout = nil) msg = '#when_present' repl_msg = '#wait_until_present if a wait is still needed' Watir.logger.deprecate msg, repl_msg, ids: [:when_present] timeout ||= Watir.default_timeout message = "waiting for #{selector_string} to become present" if block_given? Wait.until(timeout, message) { present? } yield self else WhenPresentDecorator.new(self, timeout, message) end end
ruby
def when_present(timeout = nil) msg = '#when_present' repl_msg = '#wait_until_present if a wait is still needed' Watir.logger.deprecate msg, repl_msg, ids: [:when_present] timeout ||= Watir.default_timeout message = "waiting for #{selector_string} to become present" if block_given? Wait.until(timeout, message) { present? } yield self else WhenPresentDecorator.new(self, timeout, message) end end
[ "def", "when_present", "(", "timeout", "=", "nil", ")", "msg", "=", "'#when_present'", "repl_msg", "=", "'#wait_until_present if a wait is still needed'", "Watir", ".", "logger", ".", "deprecate", "msg", ",", "repl_msg", ",", "ids", ":", "[", ":when_present", "]", "timeout", "||=", "Watir", ".", "default_timeout", "message", "=", "\"waiting for #{selector_string} to become present\"", "if", "block_given?", "Wait", ".", "until", "(", "timeout", ",", "message", ")", "{", "present?", "}", "yield", "self", "else", "WhenPresentDecorator", ".", "new", "(", "self", ",", "timeout", ",", "message", ")", "end", "end" ]
Waits until the element is present. @example browser.text_field(name: "new_user_first_name").when_present.click browser.text_field(name: "new_user_first_name").when_present { |field| field.set "Watir" } browser.text_field(name: "new_user_first_name").when_present(60).text @param [Integer] timeout seconds to wait before timing out @see Watir::Wait @see Watir::Element#present?
[ "Waits", "until", "the", "element", "is", "present", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/legacy_wait.rb#L79-L93
train
watir/watir
lib/watir/legacy_wait.rb
Watir.EventuallyPresent.when_enabled
def when_enabled(timeout = nil) msg = '#when_enabled' repl_msg = 'wait_until(&:enabled?)' Watir.logger.deprecate msg, repl_msg, ids: [:when_enabled] timeout ||= Watir.default_timeout message = "waiting for #{selector_string} to become enabled" if block_given? Wait.until(timeout, message) { enabled? } yield self else WhenEnabledDecorator.new(self, timeout, message) end end
ruby
def when_enabled(timeout = nil) msg = '#when_enabled' repl_msg = 'wait_until(&:enabled?)' Watir.logger.deprecate msg, repl_msg, ids: [:when_enabled] timeout ||= Watir.default_timeout message = "waiting for #{selector_string} to become enabled" if block_given? Wait.until(timeout, message) { enabled? } yield self else WhenEnabledDecorator.new(self, timeout, message) end end
[ "def", "when_enabled", "(", "timeout", "=", "nil", ")", "msg", "=", "'#when_enabled'", "repl_msg", "=", "'wait_until(&:enabled?)'", "Watir", ".", "logger", ".", "deprecate", "msg", ",", "repl_msg", ",", "ids", ":", "[", ":when_enabled", "]", "timeout", "||=", "Watir", ".", "default_timeout", "message", "=", "\"waiting for #{selector_string} to become enabled\"", "if", "block_given?", "Wait", ".", "until", "(", "timeout", ",", "message", ")", "{", "enabled?", "}", "yield", "self", "else", "WhenEnabledDecorator", ".", "new", "(", "self", ",", "timeout", ",", "message", ")", "end", "end" ]
Waits until the element is enabled. @example browser.button(name: "new_user_button_2").when_enabled.click @param [Integer] timeout seconds to wait before timing out @see Watir::Wait @see Watir::Element#enabled?
[ "Waits", "until", "the", "element", "is", "enabled", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/legacy_wait.rb#L107-L121
train
watir/watir
lib/watir/after_hooks.rb
Watir.AfterHooks.add
def add(after_hook = nil, &block) if block_given? @after_hooks << block elsif after_hook.respond_to? :call @after_hooks << after_hook else raise ArgumentError, 'expected block or object responding to #call' end end
ruby
def add(after_hook = nil, &block) if block_given? @after_hooks << block elsif after_hook.respond_to? :call @after_hooks << after_hook else raise ArgumentError, 'expected block or object responding to #call' end end
[ "def", "add", "(", "after_hook", "=", "nil", ",", "&", "block", ")", "if", "block_given?", "@after_hooks", "<<", "block", "elsif", "after_hook", ".", "respond_to?", ":call", "@after_hooks", "<<", "after_hook", "else", "raise", "ArgumentError", ",", "'expected block or object responding to #call'", "end", "end" ]
Adds new after hook. @example browser.after_hooks.add do |browser| browser.text.include?("Server Error") and puts "Application exception or 500 error!" end browser.goto "watir.com/404" "Application exception or 500 error!" @param [#call] after_hook Object responding to call @yield after_hook block @yieldparam [Watir::Browser]
[ "Adds", "new", "after", "hook", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/after_hooks.rb#L35-L43
train
watir/watir
lib/watir/after_hooks.rb
Watir.AfterHooks.run
def run # We can't just rescue exception because Firefox automatically closes alert when exception raised return unless @after_hooks.any? && [email protected]? each { |after_hook| after_hook.call(@browser) } rescue Selenium::WebDriver::Error::NoSuchWindowError => ex Watir.logger.info "Could not execute After Hooks because browser window was closed #{ex}" end
ruby
def run # We can't just rescue exception because Firefox automatically closes alert when exception raised return unless @after_hooks.any? && [email protected]? each { |after_hook| after_hook.call(@browser) } rescue Selenium::WebDriver::Error::NoSuchWindowError => ex Watir.logger.info "Could not execute After Hooks because browser window was closed #{ex}" end
[ "def", "run", "# We can't just rescue exception because Firefox automatically closes alert when exception raised", "return", "unless", "@after_hooks", ".", "any?", "&&", "!", "@browser", ".", "alert", ".", "exists?", "each", "{", "|", "after_hook", "|", "after_hook", ".", "call", "(", "@browser", ")", "}", "rescue", "Selenium", "::", "WebDriver", "::", "Error", "::", "NoSuchWindowError", "=>", "ex", "Watir", ".", "logger", ".", "info", "\"Could not execute After Hooks because browser window was closed #{ex}\"", "end" ]
Runs after hooks.
[ "Runs", "after", "hooks", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/after_hooks.rb#L67-L74
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.exists?
def exists? if located? && stale? Watir.logger.deprecate 'Checking `#exists? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_exists] # TODO: Change this to `reset!` after removing deprecation return false end assert_exists true rescue UnknownObjectException, UnknownFrameException false end
ruby
def exists? if located? && stale? Watir.logger.deprecate 'Checking `#exists? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_exists] # TODO: Change this to `reset!` after removing deprecation return false end assert_exists true rescue UnknownObjectException, UnknownFrameException false end
[ "def", "exists?", "if", "located?", "&&", "stale?", "Watir", ".", "logger", ".", "deprecate", "'Checking `#exists? == false` to determine a stale element'", ",", "'`#stale? == true`'", ",", "reference", ":", "'http://watir.com/staleness-changes'", ",", "ids", ":", "[", ":stale_exists", "]", "# TODO: Change this to `reset!` after removing deprecation", "return", "false", "end", "assert_exists", "true", "rescue", "UnknownObjectException", ",", "UnknownFrameException", "false", "end" ]
Returns true if element exists. Checking for staleness is deprecated @return [Boolean]
[ "Returns", "true", "if", "element", "exists", ".", "Checking", "for", "staleness", "is", "deprecated" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L55-L69
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.click
def click(*modifiers) # TODO: Should wait_for_enabled be default, or `Button` specific behavior? element_call(:wait_for_enabled) do if modifiers.any? action = driver.action modifiers.each { |mod| action.key_down mod } action.click @element modifiers.each { |mod| action.key_up mod } action.perform else @element.click end end browser.after_hooks.run end
ruby
def click(*modifiers) # TODO: Should wait_for_enabled be default, or `Button` specific behavior? element_call(:wait_for_enabled) do if modifiers.any? action = driver.action modifiers.each { |mod| action.key_down mod } action.click @element modifiers.each { |mod| action.key_up mod } action.perform else @element.click end end browser.after_hooks.run end
[ "def", "click", "(", "*", "modifiers", ")", "# TODO: Should wait_for_enabled be default, or `Button` specific behavior?", "element_call", "(", ":wait_for_enabled", ")", "do", "if", "modifiers", ".", "any?", "action", "=", "driver", ".", "action", "modifiers", ".", "each", "{", "|", "mod", "|", "action", ".", "key_down", "mod", "}", "action", ".", "click", "@element", "modifiers", ".", "each", "{", "|", "mod", "|", "action", ".", "key_up", "mod", "}", "action", ".", "perform", "else", "@element", ".", "click", "end", "end", "browser", ".", "after_hooks", ".", "run", "end" ]
Clicks the element, optionally while pressing the given modifier keys. Note that support for holding a modifier key is currently experimental, and may not work at all. @example Click an element browser.element(name: "new_user_button").click @example Click an element with shift key pressed browser.element(name: "new_user_button").click(:shift) @example Click an element with several modifier keys pressed browser.element(name: "new_user_button").click(:shift, :control) @param [:shift, :alt, :control, :command, :meta] modifiers to press while clicking.
[ "Clicks", "the", "element", "optionally", "while", "pressing", "the", "given", "modifier", "keys", ".", "Note", "that", "support", "for", "holding", "a", "modifier", "key", "is", "currently", "experimental", "and", "may", "not", "work", "at", "all", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L143-L159
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.drag_and_drop_on
def drag_and_drop_on(other) assert_is_element other value = element_call(:wait_for_present) do driver.action .drag_and_drop(@element, other.wd) .perform end browser.after_hooks.run value end
ruby
def drag_and_drop_on(other) assert_is_element other value = element_call(:wait_for_present) do driver.action .drag_and_drop(@element, other.wd) .perform end browser.after_hooks.run value end
[ "def", "drag_and_drop_on", "(", "other", ")", "assert_is_element", "other", "value", "=", "element_call", "(", ":wait_for_present", ")", "do", "driver", ".", "action", ".", "drag_and_drop", "(", "@element", ",", "other", ".", "wd", ")", ".", "perform", "end", "browser", ".", "after_hooks", ".", "run", "value", "end" ]
Drag and drop this element on to another element instance. Note that browser support may vary. @example a = browser.div(id: "draggable") b = browser.div(id: "droppable") a.drag_and_drop_on b
[ "Drag", "and", "drop", "this", "element", "on", "to", "another", "element", "instance", ".", "Note", "that", "browser", "support", "may", "vary", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L233-L243
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.drag_and_drop_by
def drag_and_drop_by(right_by, down_by) element_call(:wait_for_present) do driver.action .drag_and_drop_by(@element, right_by, down_by) .perform end end
ruby
def drag_and_drop_by(right_by, down_by) element_call(:wait_for_present) do driver.action .drag_and_drop_by(@element, right_by, down_by) .perform end end
[ "def", "drag_and_drop_by", "(", "right_by", ",", "down_by", ")", "element_call", "(", ":wait_for_present", ")", "do", "driver", ".", "action", ".", "drag_and_drop_by", "(", "@element", ",", "right_by", ",", "down_by", ")", ".", "perform", "end", "end" ]
Drag and drop this element by the given offsets. Note that browser support may vary. @example browser.div(id: "draggable").drag_and_drop_by 100, -200 @param [Integer] right_by @param [Integer] down_by
[ "Drag", "and", "drop", "this", "element", "by", "the", "given", "offsets", ".", "Note", "that", "browser", "support", "may", "vary", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L256-L262
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.attribute_value
def attribute_value(attribute_name) attribute_name = attribute_name.to_s.tr('_', '-') if attribute_name.is_a?(::Symbol) element_call { @element.attribute attribute_name } end
ruby
def attribute_value(attribute_name) attribute_name = attribute_name.to_s.tr('_', '-') if attribute_name.is_a?(::Symbol) element_call { @element.attribute attribute_name } end
[ "def", "attribute_value", "(", "attribute_name", ")", "attribute_name", "=", "attribute_name", ".", "to_s", ".", "tr", "(", "'_'", ",", "'-'", ")", "if", "attribute_name", ".", "is_a?", "(", "::", "Symbol", ")", "element_call", "{", "@element", ".", "attribute", "attribute_name", "}", "end" ]
Returns given attribute value of element. @example browser.a(id: "link_2").attribute_value "title" #=> "link_title_2" @param [String, ::Symbol] attribute_name @return [String, nil]
[ "Returns", "given", "attribute", "value", "of", "element", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L285-L288
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.attribute_values
def attribute_values result = element_call { execute_js(:attributeValues, @element) } result.keys.each do |key| next unless key == key[/[a-zA-Z\-]*/] result[key.tr('-', '_').to_sym] = result.delete(key) end result end
ruby
def attribute_values result = element_call { execute_js(:attributeValues, @element) } result.keys.each do |key| next unless key == key[/[a-zA-Z\-]*/] result[key.tr('-', '_').to_sym] = result.delete(key) end result end
[ "def", "attribute_values", "result", "=", "element_call", "{", "execute_js", "(", ":attributeValues", ",", "@element", ")", "}", "result", ".", "keys", ".", "each", "do", "|", "key", "|", "next", "unless", "key", "==", "key", "[", "/", "\\-", "/", "]", "result", "[", "key", ".", "tr", "(", "'-'", ",", "'_'", ")", ".", "to_sym", "]", "=", "result", ".", "delete", "(", "key", ")", "end", "result", "end" ]
Returns all attribute values. Attributes with special characters are returned as String, rest are returned as a Symbol. @return [Hash] @example browser.pre(id: 'rspec').attribute_values #=> {class:'ruby', id: 'rspec' }
[ "Returns", "all", "attribute", "values", ".", "Attributes", "with", "special", "characters", "are", "returned", "as", "String", "rest", "are", "returned", "as", "a", "Symbol", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L302-L310
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.center
def center point = location dimensions = size Selenium::WebDriver::Point.new(point.x + (dimensions['width'] / 2), point.y + (dimensions['height'] / 2)) end
ruby
def center point = location dimensions = size Selenium::WebDriver::Point.new(point.x + (dimensions['width'] / 2), point.y + (dimensions['height'] / 2)) end
[ "def", "center", "point", "=", "location", "dimensions", "=", "size", "Selenium", "::", "WebDriver", "::", "Point", ".", "new", "(", "point", ".", "x", "+", "(", "dimensions", "[", "'width'", "]", "/", "2", ")", ",", "point", ".", "y", "+", "(", "dimensions", "[", "'height'", "]", "/", "2", ")", ")", "end" ]
Get centre coordinates of element @example browser.button(name: "new_user_button").centre @return [Selenium::WebDriver::Point]
[ "Get", "centre", "coordinates", "of", "element" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L425-L430
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.visible?
def visible? msg = '#visible? behavior will be changing slightly, consider switching to #present? ' \ '(more details: http://watir.com/element-existentialism/)' Watir.logger.warn msg, ids: [:visible_element] displayed = display_check if displayed.nil? && display_check Watir.logger.deprecate 'Checking `#visible? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_visible] end raise unknown_exception if displayed.nil? displayed end
ruby
def visible? msg = '#visible? behavior will be changing slightly, consider switching to #present? ' \ '(more details: http://watir.com/element-existentialism/)' Watir.logger.warn msg, ids: [:visible_element] displayed = display_check if displayed.nil? && display_check Watir.logger.deprecate 'Checking `#visible? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_visible] end raise unknown_exception if displayed.nil? displayed end
[ "def", "visible?", "msg", "=", "'#visible? behavior will be changing slightly, consider switching to #present? '", "'(more details: http://watir.com/element-existentialism/)'", "Watir", ".", "logger", ".", "warn", "msg", ",", "ids", ":", "[", ":visible_element", "]", "displayed", "=", "display_check", "if", "displayed", ".", "nil?", "&&", "display_check", "Watir", ".", "logger", ".", "deprecate", "'Checking `#visible? == false` to determine a stale element'", ",", "'`#stale? == true`'", ",", "reference", ":", "'http://watir.com/staleness-changes'", ",", "ids", ":", "[", ":stale_visible", "]", "end", "raise", "unknown_exception", "if", "displayed", ".", "nil?", "displayed", "end" ]
Returns true if this element is visible on the page. Raises exception if element does not exist @return [Boolean]
[ "Returns", "true", "if", "this", "element", "is", "visible", "on", "the", "page", ".", "Raises", "exception", "if", "element", "does", "not", "exist" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L459-L473
train
watir/watir
lib/watir/elements/element.rb
Watir.Element.present?
def present? displayed = display_check if displayed.nil? && display_check Watir.logger.deprecate 'Checking `#present? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_present] end displayed rescue UnknownObjectException, UnknownFrameException false end
ruby
def present? displayed = display_check if displayed.nil? && display_check Watir.logger.deprecate 'Checking `#present? == false` to determine a stale element', '`#stale? == true`', reference: 'http://watir.com/staleness-changes', ids: [:stale_present] end displayed rescue UnknownObjectException, UnknownFrameException false end
[ "def", "present?", "displayed", "=", "display_check", "if", "displayed", ".", "nil?", "&&", "display_check", "Watir", ".", "logger", ".", "deprecate", "'Checking `#present? == false` to determine a stale element'", ",", "'`#stale? == true`'", ",", "reference", ":", "'http://watir.com/staleness-changes'", ",", "ids", ":", "[", ":stale_present", "]", "end", "displayed", "rescue", "UnknownObjectException", ",", "UnknownFrameException", "false", "end" ]
Returns true if the element exists and is visible on the page. Returns false if element does not exist or exists but is not visible @return [Boolean] @see Watir::Wait
[ "Returns", "true", "if", "the", "element", "exists", "and", "is", "visible", "on", "the", "page", ".", "Returns", "false", "if", "element", "does", "not", "exist", "or", "exists", "but", "is", "not", "visible" ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/elements/element.rb#L494-L505
train
watir/watir
lib/watir/element_collection.rb
Watir.ElementCollection.[]
def [](value) if value.is_a?(Range) to_a[value] elsif @selector.key? :adjacent to_a[value] || element_class.new(@query_scope, invalid_locator: true) elsif @to_a && @to_a[value] @to_a[value] else element_class.new(@query_scope, @selector.merge(index: value)) end end
ruby
def [](value) if value.is_a?(Range) to_a[value] elsif @selector.key? :adjacent to_a[value] || element_class.new(@query_scope, invalid_locator: true) elsif @to_a && @to_a[value] @to_a[value] else element_class.new(@query_scope, @selector.merge(index: value)) end end
[ "def", "[]", "(", "value", ")", "if", "value", ".", "is_a?", "(", "Range", ")", "to_a", "[", "value", "]", "elsif", "@selector", ".", "key?", ":adjacent", "to_a", "[", "value", "]", "||", "element_class", ".", "new", "(", "@query_scope", ",", "invalid_locator", ":", "true", ")", "elsif", "@to_a", "&&", "@to_a", "[", "value", "]", "@to_a", "[", "value", "]", "else", "element_class", ".", "new", "(", "@query_scope", ",", "@selector", ".", "merge", "(", "index", ":", "value", ")", ")", "end", "end" ]
Get the element at the given index or range. Any call to an ElementCollection that includes an adjacent selector can not be lazy loaded because it must store the correct type Ranges can not be lazy loaded @param [Integer, Range] value Index (0-based) or Range of desired element(s) @return [Watir::Element, Watir::ElementCollection] Returns an instance of a Watir::Element subclass
[ "Get", "the", "element", "at", "the", "given", "index", "or", "range", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/element_collection.rb#L56-L66
train
watir/watir
lib/watir/element_collection.rb
Watir.ElementCollection.to_a
def to_a hash = {} @to_a ||= elements_with_tags.map.with_index do |(el, tag_name), idx| selector = @selector.dup selector[:index] = idx unless idx.zero? element = element_class.new(@query_scope, selector) if [HTMLElement, Input].include? element.class construct_subtype(element, hash, tag_name).tap { |e| e.cache = el } else element.tap { |e| e.cache = el } end end end
ruby
def to_a hash = {} @to_a ||= elements_with_tags.map.with_index do |(el, tag_name), idx| selector = @selector.dup selector[:index] = idx unless idx.zero? element = element_class.new(@query_scope, selector) if [HTMLElement, Input].include? element.class construct_subtype(element, hash, tag_name).tap { |e| e.cache = el } else element.tap { |e| e.cache = el } end end end
[ "def", "to_a", "hash", "=", "{", "}", "@to_a", "||=", "elements_with_tags", ".", "map", ".", "with_index", "do", "|", "(", "el", ",", "tag_name", ")", ",", "idx", "|", "selector", "=", "@selector", ".", "dup", "selector", "[", ":index", "]", "=", "idx", "unless", "idx", ".", "zero?", "element", "=", "element_class", ".", "new", "(", "@query_scope", ",", "selector", ")", "if", "[", "HTMLElement", ",", "Input", "]", ".", "include?", "element", ".", "class", "construct_subtype", "(", "element", ",", "hash", ",", "tag_name", ")", ".", "tap", "{", "|", "e", "|", "e", ".", "cache", "=", "el", "}", "else", "element", ".", "tap", "{", "|", "e", "|", "e", ".", "cache", "=", "el", "}", "end", "end", "end" ]
This collection as an Array. @return [Array<Watir::Element>]
[ "This", "collection", "as", "an", "Array", "." ]
2d8db09811c6221ae401b85b2f61f5fa66e463a3
https://github.com/watir/watir/blob/2d8db09811c6221ae401b85b2f61f5fa66e463a3/lib/watir/element_collection.rb#L94-L107
train
libgit2/rugged
lib/rugged/commit.rb
Rugged.Commit.diff
def diff(*args) args.unshift(parents.first) if args.size == 1 && args.first.is_a?(Hash) self.tree.diff(*args) end
ruby
def diff(*args) args.unshift(parents.first) if args.size == 1 && args.first.is_a?(Hash) self.tree.diff(*args) end
[ "def", "diff", "(", "*", "args", ")", "args", ".", "unshift", "(", "parents", ".", "first", ")", "if", "args", ".", "size", "==", "1", "&&", "args", ".", "first", ".", "is_a?", "(", "Hash", ")", "self", ".", "tree", ".", "diff", "(", "args", ")", "end" ]
Return a diff between this commit and its first parent or another commit or tree. See Rugged::Tree#diff for more details.
[ "Return", "a", "diff", "between", "this", "commit", "and", "its", "first", "parent", "or", "another", "commit", "or", "tree", "." ]
33873e5df2bd38501814182ff79609ed4bd88012
https://github.com/libgit2/rugged/blob/33873e5df2bd38501814182ff79609ed4bd88012/lib/rugged/commit.rb#L24-L27
train
libgit2/rugged
lib/rugged/repository.rb
Rugged.Repository.checkout
def checkout(target, options = {}) options[:strategy] ||= :safe options.delete(:paths) return checkout_head(options) if target == "HEAD" if target.kind_of?(Rugged::Branch) branch = target else branch = branches[target] end if branch self.checkout_tree(branch.target, options) if branch.remote? references.create("HEAD", branch.target_id, force: true) else references.create("HEAD", branch.canonical_name, force: true) end else commit = Commit.lookup(self, self.rev_parse_oid(target)) references.create("HEAD", commit.oid, force: true) self.checkout_tree(commit, options) end end
ruby
def checkout(target, options = {}) options[:strategy] ||= :safe options.delete(:paths) return checkout_head(options) if target == "HEAD" if target.kind_of?(Rugged::Branch) branch = target else branch = branches[target] end if branch self.checkout_tree(branch.target, options) if branch.remote? references.create("HEAD", branch.target_id, force: true) else references.create("HEAD", branch.canonical_name, force: true) end else commit = Commit.lookup(self, self.rev_parse_oid(target)) references.create("HEAD", commit.oid, force: true) self.checkout_tree(commit, options) end end
[ "def", "checkout", "(", "target", ",", "options", "=", "{", "}", ")", "options", "[", ":strategy", "]", "||=", ":safe", "options", ".", "delete", "(", ":paths", ")", "return", "checkout_head", "(", "options", ")", "if", "target", "==", "\"HEAD\"", "if", "target", ".", "kind_of?", "(", "Rugged", "::", "Branch", ")", "branch", "=", "target", "else", "branch", "=", "branches", "[", "target", "]", "end", "if", "branch", "self", ".", "checkout_tree", "(", "branch", ".", "target", ",", "options", ")", "if", "branch", ".", "remote?", "references", ".", "create", "(", "\"HEAD\"", ",", "branch", ".", "target_id", ",", "force", ":", "true", ")", "else", "references", ".", "create", "(", "\"HEAD\"", ",", "branch", ".", "canonical_name", ",", "force", ":", "true", ")", "end", "else", "commit", "=", "Commit", ".", "lookup", "(", "self", ",", "self", ".", "rev_parse_oid", "(", "target", ")", ")", "references", ".", "create", "(", "\"HEAD\"", ",", "commit", ".", "oid", ",", "force", ":", "true", ")", "self", ".", "checkout_tree", "(", "commit", ",", "options", ")", "end", "end" ]
Checkout the specified branch, reference or commit. target - A revparse spec for the branch, reference or commit to check out. options - Options passed to #checkout_tree.
[ "Checkout", "the", "specified", "branch", "reference", "or", "commit", "." ]
33873e5df2bd38501814182ff79609ed4bd88012
https://github.com/libgit2/rugged/blob/33873e5df2bd38501814182ff79609ed4bd88012/lib/rugged/repository.rb#L29-L54
train
libgit2/rugged
lib/rugged/repository.rb
Rugged.Repository.create_branch
def create_branch(name, sha_or_ref = "HEAD") case sha_or_ref when Rugged::Object target = sha_or_ref.oid else target = rev_parse_oid(sha_or_ref) end branches.create(name, target) end
ruby
def create_branch(name, sha_or_ref = "HEAD") case sha_or_ref when Rugged::Object target = sha_or_ref.oid else target = rev_parse_oid(sha_or_ref) end branches.create(name, target) end
[ "def", "create_branch", "(", "name", ",", "sha_or_ref", "=", "\"HEAD\"", ")", "case", "sha_or_ref", "when", "Rugged", "::", "Object", "target", "=", "sha_or_ref", ".", "oid", "else", "target", "=", "rev_parse_oid", "(", "sha_or_ref", ")", "end", "branches", ".", "create", "(", "name", ",", "target", ")", "end" ]
Create a new branch in the repository name - The name of the branch (without a full reference path) sha_or_ref - The target of the branch; either a String representing an OID or a reference name, or a Rugged::Object instance. Returns a Rugged::Branch object
[ "Create", "a", "new", "branch", "in", "the", "repository" ]
33873e5df2bd38501814182ff79609ed4bd88012
https://github.com/libgit2/rugged/blob/33873e5df2bd38501814182ff79609ed4bd88012/lib/rugged/repository.rb#L225-L234
train
libgit2/rugged
lib/rugged/repository.rb
Rugged.Repository.blob_at
def blob_at(revision, path) tree = Rugged::Commit.lookup(self, revision).tree begin blob_data = tree.path(path) rescue Rugged::TreeError return nil end blob = Rugged::Blob.lookup(self, blob_data[:oid]) (blob.type == :blob) ? blob : nil end
ruby
def blob_at(revision, path) tree = Rugged::Commit.lookup(self, revision).tree begin blob_data = tree.path(path) rescue Rugged::TreeError return nil end blob = Rugged::Blob.lookup(self, blob_data[:oid]) (blob.type == :blob) ? blob : nil end
[ "def", "blob_at", "(", "revision", ",", "path", ")", "tree", "=", "Rugged", "::", "Commit", ".", "lookup", "(", "self", ",", "revision", ")", ".", "tree", "begin", "blob_data", "=", "tree", ".", "path", "(", "path", ")", "rescue", "Rugged", "::", "TreeError", "return", "nil", "end", "blob", "=", "Rugged", "::", "Blob", ".", "lookup", "(", "self", ",", "blob_data", "[", ":oid", "]", ")", "(", "blob", ".", "type", "==", ":blob", ")", "?", "blob", ":", "nil", "end" ]
Get the blob at a path for a specific revision. revision - The String SHA1. path - The String file path. Returns a Rugged::Blob object
[ "Get", "the", "blob", "at", "a", "path", "for", "a", "specific", "revision", "." ]
33873e5df2bd38501814182ff79609ed4bd88012
https://github.com/libgit2/rugged/blob/33873e5df2bd38501814182ff79609ed4bd88012/lib/rugged/repository.rb#L242-L251
train
libgit2/rugged
lib/rugged/repository.rb
Rugged.Repository.push
def push(remote_or_url, *args) unless remote_or_url.kind_of? Remote remote_or_url = remotes[remote_or_url] || remotes.create_anonymous(remote_or_url) end remote_or_url.push(*args) end
ruby
def push(remote_or_url, *args) unless remote_or_url.kind_of? Remote remote_or_url = remotes[remote_or_url] || remotes.create_anonymous(remote_or_url) end remote_or_url.push(*args) end
[ "def", "push", "(", "remote_or_url", ",", "*", "args", ")", "unless", "remote_or_url", ".", "kind_of?", "Remote", "remote_or_url", "=", "remotes", "[", "remote_or_url", "]", "||", "remotes", ".", "create_anonymous", "(", "remote_or_url", ")", "end", "remote_or_url", ".", "push", "(", "args", ")", "end" ]
Push a list of refspecs to the given remote. refspecs - A list of refspecs that should be pushed to the remote. Returns a hash containing the pushed refspecs as keys and any error messages or +nil+ as values.
[ "Push", "a", "list", "of", "refspecs", "to", "the", "given", "remote", "." ]
33873e5df2bd38501814182ff79609ed4bd88012
https://github.com/libgit2/rugged/blob/33873e5df2bd38501814182ff79609ed4bd88012/lib/rugged/repository.rb#L267-L273
train
libgit2/rugged
lib/rugged/submodule_collection.rb
Rugged.SubmoduleCollection.clone_submodule
def clone_submodule(repo, fetch_options) # the remote was just added by setup_add, no need to check presence repo.remotes['origin'].fetch(fetch_options) repo.branches.create('master','origin/master') repo.branches['master'].upstream = repo.branches['origin/master'] repo.checkout_head(strategy: :force) end
ruby
def clone_submodule(repo, fetch_options) # the remote was just added by setup_add, no need to check presence repo.remotes['origin'].fetch(fetch_options) repo.branches.create('master','origin/master') repo.branches['master'].upstream = repo.branches['origin/master'] repo.checkout_head(strategy: :force) end
[ "def", "clone_submodule", "(", "repo", ",", "fetch_options", ")", "# the remote was just added by setup_add, no need to check presence", "repo", ".", "remotes", "[", "'origin'", "]", ".", "fetch", "(", "fetch_options", ")", "repo", ".", "branches", ".", "create", "(", "'master'", ",", "'origin/master'", ")", "repo", ".", "branches", "[", "'master'", "]", ".", "upstream", "=", "repo", ".", "branches", "[", "'origin/master'", "]", "repo", ".", "checkout_head", "(", "strategy", ":", ":force", ")", "end" ]
currently libgit2's `git_submodule_add_setup` initializes a repo with a workdir for the submodule. libgit2's `git_clone` however requires the target for the clone to be an empty dir. This provides a ghetto clone implementation that: 1. fetches the remote 2. sets up a master branch to be tracking origin/master 3. checkouts the submodule
[ "currently", "libgit2", "s", "git_submodule_add_setup", "initializes", "a", "repo", "with", "a", "workdir", "for", "the", "submodule", ".", "libgit2", "s", "git_clone", "however", "requires", "the", "target", "for", "the", "clone", "to", "be", "an", "empty", "dir", "." ]
33873e5df2bd38501814182ff79609ed4bd88012
https://github.com/libgit2/rugged/blob/33873e5df2bd38501814182ff79609ed4bd88012/lib/rugged/submodule_collection.rb#L43-L51
train
oauth-xx/oauth2
lib/oauth2/client.rb
OAuth2.Client.build_access_token
def build_access_token(response, access_token_opts, access_token_class) access_token_class.from_hash(self, response.parsed.merge(access_token_opts)).tap do |access_token| access_token.response = response if access_token.respond_to?(:response=) end end
ruby
def build_access_token(response, access_token_opts, access_token_class) access_token_class.from_hash(self, response.parsed.merge(access_token_opts)).tap do |access_token| access_token.response = response if access_token.respond_to?(:response=) end end
[ "def", "build_access_token", "(", "response", ",", "access_token_opts", ",", "access_token_class", ")", "access_token_class", ".", "from_hash", "(", "self", ",", "response", ".", "parsed", ".", "merge", "(", "access_token_opts", ")", ")", ".", "tap", "do", "|", "access_token", "|", "access_token", ".", "response", "=", "response", "if", "access_token", ".", "respond_to?", "(", ":response=", ")", "end", "end" ]
Builds the access token from the response of the HTTP call @return [AccessToken] the initialized AccessToken
[ "Builds", "the", "access", "token", "from", "the", "response", "of", "the", "HTTP", "call" ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/client.rb#L221-L225
train
oauth-xx/oauth2
lib/oauth2/authenticator.rb
OAuth2.Authenticator.apply
def apply(params) case mode.to_sym when :basic_auth apply_basic_auth(params) when :request_body apply_params_auth(params) else raise NotImplementedError end end
ruby
def apply(params) case mode.to_sym when :basic_auth apply_basic_auth(params) when :request_body apply_params_auth(params) else raise NotImplementedError end end
[ "def", "apply", "(", "params", ")", "case", "mode", ".", "to_sym", "when", ":basic_auth", "apply_basic_auth", "(", "params", ")", "when", ":request_body", "apply_params_auth", "(", "params", ")", "else", "raise", "NotImplementedError", "end", "end" ]
Apply the request credentials used to authenticate to the Authorization Server Depending on configuration, this might be as request params or as an Authorization header. User-provided params and header take precedence. @param [Hash] params a Hash of params for the token endpoint @return [Hash] params amended with appropriate authentication details
[ "Apply", "the", "request", "credentials", "used", "to", "authenticate", "to", "the", "Authorization", "Server" ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/authenticator.rb#L22-L31
train
oauth-xx/oauth2
lib/oauth2/authenticator.rb
OAuth2.Authenticator.apply_basic_auth
def apply_basic_auth(params) headers = params.fetch(:headers, {}) headers = basic_auth_header.merge(headers) params.merge(:headers => headers) end
ruby
def apply_basic_auth(params) headers = params.fetch(:headers, {}) headers = basic_auth_header.merge(headers) params.merge(:headers => headers) end
[ "def", "apply_basic_auth", "(", "params", ")", "headers", "=", "params", ".", "fetch", "(", ":headers", ",", "{", "}", ")", "headers", "=", "basic_auth_header", ".", "merge", "(", "headers", ")", "params", ".", "merge", "(", ":headers", "=>", "headers", ")", "end" ]
Adds an `Authorization` header with Basic Auth credentials if and only if it is not already set in the params.
[ "Adds", "an", "Authorization", "header", "with", "Basic", "Auth", "credentials", "if", "and", "only", "if", "it", "is", "not", "already", "set", "in", "the", "params", "." ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/authenticator.rb#L47-L51
train
oauth-xx/oauth2
lib/oauth2/response.rb
OAuth2.Response.content_type
def content_type return nil unless response.headers ((response.headers.values_at('content-type', 'Content-Type').compact.first || '').split(';').first || '').strip end
ruby
def content_type return nil unless response.headers ((response.headers.values_at('content-type', 'Content-Type').compact.first || '').split(';').first || '').strip end
[ "def", "content_type", "return", "nil", "unless", "response", ".", "headers", "(", "(", "response", ".", "headers", ".", "values_at", "(", "'content-type'", ",", "'Content-Type'", ")", ".", "compact", ".", "first", "||", "''", ")", ".", "split", "(", "';'", ")", ".", "first", "||", "''", ")", ".", "strip", "end" ]
Attempts to determine the content type of the response.
[ "Attempts", "to", "determine", "the", "content", "type", "of", "the", "response", "." ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/response.rb#L84-L87
train
oauth-xx/oauth2
lib/oauth2/mac_token.rb
OAuth2.MACToken.request
def request(verb, path, opts = {}, &block) url = client.connection.build_url(path, opts[:params]).to_s opts[:headers] ||= {} opts[:headers]['Authorization'] = header(verb, url) @client.request(verb, path, opts, &block) end
ruby
def request(verb, path, opts = {}, &block) url = client.connection.build_url(path, opts[:params]).to_s opts[:headers] ||= {} opts[:headers]['Authorization'] = header(verb, url) @client.request(verb, path, opts, &block) end
[ "def", "request", "(", "verb", ",", "path", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "url", "=", "client", ".", "connection", ".", "build_url", "(", "path", ",", "opts", "[", ":params", "]", ")", ".", "to_s", "opts", "[", ":headers", "]", "||=", "{", "}", "opts", "[", ":headers", "]", "[", "'Authorization'", "]", "=", "header", "(", "verb", ",", "url", ")", "@client", ".", "request", "(", "verb", ",", "path", ",", "opts", ",", "block", ")", "end" ]
Initalize a MACToken @param [Client] client the OAuth2::Client instance @param [String] token the Access Token value @option [String] secret the secret key value @param [Hash] opts the options to create the Access Token with @option opts [String] :refresh_token (nil) the refresh_token value @option opts [FixNum, String] :expires_in (nil) the number of seconds in which the AccessToken will expire @option opts [FixNum, String] :expires_at (nil) the epoch time in seconds in which AccessToken will expire @option opts [FixNum, String] :algorithm (hmac-sha-256) the algorithm to use for the HMAC digest (one of 'hmac-sha-256', 'hmac-sha-1') Make a request with the MAC Token @param [Symbol] verb the HTTP request method @param [String] path the HTTP URL path of the request @param [Hash] opts the options to make the request with @see Client#request
[ "Initalize", "a", "MACToken" ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/mac_token.rb#L43-L50
train
oauth-xx/oauth2
lib/oauth2/mac_token.rb
OAuth2.MACToken.header
def header(verb, url) timestamp = Time.now.utc.to_i nonce = Digest::MD5.hexdigest([timestamp, SecureRandom.hex].join(':')) uri = URI.parse(url) raise(ArgumentError, "could not parse \"#{url}\" into URI") unless uri.is_a?(URI::HTTP) mac = signature(timestamp, nonce, verb, uri) "MAC id=\"#{token}\", ts=\"#{timestamp}\", nonce=\"#{nonce}\", mac=\"#{mac}\"" end
ruby
def header(verb, url) timestamp = Time.now.utc.to_i nonce = Digest::MD5.hexdigest([timestamp, SecureRandom.hex].join(':')) uri = URI.parse(url) raise(ArgumentError, "could not parse \"#{url}\" into URI") unless uri.is_a?(URI::HTTP) mac = signature(timestamp, nonce, verb, uri) "MAC id=\"#{token}\", ts=\"#{timestamp}\", nonce=\"#{nonce}\", mac=\"#{mac}\"" end
[ "def", "header", "(", "verb", ",", "url", ")", "timestamp", "=", "Time", ".", "now", ".", "utc", ".", "to_i", "nonce", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "[", "timestamp", ",", "SecureRandom", ".", "hex", "]", ".", "join", "(", "':'", ")", ")", "uri", "=", "URI", ".", "parse", "(", "url", ")", "raise", "(", "ArgumentError", ",", "\"could not parse \\\"#{url}\\\" into URI\"", ")", "unless", "uri", ".", "is_a?", "(", "URI", "::", "HTTP", ")", "mac", "=", "signature", "(", "timestamp", ",", "nonce", ",", "verb", ",", "uri", ")", "\"MAC id=\\\"#{token}\\\", ts=\\\"#{timestamp}\\\", nonce=\\\"#{nonce}\\\", mac=\\\"#{mac}\\\"\"", "end" ]
Generate the MAC header @param [Symbol] verb the HTTP request method @param [String] url the HTTP URL path of the request
[ "Generate", "the", "MAC", "header" ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/mac_token.rb#L61-L72
train
oauth-xx/oauth2
lib/oauth2/mac_token.rb
OAuth2.MACToken.signature
def signature(timestamp, nonce, verb, uri) signature = [ timestamp, nonce, verb.to_s.upcase, uri.request_uri, uri.host, uri.port, '', nil ].join("\n") Base64.strict_encode64(OpenSSL::HMAC.digest(@algorithm, secret, signature)) end
ruby
def signature(timestamp, nonce, verb, uri) signature = [ timestamp, nonce, verb.to_s.upcase, uri.request_uri, uri.host, uri.port, '', nil ].join("\n") Base64.strict_encode64(OpenSSL::HMAC.digest(@algorithm, secret, signature)) end
[ "def", "signature", "(", "timestamp", ",", "nonce", ",", "verb", ",", "uri", ")", "signature", "=", "[", "timestamp", ",", "nonce", ",", "verb", ".", "to_s", ".", "upcase", ",", "uri", ".", "request_uri", ",", "uri", ".", "host", ",", "uri", ".", "port", ",", "''", ",", "nil", "]", ".", "join", "(", "\"\\n\"", ")", "Base64", ".", "strict_encode64", "(", "OpenSSL", "::", "HMAC", ".", "digest", "(", "@algorithm", ",", "secret", ",", "signature", ")", ")", "end" ]
Generate the Base64-encoded HMAC digest signature @param [Fixnum] timestamp the timestamp of the request in seconds since epoch @param [String] nonce the MAC header nonce @param [Symbol] verb the HTTP request method @param [String] url the HTTP URL path of the request
[ "Generate", "the", "Base64", "-", "encoded", "HMAC", "digest", "signature" ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/mac_token.rb#L80-L92
train
oauth-xx/oauth2
lib/oauth2/mac_token.rb
OAuth2.MACToken.algorithm=
def algorithm=(alg) @algorithm = begin case alg.to_s when 'hmac-sha-1' OpenSSL::Digest::SHA1.new when 'hmac-sha-256' OpenSSL::Digest::SHA256.new else raise(ArgumentError, 'Unsupported algorithm') end end end
ruby
def algorithm=(alg) @algorithm = begin case alg.to_s when 'hmac-sha-1' OpenSSL::Digest::SHA1.new when 'hmac-sha-256' OpenSSL::Digest::SHA256.new else raise(ArgumentError, 'Unsupported algorithm') end end end
[ "def", "algorithm", "=", "(", "alg", ")", "@algorithm", "=", "begin", "case", "alg", ".", "to_s", "when", "'hmac-sha-1'", "OpenSSL", "::", "Digest", "::", "SHA1", ".", "new", "when", "'hmac-sha-256'", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "new", "else", "raise", "(", "ArgumentError", ",", "'Unsupported algorithm'", ")", "end", "end", "end" ]
Set the HMAC algorithm @param [String] alg the algorithm to use (one of 'hmac-sha-1', 'hmac-sha-256')
[ "Set", "the", "HMAC", "algorithm" ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/mac_token.rb#L97-L108
train
oauth-xx/oauth2
lib/oauth2/access_token.rb
OAuth2.AccessToken.refresh
def refresh(params = {}, access_token_opts = {}, access_token_class = self.class) raise('A refresh_token is not available') unless refresh_token params[:grant_type] = 'refresh_token' params[:refresh_token] = refresh_token new_token = @client.get_token(params, access_token_opts, access_token_class) new_token.options = options new_token.refresh_token = refresh_token unless new_token.refresh_token new_token end
ruby
def refresh(params = {}, access_token_opts = {}, access_token_class = self.class) raise('A refresh_token is not available') unless refresh_token params[:grant_type] = 'refresh_token' params[:refresh_token] = refresh_token new_token = @client.get_token(params, access_token_opts, access_token_class) new_token.options = options new_token.refresh_token = refresh_token unless new_token.refresh_token new_token end
[ "def", "refresh", "(", "params", "=", "{", "}", ",", "access_token_opts", "=", "{", "}", ",", "access_token_class", "=", "self", ".", "class", ")", "raise", "(", "'A refresh_token is not available'", ")", "unless", "refresh_token", "params", "[", ":grant_type", "]", "=", "'refresh_token'", "params", "[", ":refresh_token", "]", "=", "refresh_token", "new_token", "=", "@client", ".", "get_token", "(", "params", ",", "access_token_opts", ",", "access_token_class", ")", "new_token", ".", "options", "=", "options", "new_token", ".", "refresh_token", "=", "refresh_token", "unless", "new_token", ".", "refresh_token", "new_token", "end" ]
Refreshes the current Access Token @return [AccessToken] a new AccessToken @note options should be carried over to the new AccessToken
[ "Refreshes", "the", "current", "Access", "Token" ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/access_token.rb#L85-L93
train
oauth-xx/oauth2
lib/oauth2/access_token.rb
OAuth2.AccessToken.request
def request(verb, path, opts = {}, &block) configure_authentication!(opts) @client.request(verb, path, opts, &block) end
ruby
def request(verb, path, opts = {}, &block) configure_authentication!(opts) @client.request(verb, path, opts, &block) end
[ "def", "request", "(", "verb", ",", "path", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "configure_authentication!", "(", "opts", ")", "@client", ".", "request", "(", "verb", ",", "path", ",", "opts", ",", "block", ")", "end" ]
Make a request with the Access Token @param [Symbol] verb the HTTP request method @param [String] path the HTTP URL path of the request @param [Hash] opts the options to make the request with @see Client#request
[ "Make", "a", "request", "with", "the", "Access", "Token" ]
f08ff9da169136ab133aa2faab0d74a4407deffb
https://github.com/oauth-xx/oauth2/blob/f08ff9da169136ab133aa2faab0d74a4407deffb/lib/oauth2/access_token.rb#L111-L114
train
ruby-git/ruby-git
lib/git/log.rb
Git.Log.run_log
def run_log log = @base.lib.full_log_commits(:count => @count, :object => @object, :path_limiter => @path, :since => @since, :author => @author, :grep => @grep, :skip => @skip, :until => @until, :between => @between) @commits = log.map { |c| Git::Object::Commit.new(@base, c['sha'], c) } end
ruby
def run_log log = @base.lib.full_log_commits(:count => @count, :object => @object, :path_limiter => @path, :since => @since, :author => @author, :grep => @grep, :skip => @skip, :until => @until, :between => @between) @commits = log.map { |c| Git::Object::Commit.new(@base, c['sha'], c) } end
[ "def", "run_log", "log", "=", "@base", ".", "lib", ".", "full_log_commits", "(", ":count", "=>", "@count", ",", ":object", "=>", "@object", ",", ":path_limiter", "=>", "@path", ",", ":since", "=>", "@since", ",", ":author", "=>", "@author", ",", ":grep", "=>", "@grep", ",", ":skip", "=>", "@skip", ",", ":until", "=>", "@until", ",", ":between", "=>", "@between", ")", "@commits", "=", "log", ".", "map", "{", "|", "c", "|", "Git", "::", "Object", "::", "Commit", ".", "new", "(", "@base", ",", "c", "[", "'sha'", "]", ",", "c", ")", "}", "end" ]
actually run the 'git log' command
[ "actually", "run", "the", "git", "log", "command" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/log.rb#L118-L124
train
ruby-git/ruby-git
lib/git/branches.rb
Git.Branches.[]
def [](branch_name) @branches.values.inject(@branches) do |branches, branch| branches[branch.full] ||= branch # This is how Git (version 1.7.9.5) works. # Lets you ignore the 'remotes' if its at the beginning of the branch full name (even if is not a real remote branch). branches[branch.full.sub('remotes/', '')] ||= branch if branch.full =~ /^remotes\/.+/ branches end[branch_name.to_s] end
ruby
def [](branch_name) @branches.values.inject(@branches) do |branches, branch| branches[branch.full] ||= branch # This is how Git (version 1.7.9.5) works. # Lets you ignore the 'remotes' if its at the beginning of the branch full name (even if is not a real remote branch). branches[branch.full.sub('remotes/', '')] ||= branch if branch.full =~ /^remotes\/.+/ branches end[branch_name.to_s] end
[ "def", "[]", "(", "branch_name", ")", "@branches", ".", "values", ".", "inject", "(", "@branches", ")", "do", "|", "branches", ",", "branch", "|", "branches", "[", "branch", ".", "full", "]", "||=", "branch", "# This is how Git (version 1.7.9.5) works. ", "# Lets you ignore the 'remotes' if its at the beginning of the branch full name (even if is not a real remote branch). ", "branches", "[", "branch", ".", "full", ".", "sub", "(", "'remotes/'", ",", "''", ")", "]", "||=", "branch", "if", "branch", ".", "full", "=~", "/", "\\/", "/", "branches", "end", "[", "branch_name", ".", "to_s", "]", "end" ]
Returns the target branch Example: Given (git branch -a): master remotes/working/master g.branches['master'].full #=> 'master' g.branches['working/master'].full => 'remotes/working/master' g.branches['remotes/working/master'].full => 'remotes/working/master' @param [#to_s] branch_name the target branch name. @return [Git::Branch] the target branch.
[ "Returns", "the", "target", "branch" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/branches.rb#L49-L59
train
ruby-git/ruby-git
lib/git/lib.rb
Git.Lib.describe
def describe(committish=nil, opts={}) arr_opts = [] arr_opts << '--all' if opts[:all] arr_opts << '--tags' if opts[:tags] arr_opts << '--contains' if opts[:contains] arr_opts << '--debug' if opts[:debug] arr_opts << '--long' if opts[:long] arr_opts << '--always' if opts[:always] arr_opts << '--exact-match' if opts[:exact_match] || opts[:"exact-match"] arr_opts << '--dirty' if opts['dirty'] == true arr_opts << "--dirty=#{opts['dirty']}" if opts['dirty'].is_a?(String) arr_opts << "--abbrev=#{opts['abbrev']}" if opts[:abbrev] arr_opts << "--candidates=#{opts['candidates']}" if opts[:candidates] arr_opts << "--match=#{opts['match']}" if opts[:match] arr_opts << committish if committish return command('describe', arr_opts) end
ruby
def describe(committish=nil, opts={}) arr_opts = [] arr_opts << '--all' if opts[:all] arr_opts << '--tags' if opts[:tags] arr_opts << '--contains' if opts[:contains] arr_opts << '--debug' if opts[:debug] arr_opts << '--long' if opts[:long] arr_opts << '--always' if opts[:always] arr_opts << '--exact-match' if opts[:exact_match] || opts[:"exact-match"] arr_opts << '--dirty' if opts['dirty'] == true arr_opts << "--dirty=#{opts['dirty']}" if opts['dirty'].is_a?(String) arr_opts << "--abbrev=#{opts['abbrev']}" if opts[:abbrev] arr_opts << "--candidates=#{opts['candidates']}" if opts[:candidates] arr_opts << "--match=#{opts['match']}" if opts[:match] arr_opts << committish if committish return command('describe', arr_opts) end
[ "def", "describe", "(", "committish", "=", "nil", ",", "opts", "=", "{", "}", ")", "arr_opts", "=", "[", "]", "arr_opts", "<<", "'--all'", "if", "opts", "[", ":all", "]", "arr_opts", "<<", "'--tags'", "if", "opts", "[", ":tags", "]", "arr_opts", "<<", "'--contains'", "if", "opts", "[", ":contains", "]", "arr_opts", "<<", "'--debug'", "if", "opts", "[", ":debug", "]", "arr_opts", "<<", "'--long'", "if", "opts", "[", ":long", "]", "arr_opts", "<<", "'--always'", "if", "opts", "[", ":always", "]", "arr_opts", "<<", "'--exact-match'", "if", "opts", "[", ":exact_match", "]", "||", "opts", "[", ":\"", "\"", "]", "arr_opts", "<<", "'--dirty'", "if", "opts", "[", "'dirty'", "]", "==", "true", "arr_opts", "<<", "\"--dirty=#{opts['dirty']}\"", "if", "opts", "[", "'dirty'", "]", ".", "is_a?", "(", "String", ")", "arr_opts", "<<", "\"--abbrev=#{opts['abbrev']}\"", "if", "opts", "[", ":abbrev", "]", "arr_opts", "<<", "\"--candidates=#{opts['candidates']}\"", "if", "opts", "[", ":candidates", "]", "arr_opts", "<<", "\"--match=#{opts['match']}\"", "if", "opts", "[", ":match", "]", "arr_opts", "<<", "committish", "if", "committish", "return", "command", "(", "'describe'", ",", "arr_opts", ")", "end" ]
tries to clone the given repo returns {:repository} (if bare) {:working_directory} otherwise accepts options: :bare:: no working directory :branch:: name of branch to track (rather than 'master') :depth:: the number of commits back to pull :origin:: name of remote (same as remote) :path:: directory where the repo will be cloned :remote:: name of remote (rather than 'origin') :recursive:: after the clone is created, initialize all submodules within, using their default settings. TODO - make this work with SSH password or auth_key READ COMMANDS Returns most recent tag that is reachable from a commit accepts options: :all :tags :contains :debug :exact_match :dirty :abbrev :candidates :long :always :math @param [String|NilClass] committish target commit sha or object name @param [{Symbol=>Object}] opts the given options @return [String] the tag name
[ "tries", "to", "clone", "the", "given", "repo" ]
9bd4407c56068e1604f14a1b6c0c5a84868e6378
https://github.com/ruby-git/ruby-git/blob/9bd4407c56068e1604f14a1b6c0c5a84868e6378/lib/git/lib.rb#L105-L126
train