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
hsgubert/cassandra_migrations
lib/cassandra_migrations/migration.rb
CassandraMigrations.Migration.migrate
def migrate(direction) return unless respond_to?(direction) case direction when :up then announce_migration "migrating" when :down then announce_migration "reverting" end time = Benchmark.measure { send(direction) } case direction when :up then announce_migration "migrated (%.4fs)" % time.real; puts when :down then announce_migration "reverted (%.4fs)" % time.real; puts end end
ruby
def migrate(direction) return unless respond_to?(direction) case direction when :up then announce_migration "migrating" when :down then announce_migration "reverting" end time = Benchmark.measure { send(direction) } case direction when :up then announce_migration "migrated (%.4fs)" % time.real; puts when :down then announce_migration "reverted (%.4fs)" % time.real; puts end end
[ "def", "migrate", "(", "direction", ")", "return", "unless", "respond_to?", "(", "direction", ")", "case", "direction", "when", ":up", "then", "announce_migration", "\"migrating\"", "when", ":down", "then", "announce_migration", "\"reverting\"", "end", "time", "=", "Benchmark", ".", "measure", "{", "send", "(", "direction", ")", "}", "case", "direction", "when", ":up", "then", "announce_migration", "\"migrated (%.4fs)\"", "%", "time", ".", "real", ";", "puts", "when", ":down", "then", "announce_migration", "\"reverted (%.4fs)\"", "%", "time", ".", "real", ";", "puts", "end", "end" ]
Execute this migration in the named direction. The advantage of using this instead of directly calling up or down is that this method gives informative output and benchmarks the time taken.
[ "Execute", "this", "migration", "in", "the", "named", "direction", "." ]
24dae6a4bb39356fa3b596ba120eadf66bca4925
https://github.com/hsgubert/cassandra_migrations/blob/24dae6a4bb39356fa3b596ba120eadf66bca4925/lib/cassandra_migrations/migration.rb#L51-L65
train
hsgubert/cassandra_migrations
lib/cassandra_migrations/migration.rb
CassandraMigrations.Migration.announce_migration
def announce_migration(message) text = "#{name}: #{message}" length = [0, 75 - text.length].max puts "== %s %s" % [text, "=" * length] end
ruby
def announce_migration(message) text = "#{name}: #{message}" length = [0, 75 - text.length].max puts "== %s %s" % [text, "=" * length] end
[ "def", "announce_migration", "(", "message", ")", "text", "=", "\"#{name}: #{message}\"", "length", "=", "[", "0", ",", "75", "-", "text", ".", "length", "]", ".", "max", "puts", "\"== %s %s\"", "%", "[", "text", ",", "\"=\"", "*", "length", "]", "end" ]
Generates output labeled with name of migration and a line that goes up to 75 characters long in the terminal
[ "Generates", "output", "labeled", "with", "name", "of", "migration", "and", "a", "line", "that", "goes", "up", "to", "75", "characters", "long", "in", "the", "terminal" ]
24dae6a4bb39356fa3b596ba120eadf66bca4925
https://github.com/hsgubert/cassandra_migrations/blob/24dae6a4bb39356fa3b596ba120eadf66bca4925/lib/cassandra_migrations/migration.rb#L71-L75
train
yandex-money/yandex-money-sdk-ruby
lib/yandex_money/wallet.rb
YandexMoney.Wallet.operation_history
def operation_history(options=nil) history = RecursiveOpenStruct.new( send_request("/api/operation-history", options).parsed_response ) history.operations = history.operations.map do |operation| RecursiveOpenStruct.new operation end history end
ruby
def operation_history(options=nil) history = RecursiveOpenStruct.new( send_request("/api/operation-history", options).parsed_response ) history.operations = history.operations.map do |operation| RecursiveOpenStruct.new operation end history end
[ "def", "operation_history", "(", "options", "=", "nil", ")", "history", "=", "RecursiveOpenStruct", ".", "new", "(", "send_request", "(", "\"/api/operation-history\"", ",", "options", ")", ".", "parsed_response", ")", "history", ".", "operations", "=", "history", ".", "operations", ".", "map", "do", "|", "operation", "|", "RecursiveOpenStruct", ".", "new", "operation", "end", "history", "end" ]
Returns operation history of a user's wallet @see http://api.yandex.com/money/doc/dg/reference/operation-history.xml @see https://tech.yandex.ru/money/doc/dg/reference/operation-history-docpage/ @param options [Hash] A hash with filter parameters according to documetation @return [Array<RecursiveOpenStruct>] An array containing user's wallet operations. @raise [YandexMoney::InvalidRequestError] HTTP request does not conform to protocol format. Unable to parse HTTP request, or the Authorization header is missing or has an invalid value. @raise [YandexMoney::UnauthorizedError] Nonexistent, expired, or revoked token specified. @raise [YandexMoney::InsufficientScopeError] The token does not have permissions for the requested operation. @raise [YandexMoney::ServerError] A technical error occurs (the server responds with the HTTP code 500 Internal Server Error). The application should repeat the request with the same parameters later.
[ "Returns", "operation", "history", "of", "a", "user", "s", "wallet" ]
5634ebc09aaad3c8f96e2cde20cc60edf6b47899
https://github.com/yandex-money/yandex-money-sdk-ruby/blob/5634ebc09aaad3c8f96e2cde20cc60edf6b47899/lib/yandex_money/wallet.rb#L45-L53
train
yandex-money/yandex-money-sdk-ruby
lib/yandex_money/wallet.rb
YandexMoney.Wallet.operation_details
def operation_details(operation_id) request = send_request("/api/operation-details", operation_id: operation_id) RecursiveOpenStruct.new request.parsed_response end
ruby
def operation_details(operation_id) request = send_request("/api/operation-details", operation_id: operation_id) RecursiveOpenStruct.new request.parsed_response end
[ "def", "operation_details", "(", "operation_id", ")", "request", "=", "send_request", "(", "\"/api/operation-details\"", ",", "operation_id", ":", "operation_id", ")", "RecursiveOpenStruct", ".", "new", "request", ".", "parsed_response", "end" ]
Returns details of operation specified by operation_id @see http://api.yandex.com/money/doc/dg/reference/operation-details.xml @see https://tech.yandex.ru/money/doc/dg/reference/operation-details-docpage/ @param operation_id [String] A operation identifier @return [RecursiveOpenStruct] All details of requested operation. @raise [YandexMoney::InvalidRequestError] HTTP request does not conform to protocol format. Unable to parse HTTP request, or the Authorization header is missing or has an invalid value. @raise [YandexMoney::UnauthorizedError] Nonexistent, expired, or revoked token specified. @raise [YandexMoney::InsufficientScopeError] The token does not have permissions for the requested operation. @raise [YandexMoney::ServerError] A technical error occurs (the server responds with the HTTP code 500 Internal Server Error). The application should repeat the request with the same parameters later.
[ "Returns", "details", "of", "operation", "specified", "by", "operation_id" ]
5634ebc09aaad3c8f96e2cde20cc60edf6b47899
https://github.com/yandex-money/yandex-money-sdk-ruby/blob/5634ebc09aaad3c8f96e2cde20cc60edf6b47899/lib/yandex_money/wallet.rb#L67-L70
train
yandex-money/yandex-money-sdk-ruby
lib/yandex_money/wallet.rb
YandexMoney.Wallet.incoming_transfer_accept
def incoming_transfer_accept(operation_id, protection_code = nil) uri = "/api/incoming-transfer-accept" if protection_code request_body = { operation_id: operation_id, protection_code: protection_code } else request_body = { operation_id: operation_id } end RecursiveOpenStruct.new send_request("/api/incoming-transfer-accept", request_body) end
ruby
def incoming_transfer_accept(operation_id, protection_code = nil) uri = "/api/incoming-transfer-accept" if protection_code request_body = { operation_id: operation_id, protection_code: protection_code } else request_body = { operation_id: operation_id } end RecursiveOpenStruct.new send_request("/api/incoming-transfer-accept", request_body) end
[ "def", "incoming_transfer_accept", "(", "operation_id", ",", "protection_code", "=", "nil", ")", "uri", "=", "\"/api/incoming-transfer-accept\"", "if", "protection_code", "request_body", "=", "{", "operation_id", ":", "operation_id", ",", "protection_code", ":", "protection_code", "}", "else", "request_body", "=", "{", "operation_id", ":", "operation_id", "}", "end", "RecursiveOpenStruct", ".", "new", "send_request", "(", "\"/api/incoming-transfer-accept\"", ",", "request_body", ")", "end" ]
Accepts incoming transfer with a protection code or deferred transfer @see http://api.yandex.com/money/doc/dg/reference/incoming-transfer-accept.xml @see https://tech.yandex.ru/money/doc/dg/reference/incoming-transfer-accept-docpage/ @param operation_id [String] A operation identifier @param protection_code [String] Secret code of four decimal digits. Specified for an incoming transfer proteced by a secret code. Omitted for deferred transfers @return [RecursiveOpenStruct] An information about operation result. @raise [YandexMoney::InvalidRequestError] HTTP request does not conform to protocol format. Unable to parse HTTP request, or the Authorization header is missing or has an invalid value. @raise [YandexMoney::UnauthorizedError] Nonexistent, expired, or revoked token specified. @raise [YandexMoney::InsufficientScopeError] The token does not have permissions for the requested operation. @raise [YandexMoney::ServerError] A technical error occurs (the server responds with the HTTP code 500 Internal Server Error). The application should repeat the request with the same parameters later.
[ "Accepts", "incoming", "transfer", "with", "a", "protection", "code", "or", "deferred", "transfer" ]
5634ebc09aaad3c8f96e2cde20cc60edf6b47899
https://github.com/yandex-money/yandex-money-sdk-ruby/blob/5634ebc09aaad3c8f96e2cde20cc60edf6b47899/lib/yandex_money/wallet.rb#L117-L128
train
ranjib/etcd-ruby
lib/etcd/client.rb
Etcd.Client.api_execute
def api_execute(path, method, options = {}) params = options[:params] case method when :get req = build_http_request(Net::HTTP::Get, path, params) when :post req = build_http_request(Net::HTTP::Post, path, nil, params) when :put req = build_http_request(Net::HTTP::Put, path, nil, params) when :delete req = build_http_request(Net::HTTP::Delete, path, params) else fail "Unknown http action: #{method}" end http = Net::HTTP.new(host, port) http.read_timeout = options[:timeout] || read_timeout setup_https(http) req.basic_auth(user_name, password) if [user_name, password].all? Log.debug("Invoking: '#{req.class}' against '#{path}") res = http.request(req) Log.debug("Response code: #{res.code}") Log.debug("Response body: #{res.body}") process_http_request(res) end
ruby
def api_execute(path, method, options = {}) params = options[:params] case method when :get req = build_http_request(Net::HTTP::Get, path, params) when :post req = build_http_request(Net::HTTP::Post, path, nil, params) when :put req = build_http_request(Net::HTTP::Put, path, nil, params) when :delete req = build_http_request(Net::HTTP::Delete, path, params) else fail "Unknown http action: #{method}" end http = Net::HTTP.new(host, port) http.read_timeout = options[:timeout] || read_timeout setup_https(http) req.basic_auth(user_name, password) if [user_name, password].all? Log.debug("Invoking: '#{req.class}' against '#{path}") res = http.request(req) Log.debug("Response code: #{res.code}") Log.debug("Response body: #{res.body}") process_http_request(res) end
[ "def", "api_execute", "(", "path", ",", "method", ",", "options", "=", "{", "}", ")", "params", "=", "options", "[", ":params", "]", "case", "method", "when", ":get", "req", "=", "build_http_request", "(", "Net", "::", "HTTP", "::", "Get", ",", "path", ",", "params", ")", "when", ":post", "req", "=", "build_http_request", "(", "Net", "::", "HTTP", "::", "Post", ",", "path", ",", "nil", ",", "params", ")", "when", ":put", "req", "=", "build_http_request", "(", "Net", "::", "HTTP", "::", "Put", ",", "path", ",", "nil", ",", "params", ")", "when", ":delete", "req", "=", "build_http_request", "(", "Net", "::", "HTTP", "::", "Delete", ",", "path", ",", "params", ")", "else", "fail", "\"Unknown http action: #{method}\"", "end", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "host", ",", "port", ")", "http", ".", "read_timeout", "=", "options", "[", ":timeout", "]", "||", "read_timeout", "setup_https", "(", "http", ")", "req", ".", "basic_auth", "(", "user_name", ",", "password", ")", "if", "[", "user_name", ",", "password", "]", ".", "all?", "Log", ".", "debug", "(", "\"Invoking: '#{req.class}' against '#{path}\"", ")", "res", "=", "http", ".", "request", "(", "req", ")", "Log", ".", "debug", "(", "\"Response code: #{res.code}\"", ")", "Log", ".", "debug", "(", "\"Response body: #{res.body}\"", ")", "process_http_request", "(", "res", ")", "end" ]
This method sends api request to etcd server. This method has following parameters as argument * path - etcd server path (etcd server end point) * method - the request method used * options - any additional parameters used by request method (optional) rubocop:disable MethodLength, CyclomaticComplexity
[ "This", "method", "sends", "api", "request", "to", "etcd", "server", "." ]
f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917
https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/client.rb#L92-L115
train
ranjib/etcd-ruby
lib/etcd/client.rb
Etcd.Client.process_http_request
def process_http_request(res) case res when HTTP_SUCCESS Log.debug('Http success') res when HTTP_CLIENT_ERROR fail Error.from_http_response(res) else Log.debug('Http error') Log.debug(res.body) res.error! end end
ruby
def process_http_request(res) case res when HTTP_SUCCESS Log.debug('Http success') res when HTTP_CLIENT_ERROR fail Error.from_http_response(res) else Log.debug('Http error') Log.debug(res.body) res.error! end end
[ "def", "process_http_request", "(", "res", ")", "case", "res", "when", "HTTP_SUCCESS", "Log", ".", "debug", "(", "'Http success'", ")", "res", "when", "HTTP_CLIENT_ERROR", "fail", "Error", ".", "from_http_response", "(", "res", ")", "else", "Log", ".", "debug", "(", "'Http error'", ")", "Log", ".", "debug", "(", "res", ".", "body", ")", "res", ".", "error!", "end", "end" ]
need to have original request to process the response when it redirects
[ "need", "to", "have", "original", "request", "to", "process", "the", "response", "when", "it", "redirects" ]
f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917
https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/client.rb#L135-L147
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.list
def list(reverse = false) requests = server.current_requests_full.reject do |request| # Find only pending (= unmerged) requests and output summary. # Explicitly look for local changes git does not yet know about. # TODO: Isn't this a bit confusing? Maybe display pending pushes? local.merged? request.head.sha end source = local.source if requests.empty? puts "No pending requests for '#{source}'." else puts "Pending requests for '#{source}':" puts "ID Updated Comments Title".pink print_requests(requests, reverse) end end
ruby
def list(reverse = false) requests = server.current_requests_full.reject do |request| # Find only pending (= unmerged) requests and output summary. # Explicitly look for local changes git does not yet know about. # TODO: Isn't this a bit confusing? Maybe display pending pushes? local.merged? request.head.sha end source = local.source if requests.empty? puts "No pending requests for '#{source}'." else puts "Pending requests for '#{source}':" puts "ID Updated Comments Title".pink print_requests(requests, reverse) end end
[ "def", "list", "(", "reverse", "=", "false", ")", "requests", "=", "server", ".", "current_requests_full", ".", "reject", "do", "|", "request", "|", "local", ".", "merged?", "request", ".", "head", ".", "sha", "end", "source", "=", "local", ".", "source", "if", "requests", ".", "empty?", "puts", "\"No pending requests for '#{source}'.\"", "else", "puts", "\"Pending requests for '#{source}':\"", "puts", "\"ID Updated Comments Title\"", ".", "pink", "print_requests", "(", "requests", ",", "reverse", ")", "end", "end" ]
List all pending requests.
[ "List", "all", "pending", "requests", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L9-L24
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.show
def show(number, full = false) request = server.get_request_by_number(number) # Determine whether to show full diff or stats only. option = full ? '' : '--stat ' diff = "diff --color=always #{option}HEAD...#{request.head.sha}" # TODO: Refactor into using Request model. print_request_details request puts git_call(diff) print_request_discussions request end
ruby
def show(number, full = false) request = server.get_request_by_number(number) # Determine whether to show full diff or stats only. option = full ? '' : '--stat ' diff = "diff --color=always #{option}HEAD...#{request.head.sha}" # TODO: Refactor into using Request model. print_request_details request puts git_call(diff) print_request_discussions request end
[ "def", "show", "(", "number", ",", "full", "=", "false", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "option", "=", "full", "?", "''", ":", "'--stat '", "diff", "=", "\"diff --color=always #{option}HEAD...#{request.head.sha}\"", "print_request_details", "request", "puts", "git_call", "(", "diff", ")", "print_request_discussions", "request", "end" ]
Show details for a single request.
[ "Show", "details", "for", "a", "single", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L27-L36
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.browse
def browse(number) request = server.get_request_by_number(number) # FIXME: Use request.html_url as soon as we are using our Request model. Launchy.open request._links.html.href end
ruby
def browse(number) request = server.get_request_by_number(number) # FIXME: Use request.html_url as soon as we are using our Request model. Launchy.open request._links.html.href end
[ "def", "browse", "(", "number", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "Launchy", ".", "open", "request", ".", "_links", ".", "html", ".", "href", "end" ]
Open a browser window and review a specified request.
[ "Open", "a", "browser", "window", "and", "review", "a", "specified", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L39-L43
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.checkout
def checkout(number, branch = true) request = server.get_request_by_number(number) puts 'Checking out changes to your local repository.' puts 'To get back to your original state, just run:' puts puts ' git checkout master'.pink puts # Ensure we are looking at the right remote. remote = local.remote_for_request(request) git_call "fetch #{remote}" # Checkout the right branch. branch_name = request.head.ref if branch if local.branch_exists?(:local, branch_name) if local.source_branch == branch_name puts "On branch #{branch_name}." else git_call "checkout #{branch_name}" end else git_call "checkout --track -b #{branch_name} #{remote}/#{branch_name}" end else git_call "checkout #{remote}/#{branch_name}" end end
ruby
def checkout(number, branch = true) request = server.get_request_by_number(number) puts 'Checking out changes to your local repository.' puts 'To get back to your original state, just run:' puts puts ' git checkout master'.pink puts # Ensure we are looking at the right remote. remote = local.remote_for_request(request) git_call "fetch #{remote}" # Checkout the right branch. branch_name = request.head.ref if branch if local.branch_exists?(:local, branch_name) if local.source_branch == branch_name puts "On branch #{branch_name}." else git_call "checkout #{branch_name}" end else git_call "checkout --track -b #{branch_name} #{remote}/#{branch_name}" end else git_call "checkout #{remote}/#{branch_name}" end end
[ "def", "checkout", "(", "number", ",", "branch", "=", "true", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "puts", "'Checking out changes to your local repository.'", "puts", "'To get back to your original state, just run:'", "puts", "puts", "' git checkout master'", ".", "pink", "puts", "remote", "=", "local", ".", "remote_for_request", "(", "request", ")", "git_call", "\"fetch #{remote}\"", "branch_name", "=", "request", ".", "head", ".", "ref", "if", "branch", "if", "local", ".", "branch_exists?", "(", ":local", ",", "branch_name", ")", "if", "local", ".", "source_branch", "==", "branch_name", "puts", "\"On branch #{branch_name}.\"", "else", "git_call", "\"checkout #{branch_name}\"", "end", "else", "git_call", "\"checkout --track -b #{branch_name} #{remote}/#{branch_name}\"", "end", "else", "git_call", "\"checkout #{remote}/#{branch_name}\"", "end", "end" ]
Checkout a specified request's changes to your local repository.
[ "Checkout", "a", "specified", "request", "s", "changes", "to", "your", "local", "repository", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L46-L71
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.approve
def approve(number) request = server.get_request_by_number(number) repo = server.source_repo # TODO: Make this configurable. comment = 'Reviewed and approved.' response = server.add_comment(repo, request.number, comment) if response[:body] == comment puts 'Successfully approved request.' else puts response[:message] end end
ruby
def approve(number) request = server.get_request_by_number(number) repo = server.source_repo # TODO: Make this configurable. comment = 'Reviewed and approved.' response = server.add_comment(repo, request.number, comment) if response[:body] == comment puts 'Successfully approved request.' else puts response[:message] end end
[ "def", "approve", "(", "number", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "repo", "=", "server", ".", "source_repo", "comment", "=", "'Reviewed and approved.'", "response", "=", "server", ".", "add_comment", "(", "repo", ",", "request", ".", "number", ",", "comment", ")", "if", "response", "[", ":body", "]", "==", "comment", "puts", "'Successfully approved request.'", "else", "puts", "response", "[", ":message", "]", "end", "end" ]
Add an approving comment to the request.
[ "Add", "an", "approving", "comment", "to", "the", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L74-L85
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.merge
def merge(number) request = server.get_request_by_number(number) if request.head.repo message = "Accept request ##{request.number} " + "and merge changes into \"#{local.target}\"" command = "merge -m '#{message}' #{request.head.sha}" puts puts "Request title:" puts " #{request.title}" puts puts "Merge command:" puts " git #{command}" puts puts git_call(command) else print_repo_deleted request end end
ruby
def merge(number) request = server.get_request_by_number(number) if request.head.repo message = "Accept request ##{request.number} " + "and merge changes into \"#{local.target}\"" command = "merge -m '#{message}' #{request.head.sha}" puts puts "Request title:" puts " #{request.title}" puts puts "Merge command:" puts " git #{command}" puts puts git_call(command) else print_repo_deleted request end end
[ "def", "merge", "(", "number", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "if", "request", ".", "head", ".", "repo", "message", "=", "\"Accept request ##{request.number} \"", "+", "\"and merge changes into \\\"#{local.target}\\\"\"", "command", "=", "\"merge -m '#{message}' #{request.head.sha}\"", "puts", "puts", "\"Request title:\"", "puts", "\" #{request.title}\"", "puts", "puts", "\"Merge command:\"", "puts", "\" git #{command}\"", "puts", "puts", "git_call", "(", "command", ")", "else", "print_repo_deleted", "request", "end", "end" ]
Accept a specified request by merging it into master.
[ "Accept", "a", "specified", "request", "by", "merging", "it", "into", "master", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L88-L105
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.close
def close(number) request = server.get_request_by_number(number) repo = server.source_repo server.close_issue(repo, request.number) unless server.request_exists?('open', request.number) puts 'Successfully closed request.' end end
ruby
def close(number) request = server.get_request_by_number(number) repo = server.source_repo server.close_issue(repo, request.number) unless server.request_exists?('open', request.number) puts 'Successfully closed request.' end end
[ "def", "close", "(", "number", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "repo", "=", "server", ".", "source_repo", "server", ".", "close_issue", "(", "repo", ",", "request", ".", "number", ")", "unless", "server", ".", "request_exists?", "(", "'open'", ",", "request", ".", "number", ")", "puts", "'Successfully closed request.'", "end", "end" ]
Close a specified request.
[ "Close", "a", "specified", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L108-L115
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.create
def create(upstream = false) # Prepare original_branch and local_branch. # TODO: Allow to use the same switches and parameters that prepare takes. original_branch, local_branch = prepare # Don't create request with uncommitted changes in current branch. if local.uncommitted_changes? puts 'You have uncommitted changes.' puts 'Please stash or commit before creating the request.' return end if local.new_commits?(upstream) # Feature branch differs from local or upstream master. if server.request_exists_for_branch?(upstream) puts 'A pull request already exists for this branch.' puts 'Please update the request directly using `git push`.' return end # Push latest commits to the remote branch (create if necessary). remote = local.remote_for_branch(local_branch) || 'origin' git_call( "push --set-upstream #{remote} #{local_branch}", debug_mode, true ) server.send_pull_request upstream # Return to the user's original branch. git_call "checkout #{original_branch}" else puts 'Nothing to push to remote yet. Commit something first.' end end
ruby
def create(upstream = false) # Prepare original_branch and local_branch. # TODO: Allow to use the same switches and parameters that prepare takes. original_branch, local_branch = prepare # Don't create request with uncommitted changes in current branch. if local.uncommitted_changes? puts 'You have uncommitted changes.' puts 'Please stash or commit before creating the request.' return end if local.new_commits?(upstream) # Feature branch differs from local or upstream master. if server.request_exists_for_branch?(upstream) puts 'A pull request already exists for this branch.' puts 'Please update the request directly using `git push`.' return end # Push latest commits to the remote branch (create if necessary). remote = local.remote_for_branch(local_branch) || 'origin' git_call( "push --set-upstream #{remote} #{local_branch}", debug_mode, true ) server.send_pull_request upstream # Return to the user's original branch. git_call "checkout #{original_branch}" else puts 'Nothing to push to remote yet. Commit something first.' end end
[ "def", "create", "(", "upstream", "=", "false", ")", "original_branch", ",", "local_branch", "=", "prepare", "if", "local", ".", "uncommitted_changes?", "puts", "'You have uncommitted changes.'", "puts", "'Please stash or commit before creating the request.'", "return", "end", "if", "local", ".", "new_commits?", "(", "upstream", ")", "if", "server", ".", "request_exists_for_branch?", "(", "upstream", ")", "puts", "'A pull request already exists for this branch.'", "puts", "'Please update the request directly using `git push`.'", "return", "end", "remote", "=", "local", ".", "remote_for_branch", "(", "local_branch", ")", "||", "'origin'", "git_call", "(", "\"push --set-upstream #{remote} #{local_branch}\"", ",", "debug_mode", ",", "true", ")", "server", ".", "send_pull_request", "upstream", "git_call", "\"checkout #{original_branch}\"", "else", "puts", "'Nothing to push to remote yet. Commit something first.'", "end", "end" ]
Create a new request.
[ "Create", "a", "new", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L138-L166
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.print_repo_deleted
def print_repo_deleted(request) user = request.head.user.login url = request.patch_url puts "Sorry, #{user} deleted the source repository." puts "git-review doesn't support this." puts "Tell the contributor not to do this." puts puts "You can still manually patch your repo by running:" puts puts " curl #{url} | git am" puts end
ruby
def print_repo_deleted(request) user = request.head.user.login url = request.patch_url puts "Sorry, #{user} deleted the source repository." puts "git-review doesn't support this." puts "Tell the contributor not to do this." puts puts "You can still manually patch your repo by running:" puts puts " curl #{url} | git am" puts end
[ "def", "print_repo_deleted", "(", "request", ")", "user", "=", "request", ".", "head", ".", "user", ".", "login", "url", "=", "request", ".", "patch_url", "puts", "\"Sorry, #{user} deleted the source repository.\"", "puts", "\"git-review doesn't support this.\"", "puts", "\"Tell the contributor not to do this.\"", "puts", "puts", "\"You can still manually patch your repo by running:\"", "puts", "puts", "\" curl #{url} | git am\"", "puts", "end" ]
someone deleted the source repo
[ "someone", "deleted", "the", "source", "repo" ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L258-L269
train
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.move_local_changes
def move_local_changes(original_branch, feature_name) feature_branch = create_feature_name(feature_name) # By checking out the feature branch, the commits on the original branch # are copied over. That way we only need to remove pending (local) commits # from the original branch. git_call "checkout -b #{feature_branch}" if local.source_branch == feature_branch # Save any uncommitted changes, to be able to reapply them later. save_uncommitted_changes = local.uncommitted_changes? git_call('stash') if save_uncommitted_changes # Go back to original branch and get rid of pending (local) commits. git_call("checkout #{original_branch}") remote = local.remote_for_branch(original_branch) remote += '/' if remote git_call("reset --hard #{remote}#{original_branch}") git_call("checkout #{feature_branch}") git_call('stash pop') if save_uncommitted_changes feature_branch end end
ruby
def move_local_changes(original_branch, feature_name) feature_branch = create_feature_name(feature_name) # By checking out the feature branch, the commits on the original branch # are copied over. That way we only need to remove pending (local) commits # from the original branch. git_call "checkout -b #{feature_branch}" if local.source_branch == feature_branch # Save any uncommitted changes, to be able to reapply them later. save_uncommitted_changes = local.uncommitted_changes? git_call('stash') if save_uncommitted_changes # Go back to original branch and get rid of pending (local) commits. git_call("checkout #{original_branch}") remote = local.remote_for_branch(original_branch) remote += '/' if remote git_call("reset --hard #{remote}#{original_branch}") git_call("checkout #{feature_branch}") git_call('stash pop') if save_uncommitted_changes feature_branch end end
[ "def", "move_local_changes", "(", "original_branch", ",", "feature_name", ")", "feature_branch", "=", "create_feature_name", "(", "feature_name", ")", "git_call", "\"checkout -b #{feature_branch}\"", "if", "local", ".", "source_branch", "==", "feature_branch", "save_uncommitted_changes", "=", "local", ".", "uncommitted_changes?", "git_call", "(", "'stash'", ")", "if", "save_uncommitted_changes", "git_call", "(", "\"checkout #{original_branch}\"", ")", "remote", "=", "local", ".", "remote_for_branch", "(", "original_branch", ")", "remote", "+=", "'/'", "if", "remote", "git_call", "(", "\"reset --hard #{remote}#{original_branch}\"", ")", "git_call", "(", "\"checkout #{feature_branch}\"", ")", "git_call", "(", "'stash pop'", ")", "if", "save_uncommitted_changes", "feature_branch", "end", "end" ]
Move uncommitted changes from original_branch to a feature_branch. @return [String] the new local branch uncommitted changes are moved to
[ "Move", "uncommitted", "changes", "from", "original_branch", "to", "a", "feature_branch", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L285-L304
train
dwaite/cookiejar
lib/cookiejar/cookie.rb
CookieJar.Cookie.to_s
def to_s(ver = 0, prefix = true) return "#{name}=#{value}" if ver == 0 # we do not need to encode path; the only characters required to be # quoted must be escaped in URI str = prefix ? "$Version=#{version};" : '' str << "#{name}=#{value};$Path=\"#{path}\"" str << ";$Domain=#{domain}" if domain.start_with? '.' str << ";$Port=\"#{ports.join ','}\"" if ports str end
ruby
def to_s(ver = 0, prefix = true) return "#{name}=#{value}" if ver == 0 # we do not need to encode path; the only characters required to be # quoted must be escaped in URI str = prefix ? "$Version=#{version};" : '' str << "#{name}=#{value};$Path=\"#{path}\"" str << ";$Domain=#{domain}" if domain.start_with? '.' str << ";$Port=\"#{ports.join ','}\"" if ports str end
[ "def", "to_s", "(", "ver", "=", "0", ",", "prefix", "=", "true", ")", "return", "\"#{name}=#{value}\"", "if", "ver", "==", "0", "str", "=", "prefix", "?", "\"$Version=#{version};\"", ":", "''", "str", "<<", "\"#{name}=#{value};$Path=\\\"#{path}\\\"\"", "str", "<<", "\";$Domain=#{domain}\"", "if", "domain", ".", "start_with?", "'.'", "str", "<<", "\";$Port=\\\"#{ports.join ','}\\\"\"", "if", "ports", "str", "end" ]
Returns cookie in a format appropriate to send to a server. @param [FixNum] 0 version, 0 for Netscape-style cookies, 1 for RFC2965-style. @param [Boolean] true prefix, for RFC2965, whether to prefix with "$Version=<version>;". Ignored for Netscape-style cookies
[ "Returns", "cookie", "in", "a", "format", "appropriate", "to", "send", "to", "a", "server", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/cookie.rb#L126-L136
train
dwaite/cookiejar
lib/cookiejar/cookie.rb
CookieJar.Cookie.to_hash
def to_hash result = { name: @name, value: @value, domain: @domain, path: @path, created_at: @created_at } { expiry: @expiry, secure: (true if @secure), http_only: (true if @http_only), version: (@version if version != 0), comment: @comment, comment_url: @comment_url, discard: (true if @discard), ports: @ports }.each do |name, value| result[name] = value if value end result end
ruby
def to_hash result = { name: @name, value: @value, domain: @domain, path: @path, created_at: @created_at } { expiry: @expiry, secure: (true if @secure), http_only: (true if @http_only), version: (@version if version != 0), comment: @comment, comment_url: @comment_url, discard: (true if @discard), ports: @ports }.each do |name, value| result[name] = value if value end result end
[ "def", "to_hash", "result", "=", "{", "name", ":", "@name", ",", "value", ":", "@value", ",", "domain", ":", "@domain", ",", "path", ":", "@path", ",", "created_at", ":", "@created_at", "}", "{", "expiry", ":", "@expiry", ",", "secure", ":", "(", "true", "if", "@secure", ")", ",", "http_only", ":", "(", "true", "if", "@http_only", ")", ",", "version", ":", "(", "@version", "if", "version", "!=", "0", ")", ",", "comment", ":", "@comment", ",", "comment_url", ":", "@comment_url", ",", "discard", ":", "(", "true", "if", "@discard", ")", ",", "ports", ":", "@ports", "}", ".", "each", "do", "|", "name", ",", "value", "|", "result", "[", "name", "]", "=", "value", "if", "value", "end", "result", "end" ]
Return a hash representation of the cookie.
[ "Return", "a", "hash", "representation", "of", "the", "cookie", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/cookie.rb#L140-L162
train
dwaite/cookiejar
lib/cookiejar/cookie.rb
CookieJar.Cookie.should_send?
def should_send?(request_uri, script) uri = CookieJar::CookieValidation.to_uri request_uri # cookie path must start with the uri, it must not be a secure cookie # being sent over http, and it must not be a http_only cookie sent to # a script path = if uri.path == '' '/' else uri.path end path_match = path.start_with? @path secure_match = !(@secure && uri.scheme == 'http') script_match = !(script && @http_only) expiry_match = !expired? ports_match = ports.nil? || (ports.include? uri.port) path_match && secure_match && script_match && expiry_match && ports_match end
ruby
def should_send?(request_uri, script) uri = CookieJar::CookieValidation.to_uri request_uri # cookie path must start with the uri, it must not be a secure cookie # being sent over http, and it must not be a http_only cookie sent to # a script path = if uri.path == '' '/' else uri.path end path_match = path.start_with? @path secure_match = !(@secure && uri.scheme == 'http') script_match = !(script && @http_only) expiry_match = !expired? ports_match = ports.nil? || (ports.include? uri.port) path_match && secure_match && script_match && expiry_match && ports_match end
[ "def", "should_send?", "(", "request_uri", ",", "script", ")", "uri", "=", "CookieJar", "::", "CookieValidation", ".", "to_uri", "request_uri", "path", "=", "if", "uri", ".", "path", "==", "''", "'/'", "else", "uri", ".", "path", "end", "path_match", "=", "path", ".", "start_with?", "@path", "secure_match", "=", "!", "(", "@secure", "&&", "uri", ".", "scheme", "==", "'http'", ")", "script_match", "=", "!", "(", "script", "&&", "@http_only", ")", "expiry_match", "=", "!", "expired?", "ports_match", "=", "ports", ".", "nil?", "||", "(", "ports", ".", "include?", "uri", ".", "port", ")", "path_match", "&&", "secure_match", "&&", "script_match", "&&", "expiry_match", "&&", "ports_match", "end" ]
Determine if a cookie should be sent given a request URI along with other options. This currently ignores domain. @param uri [String, URI] the requested page which may need to receive this cookie @param script [Boolean] indicates that cookies with the 'httponly' extension should be ignored @return [Boolean] whether this cookie should be sent to the server
[ "Determine", "if", "a", "cookie", "should", "be", "sent", "given", "a", "request", "URI", "along", "with", "other", "options", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/cookie.rb#L174-L190
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remotes_with_urls
def remotes_with_urls result = {} git_call('remote -vv').split("\n").each do |line| entries = line.split("\t") remote = entries.first target_entry = entries.last.split(' ') direction = target_entry.last[1..-2].to_sym target_url = target_entry.first result[remote] ||= {} result[remote][direction] = target_url end result end
ruby
def remotes_with_urls result = {} git_call('remote -vv').split("\n").each do |line| entries = line.split("\t") remote = entries.first target_entry = entries.last.split(' ') direction = target_entry.last[1..-2].to_sym target_url = target_entry.first result[remote] ||= {} result[remote][direction] = target_url end result end
[ "def", "remotes_with_urls", "result", "=", "{", "}", "git_call", "(", "'remote -vv'", ")", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "entries", "=", "line", ".", "split", "(", "\"\\t\"", ")", "remote", "=", "entries", ".", "first", "target_entry", "=", "entries", ".", "last", ".", "split", "(", "' '", ")", "direction", "=", "target_entry", ".", "last", "[", "1", "..", "-", "2", "]", ".", "to_sym", "target_url", "=", "target_entry", ".", "first", "result", "[", "remote", "]", "||=", "{", "}", "result", "[", "remote", "]", "[", "direction", "]", "=", "target_url", "end", "result", "end" ]
Create a Hash with all remotes as keys and their urls as values.
[ "Create", "a", "Hash", "with", "all", "remotes", "as", "keys", "and", "their", "urls", "as", "values", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L38-L50
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remotes_for_url
def remotes_for_url(remote_url) result = remotes_with_urls.collect do |remote, urls| remote if urls.values.all? { |url| url == remote_url } end result.compact end
ruby
def remotes_for_url(remote_url) result = remotes_with_urls.collect do |remote, urls| remote if urls.values.all? { |url| url == remote_url } end result.compact end
[ "def", "remotes_for_url", "(", "remote_url", ")", "result", "=", "remotes_with_urls", ".", "collect", "do", "|", "remote", ",", "urls", "|", "remote", "if", "urls", ".", "values", ".", "all?", "{", "|", "url", "|", "url", "==", "remote_url", "}", "end", "result", ".", "compact", "end" ]
Collect all remotes for a given url.
[ "Collect", "all", "remotes", "for", "a", "given", "url", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L53-L58
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remote_for_request
def remote_for_request(request) repo_owner = request.head.repo.owner.login remote_url = server.remote_url_for(repo_owner) remotes = remotes_for_url(remote_url) if remotes.empty? remote = "review_#{repo_owner}" git_call("remote add #{remote} #{remote_url}", debug_mode, true) else remote = remotes.first end remote end
ruby
def remote_for_request(request) repo_owner = request.head.repo.owner.login remote_url = server.remote_url_for(repo_owner) remotes = remotes_for_url(remote_url) if remotes.empty? remote = "review_#{repo_owner}" git_call("remote add #{remote} #{remote_url}", debug_mode, true) else remote = remotes.first end remote end
[ "def", "remote_for_request", "(", "request", ")", "repo_owner", "=", "request", ".", "head", ".", "repo", ".", "owner", ".", "login", "remote_url", "=", "server", ".", "remote_url_for", "(", "repo_owner", ")", "remotes", "=", "remotes_for_url", "(", "remote_url", ")", "if", "remotes", ".", "empty?", "remote", "=", "\"review_#{repo_owner}\"", "git_call", "(", "\"remote add #{remote} #{remote_url}\"", ",", "debug_mode", ",", "true", ")", "else", "remote", "=", "remotes", ".", "first", "end", "remote", "end" ]
Find or create the correct remote for a fork with a given owner name.
[ "Find", "or", "create", "the", "correct", "remote", "for", "a", "fork", "with", "a", "given", "owner", "name", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L61-L72
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.clean_remotes
def clean_remotes protected_remotes = remotes_for_branches remotes.each do |remote| # Only remove review remotes that aren't referenced by current branches. if remote.index('review_') == 0 && !protected_remotes.include?(remote) git_call "remote remove #{remote}" end end end
ruby
def clean_remotes protected_remotes = remotes_for_branches remotes.each do |remote| # Only remove review remotes that aren't referenced by current branches. if remote.index('review_') == 0 && !protected_remotes.include?(remote) git_call "remote remove #{remote}" end end end
[ "def", "clean_remotes", "protected_remotes", "=", "remotes_for_branches", "remotes", ".", "each", "do", "|", "remote", "|", "if", "remote", ".", "index", "(", "'review_'", ")", "==", "0", "&&", "!", "protected_remotes", ".", "include?", "(", "remote", ")", "git_call", "\"remote remove #{remote}\"", "end", "end", "end" ]
Remove obsolete remotes with review prefix.
[ "Remove", "obsolete", "remotes", "with", "review", "prefix", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L75-L83
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remotes_for_branches
def remotes_for_branches remotes = git_call('branch -lvv').gsub('* ', '').split("\n").map do |line| line.split(' ')[2][1..-2].split('/').first end remotes.uniq end
ruby
def remotes_for_branches remotes = git_call('branch -lvv').gsub('* ', '').split("\n").map do |line| line.split(' ')[2][1..-2].split('/').first end remotes.uniq end
[ "def", "remotes_for_branches", "remotes", "=", "git_call", "(", "'branch -lvv'", ")", ".", "gsub", "(", "'* '", ",", "''", ")", ".", "split", "(", "\"\\n\"", ")", ".", "map", "do", "|", "line", "|", "line", ".", "split", "(", "' '", ")", "[", "2", "]", "[", "1", "..", "-", "2", "]", ".", "split", "(", "'/'", ")", ".", "first", "end", "remotes", ".", "uniq", "end" ]
Find all remotes which are currently referenced by local branches.
[ "Find", "all", "remotes", "which", "are", "currently", "referenced", "by", "local", "branches", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L91-L96
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remote_for_branch
def remote_for_branch(branch_name) git_call('branch -lvv').gsub('* ', '').split("\n").each do |line| entries = line.split(' ') next unless entries.first == branch_name # Return the remote name or nil for local branches. match = entries[2].match(%r(\[(.*)(\]|:))) return match[1].split('/').first if match end nil end
ruby
def remote_for_branch(branch_name) git_call('branch -lvv').gsub('* ', '').split("\n").each do |line| entries = line.split(' ') next unless entries.first == branch_name # Return the remote name or nil for local branches. match = entries[2].match(%r(\[(.*)(\]|:))) return match[1].split('/').first if match end nil end
[ "def", "remote_for_branch", "(", "branch_name", ")", "git_call", "(", "'branch -lvv'", ")", ".", "gsub", "(", "'* '", ",", "''", ")", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "entries", "=", "line", ".", "split", "(", "' '", ")", "next", "unless", "entries", ".", "first", "==", "branch_name", "match", "=", "entries", "[", "2", "]", ".", "match", "(", "%r(", "\\[", "\\]", ")", ")", "return", "match", "[", "1", "]", ".", "split", "(", "'/'", ")", ".", "first", "if", "match", "end", "nil", "end" ]
Finds the correct remote for a given branch name.
[ "Finds", "the", "correct", "remote", "for", "a", "given", "branch", "name", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L99-L108
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.clean_single
def clean_single(number, force = false) request = server.pull_request(source_repo, number) if request && request.state == 'closed' # ensure there are no unmerged commits or '--force' flag has been set branch_name = request.head.ref if unmerged_commits?(branch_name) && !force puts "Won't delete branches that contain unmerged commits." puts "Use '--force' to override." else delete_branch(branch_name) end end rescue Octokit::NotFound false end
ruby
def clean_single(number, force = false) request = server.pull_request(source_repo, number) if request && request.state == 'closed' # ensure there are no unmerged commits or '--force' flag has been set branch_name = request.head.ref if unmerged_commits?(branch_name) && !force puts "Won't delete branches that contain unmerged commits." puts "Use '--force' to override." else delete_branch(branch_name) end end rescue Octokit::NotFound false end
[ "def", "clean_single", "(", "number", ",", "force", "=", "false", ")", "request", "=", "server", ".", "pull_request", "(", "source_repo", ",", "number", ")", "if", "request", "&&", "request", ".", "state", "==", "'closed'", "branch_name", "=", "request", ".", "head", ".", "ref", "if", "unmerged_commits?", "(", "branch_name", ")", "&&", "!", "force", "puts", "\"Won't delete branches that contain unmerged commits.\"", "puts", "\"Use '--force' to override.\"", "else", "delete_branch", "(", "branch_name", ")", "end", "end", "rescue", "Octokit", "::", "NotFound", "false", "end" ]
clean a single request's obsolete branch
[ "clean", "a", "single", "request", "s", "obsolete", "branch" ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L130-L144
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.clean_all
def clean_all (review_branches - protected_branches).each do |branch_name| # only clean up obsolete branches. delete_branch(branch_name) unless unmerged_commits?(branch_name, false) end end
ruby
def clean_all (review_branches - protected_branches).each do |branch_name| # only clean up obsolete branches. delete_branch(branch_name) unless unmerged_commits?(branch_name, false) end end
[ "def", "clean_all", "(", "review_branches", "-", "protected_branches", ")", ".", "each", "do", "|", "branch_name", "|", "delete_branch", "(", "branch_name", ")", "unless", "unmerged_commits?", "(", "branch_name", ",", "false", ")", "end", "end" ]
clean all obsolete branches
[ "clean", "all", "obsolete", "branches" ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L147-L152
train
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.target_repo
def target_repo(upstream=false) # TODO: Manually override this and set arbitrary repositories if upstream server.repository(source_repo).parent.full_name else source_repo end end
ruby
def target_repo(upstream=false) # TODO: Manually override this and set arbitrary repositories if upstream server.repository(source_repo).parent.full_name else source_repo end end
[ "def", "target_repo", "(", "upstream", "=", "false", ")", "if", "upstream", "server", ".", "repository", "(", "source_repo", ")", ".", "parent", ".", "full_name", "else", "source_repo", "end", "end" ]
if to send a pull request to upstream repo, get the parent as target @return [String] the name of the target repo
[ "if", "to", "send", "a", "pull", "request", "to", "upstream", "repo", "get", "the", "parent", "as", "target" ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L267-L274
train
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.set_cookie2
def set_cookie2(request_uri, cookie_header_value) cookie = Cookie.from_set_cookie2 request_uri, cookie_header_value add_cookie cookie end
ruby
def set_cookie2(request_uri, cookie_header_value) cookie = Cookie.from_set_cookie2 request_uri, cookie_header_value add_cookie cookie end
[ "def", "set_cookie2", "(", "request_uri", ",", "cookie_header_value", ")", "cookie", "=", "Cookie", ".", "from_set_cookie2", "request_uri", ",", "cookie_header_value", "add_cookie", "cookie", "end" ]
Given a request URI and a literal Set-Cookie2 header value, attempt to add the cookie to the cookie store. @param [String, URI] request_uri the resource returning the header @param [String] cookie_header_value the contents of the Set-Cookie2 @return [Cookie] which was created and stored @raise [InvalidCookieError] if the cookie header did not validate
[ "Given", "a", "request", "URI", "and", "a", "literal", "Set", "-", "Cookie2", "header", "value", "attempt", "to", "add", "the", "cookie", "to", "the", "cookie", "store", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L73-L76
train
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.to_a
def to_a result = [] @domains.values.each do |paths| paths.values.each do |cookies| cookies.values.inject result, :<< end end result end
ruby
def to_a result = [] @domains.values.each do |paths| paths.values.each do |cookies| cookies.values.inject result, :<< end end result end
[ "def", "to_a", "result", "=", "[", "]", "@domains", ".", "values", ".", "each", "do", "|", "paths", "|", "paths", ".", "values", ".", "each", "do", "|", "cookies", "|", "cookies", ".", "values", ".", "inject", "result", ",", ":<<", "end", "end", "result", "end" ]
Return an array of all cookie objects in the jar @return [Array<Cookie>] all cookies. Includes any expired cookies which have not yet been removed with expire_cookies
[ "Return", "an", "array", "of", "all", "cookie", "objects", "in", "the", "jar" ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L136-L144
train
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.expire_cookies
def expire_cookies(session = false) @domains.delete_if do |_domain, paths| paths.delete_if do |_path, cookies| cookies.delete_if do |_cookie_name, cookie| cookie.expired? || (session && cookie.session?) end cookies.empty? end paths.empty? end end
ruby
def expire_cookies(session = false) @domains.delete_if do |_domain, paths| paths.delete_if do |_path, cookies| cookies.delete_if do |_cookie_name, cookie| cookie.expired? || (session && cookie.session?) end cookies.empty? end paths.empty? end end
[ "def", "expire_cookies", "(", "session", "=", "false", ")", "@domains", ".", "delete_if", "do", "|", "_domain", ",", "paths", "|", "paths", ".", "delete_if", "do", "|", "_path", ",", "cookies", "|", "cookies", ".", "delete_if", "do", "|", "_cookie_name", ",", "cookie", "|", "cookie", ".", "expired?", "||", "(", "session", "&&", "cookie", ".", "session?", ")", "end", "cookies", ".", "empty?", "end", "paths", ".", "empty?", "end", "end" ]
Look through the jar for any cookies which have passed their expiration date, or session cookies from a previous session @param session [Boolean] whether session cookies should be expired, or just cookies past their expiration date.
[ "Look", "through", "the", "jar", "for", "any", "cookies", "which", "have", "passed", "their", "expiration", "date", "or", "session", "cookies", "from", "a", "previous", "session" ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L191-L201
train
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.get_cookies
def get_cookies(request_uri, opts = {}) uri = to_uri request_uri hosts = Cookie.compute_search_domains uri return [] if hosts.nil? path = if uri.path == '' '/' else uri.path end results = [] hosts.each do |host| domain = find_domain host domain.each do |apath, cookies| next unless path.start_with? apath results += cookies.values.select do |cookie| cookie.should_send? uri, opts[:script] end end end # Sort by path length, longest first results.sort do |lhs, rhs| rhs.path.length <=> lhs.path.length end end
ruby
def get_cookies(request_uri, opts = {}) uri = to_uri request_uri hosts = Cookie.compute_search_domains uri return [] if hosts.nil? path = if uri.path == '' '/' else uri.path end results = [] hosts.each do |host| domain = find_domain host domain.each do |apath, cookies| next unless path.start_with? apath results += cookies.values.select do |cookie| cookie.should_send? uri, opts[:script] end end end # Sort by path length, longest first results.sort do |lhs, rhs| rhs.path.length <=> lhs.path.length end end
[ "def", "get_cookies", "(", "request_uri", ",", "opts", "=", "{", "}", ")", "uri", "=", "to_uri", "request_uri", "hosts", "=", "Cookie", ".", "compute_search_domains", "uri", "return", "[", "]", "if", "hosts", ".", "nil?", "path", "=", "if", "uri", ".", "path", "==", "''", "'/'", "else", "uri", ".", "path", "end", "results", "=", "[", "]", "hosts", ".", "each", "do", "|", "host", "|", "domain", "=", "find_domain", "host", "domain", ".", "each", "do", "|", "apath", ",", "cookies", "|", "next", "unless", "path", ".", "start_with?", "apath", "results", "+=", "cookies", ".", "values", ".", "select", "do", "|", "cookie", "|", "cookie", ".", "should_send?", "uri", ",", "opts", "[", ":script", "]", "end", "end", "end", "results", ".", "sort", "do", "|", "lhs", ",", "rhs", "|", "rhs", ".", "path", ".", "length", "<=>", "lhs", ".", "path", ".", "length", "end", "end" ]
Given a request URI, return a sorted list of Cookie objects. Cookies will be in order per RFC 2965 - sorted by longest path length, but otherwise unordered. @param [String, URI] request_uri the address the HTTP request will be sent to. This must be a full URI, i.e. must include the protocol, if you pass digi.ninja it will fail to find the domain, you must pass http://digi.ninja @param [Hash] opts options controlling returned cookies @option opts [Boolean] :script (false) Cookies marked HTTP-only will be ignored if true @return [Array<Cookie>] cookies which should be sent in the HTTP request
[ "Given", "a", "request", "URI", "return", "a", "sorted", "list", "of", "Cookie", "objects", ".", "Cookies", "will", "be", "in", "order", "per", "RFC", "2965", "-", "sorted", "by", "longest", "path", "length", "but", "otherwise", "unordered", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L215-L241
train
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.get_cookie_header
def get_cookie_header(request_uri, opts = {}) cookies = get_cookies request_uri, opts ver = [[], []] cookies.each do |cookie| ver[cookie.version] << cookie end if ver[1].empty? # can do a netscape-style cookie header, relish the opportunity cookies.map(&:to_s).join ';' else # build a RFC 2965-style cookie header. Split the cookies into # version 0 and 1 groups so that we can reuse the '$Version' header result = '' unless ver[0].empty? result << '$Version=0;' result << ver[0].map do |cookie| (cookie.to_s 1, false) end.join(';') # separate version 0 and 1 with a comma result << ',' end result << '$Version=1;' ver[1].map do |cookie| result << (cookie.to_s 1, false) end result end end
ruby
def get_cookie_header(request_uri, opts = {}) cookies = get_cookies request_uri, opts ver = [[], []] cookies.each do |cookie| ver[cookie.version] << cookie end if ver[1].empty? # can do a netscape-style cookie header, relish the opportunity cookies.map(&:to_s).join ';' else # build a RFC 2965-style cookie header. Split the cookies into # version 0 and 1 groups so that we can reuse the '$Version' header result = '' unless ver[0].empty? result << '$Version=0;' result << ver[0].map do |cookie| (cookie.to_s 1, false) end.join(';') # separate version 0 and 1 with a comma result << ',' end result << '$Version=1;' ver[1].map do |cookie| result << (cookie.to_s 1, false) end result end end
[ "def", "get_cookie_header", "(", "request_uri", ",", "opts", "=", "{", "}", ")", "cookies", "=", "get_cookies", "request_uri", ",", "opts", "ver", "=", "[", "[", "]", ",", "[", "]", "]", "cookies", ".", "each", "do", "|", "cookie", "|", "ver", "[", "cookie", ".", "version", "]", "<<", "cookie", "end", "if", "ver", "[", "1", "]", ".", "empty?", "cookies", ".", "map", "(", "&", ":to_s", ")", ".", "join", "';'", "else", "result", "=", "''", "unless", "ver", "[", "0", "]", ".", "empty?", "result", "<<", "'$Version=0;'", "result", "<<", "ver", "[", "0", "]", ".", "map", "do", "|", "cookie", "|", "(", "cookie", ".", "to_s", "1", ",", "false", ")", "end", ".", "join", "(", "';'", ")", "result", "<<", "','", "end", "result", "<<", "'$Version=1;'", "ver", "[", "1", "]", ".", "map", "do", "|", "cookie", "|", "result", "<<", "(", "cookie", ".", "to_s", "1", ",", "false", ")", "end", "result", "end", "end" ]
Given a request URI, return a string Cookie header.Cookies will be in order per RFC 2965 - sorted by longest path length, but otherwise unordered. @param [String, URI] request_uri the address the HTTP request will be sent to @param [Hash] opts options controlling returned cookies @option opts [Boolean] :script (false) Cookies marked HTTP-only will be ignored if true @return String value of the Cookie header which should be sent on the HTTP request
[ "Given", "a", "request", "URI", "return", "a", "string", "Cookie", "header", ".", "Cookies", "will", "be", "in", "order", "per", "RFC", "2965", "-", "sorted", "by", "longest", "path", "length", "but", "otherwise", "unordered", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L254-L281
train
dkubb/memoizable
lib/memoizable/memory.rb
Memoizable.Memory.[]=
def []=(name, value) memoized = true @memory.compute_if_absent(name) do memoized = false value end fail ArgumentError, "The method #{name} is already memoized" if memoized end
ruby
def []=(name, value) memoized = true @memory.compute_if_absent(name) do memoized = false value end fail ArgumentError, "The method #{name} is already memoized" if memoized end
[ "def", "[]=", "(", "name", ",", "value", ")", "memoized", "=", "true", "@memory", ".", "compute_if_absent", "(", "name", ")", "do", "memoized", "=", "false", "value", "end", "fail", "ArgumentError", ",", "\"The method #{name} is already memoized\"", "if", "memoized", "end" ]
Store the value in memory @param [Symbol] name @param [Object] value @return [undefined] @api public
[ "Store", "the", "value", "in", "memory" ]
fd3a0812bee27b64ecbc80d525e1edc838bd1529
https://github.com/dkubb/memoizable/blob/fd3a0812bee27b64ecbc80d525e1edc838bd1529/lib/memoizable/memory.rb#L42-L49
train
bsiggelkow/jsonify
lib/jsonify/builder.rb
Jsonify.Builder.attributes!
def attributes!(object, *attrs) attrs.each do |attr| method_missing attr, object.send(attr) end end
ruby
def attributes!(object, *attrs) attrs.each do |attr| method_missing attr, object.send(attr) end end
[ "def", "attributes!", "(", "object", ",", "*", "attrs", ")", "attrs", ".", "each", "do", "|", "attr", "|", "method_missing", "attr", ",", "object", ".", "send", "(", "attr", ")", "end", "end" ]
Adds a new JsonPair for each attribute in attrs by taking attr as key and value of that attribute in object. @param object [Object] Object to take values from @param *attrs [Array<Symbol>] Array of attributes for JsonPair keys
[ "Adds", "a", "new", "JsonPair", "for", "each", "attribute", "in", "attrs", "by", "taking", "attr", "as", "key", "and", "value", "of", "that", "attribute", "in", "object", "." ]
94b1a371cd730470d2829c144957a5206e3fae74
https://github.com/bsiggelkow/jsonify/blob/94b1a371cd730470d2829c144957a5206e3fae74/lib/jsonify/builder.rb#L63-L67
train
bsiggelkow/jsonify
lib/jsonify/builder.rb
Jsonify.Builder.array!
def array!(args) __array args.each do |arg| @level += 1 yield arg @level -= 1 value = @stack.pop # If the object created was an array with a single value # assume that just the value should be added if (JsonArray === value && value.values.length <= 1) value = value.values.first end @stack[@level].add value end end
ruby
def array!(args) __array args.each do |arg| @level += 1 yield arg @level -= 1 value = @stack.pop # If the object created was an array with a single value # assume that just the value should be added if (JsonArray === value && value.values.length <= 1) value = value.values.first end @stack[@level].add value end end
[ "def", "array!", "(", "args", ")", "__array", "args", ".", "each", "do", "|", "arg", "|", "@level", "+=", "1", "yield", "arg", "@level", "-=", "1", "value", "=", "@stack", ".", "pop", "if", "(", "JsonArray", "===", "value", "&&", "value", ".", "values", ".", "length", "<=", "1", ")", "value", "=", "value", ".", "values", ".", "first", "end", "@stack", "[", "@level", "]", ".", "add", "value", "end", "end" ]
Creates array of json objects in current element from array passed to this method. Accepts block which yields each array element. @example Create array in root JSON element json.array!(@links) do |link| json.rel link.first json.href link.last end @example compiles to something like ... [ { "rel": "self", "href": "http://example.com/people/123" }, { "rel": "school", "href": "http://gatech.edu" } ]
[ "Creates", "array", "of", "json", "objects", "in", "current", "element", "from", "array", "passed", "to", "this", "method", ".", "Accepts", "block", "which", "yields", "each", "array", "element", "." ]
94b1a371cd730470d2829c144957a5206e3fae74
https://github.com/bsiggelkow/jsonify/blob/94b1a371cd730470d2829c144957a5206e3fae74/lib/jsonify/builder.rb#L131-L148
train
arambert/semrush
lib/semrush/report.rb
Semrush.Report.error
def error(text = "") e = /ERROR\s(\d+)\s::\s(.*)/.match(text) || {} name = (e[2] || "UnknownError").titleize code = e[1] || -1 error_class = name.gsub(/\s/, "") if error_class == "NothingFound" [] else begin raise Semrush::Exception.const_get(error_class).new(self, "#{name} (#{code})") rescue raise Semrush::Exception::Base.new(self, "#{name} (#{code}) *** error_class=#{error_class} not implemented ***") end end end
ruby
def error(text = "") e = /ERROR\s(\d+)\s::\s(.*)/.match(text) || {} name = (e[2] || "UnknownError").titleize code = e[1] || -1 error_class = name.gsub(/\s/, "") if error_class == "NothingFound" [] else begin raise Semrush::Exception.const_get(error_class).new(self, "#{name} (#{code})") rescue raise Semrush::Exception::Base.new(self, "#{name} (#{code}) *** error_class=#{error_class} not implemented ***") end end end
[ "def", "error", "(", "text", "=", "\"\"", ")", "e", "=", "/", "\\s", "\\d", "\\s", "\\s", "/", ".", "match", "(", "text", ")", "||", "{", "}", "name", "=", "(", "e", "[", "2", "]", "||", "\"UnknownError\"", ")", ".", "titleize", "code", "=", "e", "[", "1", "]", "||", "-", "1", "error_class", "=", "name", ".", "gsub", "(", "/", "\\s", "/", ",", "\"\"", ")", "if", "error_class", "==", "\"NothingFound\"", "[", "]", "else", "begin", "raise", "Semrush", "::", "Exception", ".", "const_get", "(", "error_class", ")", ".", "new", "(", "self", ",", "\"#{name} (#{code})\"", ")", "rescue", "raise", "Semrush", "::", "Exception", "::", "Base", ".", "new", "(", "self", ",", "\"#{name} (#{code}) *** error_class=#{error_class} not implemented ***\"", ")", "end", "end", "end" ]
Format and raise an error
[ "Format", "and", "raise", "an", "error" ]
2b22a14d430ec0e04c37ce6df5d6852973cc0271
https://github.com/arambert/semrush/blob/2b22a14d430ec0e04c37ce6df5d6852973cc0271/lib/semrush/report.rb#L328-L343
train
yujinakayama/astrolabe
lib/astrolabe/node.rb
Astrolabe.Node.each_ancestor
def each_ancestor(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_ancestors(&block) else visit_ancestors_with_types(types, &block) end self end
ruby
def each_ancestor(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_ancestors(&block) else visit_ancestors_with_types(types, &block) end self end
[ "def", "each_ancestor", "(", "*", "types", ",", "&", "block", ")", "return", "to_enum", "(", "__method__", ",", "*", "types", ")", "unless", "block_given?", "types", ".", "flatten!", "if", "types", ".", "empty?", "visit_ancestors", "(", "&", "block", ")", "else", "visit_ancestors_with_types", "(", "types", ",", "&", "block", ")", "end", "self", "end" ]
Calls the given block for each ancestor node in the order from parent to root. If no block is given, an `Enumerator` is returned. @overload each_ancestor Yield all nodes. @overload each_ancestor(type) Yield only nodes matching the type. @param [Symbol] type a node type @overload each_ancestor(type_a, type_b, ...) Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type @overload each_ancestor(types) Yield only nodes matching any of types in the array. @param [Array<Symbol>] types an array containing node types @yieldparam [Node] node each ancestor node @return [self] if a block is given @return [Enumerator] if no block is given
[ "Calls", "the", "given", "block", "for", "each", "ancestor", "node", "in", "the", "order", "from", "parent", "to", "root", ".", "If", "no", "block", "is", "given", "an", "Enumerator", "is", "returned", "." ]
d7279b21e9fef9f56a48f87ef1403eb5264a9600
https://github.com/yujinakayama/astrolabe/blob/d7279b21e9fef9f56a48f87ef1403eb5264a9600/lib/astrolabe/node.rb#L89-L101
train
yujinakayama/astrolabe
lib/astrolabe/node.rb
Astrolabe.Node.each_child_node
def each_child_node(*types) return to_enum(__method__, *types) unless block_given? types.flatten! children.each do |child| next unless child.is_a?(Node) yield child if types.empty? || types.include?(child.type) end self end
ruby
def each_child_node(*types) return to_enum(__method__, *types) unless block_given? types.flatten! children.each do |child| next unless child.is_a?(Node) yield child if types.empty? || types.include?(child.type) end self end
[ "def", "each_child_node", "(", "*", "types", ")", "return", "to_enum", "(", "__method__", ",", "*", "types", ")", "unless", "block_given?", "types", ".", "flatten!", "children", ".", "each", "do", "|", "child", "|", "next", "unless", "child", ".", "is_a?", "(", "Node", ")", "yield", "child", "if", "types", ".", "empty?", "||", "types", ".", "include?", "(", "child", ".", "type", ")", "end", "self", "end" ]
Calls the given block for each child node. If no block is given, an `Enumerator` is returned. Note that this is different from `node.children.each { |child| ... }` which yields all children including non-node element. @overload each_child_node Yield all nodes. @overload each_child_node(type) Yield only nodes matching the type. @param [Symbol] type a node type @overload each_child_node(type_a, type_b, ...) Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type @overload each_child_node(types) Yield only nodes matching any of types in the array. @param [Array<Symbol>] types an array containing node types @yieldparam [Node] node each child node @return [self] if a block is given @return [Enumerator] if no block is given
[ "Calls", "the", "given", "block", "for", "each", "child", "node", ".", "If", "no", "block", "is", "given", "an", "Enumerator", "is", "returned", "." ]
d7279b21e9fef9f56a48f87ef1403eb5264a9600
https://github.com/yujinakayama/astrolabe/blob/d7279b21e9fef9f56a48f87ef1403eb5264a9600/lib/astrolabe/node.rb#L132-L143
train
yujinakayama/astrolabe
lib/astrolabe/node.rb
Astrolabe.Node.each_descendant
def each_descendant(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
ruby
def each_descendant(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
[ "def", "each_descendant", "(", "*", "types", ",", "&", "block", ")", "return", "to_enum", "(", "__method__", ",", "*", "types", ")", "unless", "block_given?", "types", ".", "flatten!", "if", "types", ".", "empty?", "visit_descendants", "(", "&", "block", ")", "else", "visit_descendants_with_types", "(", "types", ",", "&", "block", ")", "end", "self", "end" ]
Calls the given block for each descendant node with depth first order. If no block is given, an `Enumerator` is returned. @overload each_descendant Yield all nodes. @overload each_descendant(type) Yield only nodes matching the type. @param [Symbol] type a node type @overload each_descendant(type_a, type_b, ...) Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type @overload each_descendant(types) Yield only nodes matching any of types in the array. @param [Array<Symbol>] types an array containing node types @yieldparam [Node] node each descendant node @return [self] if a block is given @return [Enumerator] if no block is given
[ "Calls", "the", "given", "block", "for", "each", "descendant", "node", "with", "depth", "first", "order", ".", "If", "no", "block", "is", "given", "an", "Enumerator", "is", "returned", "." ]
d7279b21e9fef9f56a48f87ef1403eb5264a9600
https://github.com/yujinakayama/astrolabe/blob/d7279b21e9fef9f56a48f87ef1403eb5264a9600/lib/astrolabe/node.rb#L171-L183
train
yujinakayama/astrolabe
lib/astrolabe/node.rb
Astrolabe.Node.each_node
def each_node(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! yield self if types.empty? || types.include?(type) if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
ruby
def each_node(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! yield self if types.empty? || types.include?(type) if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
[ "def", "each_node", "(", "*", "types", ",", "&", "block", ")", "return", "to_enum", "(", "__method__", ",", "*", "types", ")", "unless", "block_given?", "types", ".", "flatten!", "yield", "self", "if", "types", ".", "empty?", "||", "types", ".", "include?", "(", "type", ")", "if", "types", ".", "empty?", "visit_descendants", "(", "&", "block", ")", "else", "visit_descendants_with_types", "(", "types", ",", "&", "block", ")", "end", "self", "end" ]
Calls the given block for the receiver and each descendant node with depth first order. If no block is given, an `Enumerator` is returned. This method would be useful when you treat the receiver node as a root of tree and want to iterate all nodes in the tree. @overload each_node Yield all nodes. @overload each_node(type) Yield only nodes matching the type. @param [Symbol] type a node type @overload each_node(type_a, type_b, ...) Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type @overload each_node(types) Yield only nodes matching any of types in the array. @param [Array<Symbol>] types an array containing node types @yieldparam [Node] node each node @return [self] if a block is given @return [Enumerator] if no block is given
[ "Calls", "the", "given", "block", "for", "the", "receiver", "and", "each", "descendant", "node", "with", "depth", "first", "order", ".", "If", "no", "block", "is", "given", "an", "Enumerator", "is", "returned", "." ]
d7279b21e9fef9f56a48f87ef1403eb5264a9600
https://github.com/yujinakayama/astrolabe/blob/d7279b21e9fef9f56a48f87ef1403eb5264a9600/lib/astrolabe/node.rb#L214-L228
train
ging/avatars_for_rails
lib/avatars_for_rails/active_record.rb
AvatarsForRails.ActiveRecord.acts_as_avatarable
def acts_as_avatarable(options = {}) options[:styles] ||= AvatarsForRails.avatarable_styles cattr_accessor :avatarable_options self.avatarable_options = options include AvatarsForRails::Avatarable end
ruby
def acts_as_avatarable(options = {}) options[:styles] ||= AvatarsForRails.avatarable_styles cattr_accessor :avatarable_options self.avatarable_options = options include AvatarsForRails::Avatarable end
[ "def", "acts_as_avatarable", "(", "options", "=", "{", "}", ")", "options", "[", ":styles", "]", "||=", "AvatarsForRails", ".", "avatarable_styles", "cattr_accessor", ":avatarable_options", "self", ".", "avatarable_options", "=", "options", "include", "AvatarsForRails", "::", "Avatarable", "end" ]
Adds an ActiveRecord model with support for avatars
[ "Adds", "an", "ActiveRecord", "model", "with", "support", "for", "avatars" ]
b3621788966a1fa89b855e2ca0425282c80bb7aa
https://github.com/ging/avatars_for_rails/blob/b3621788966a1fa89b855e2ca0425282c80bb7aa/lib/avatars_for_rails/active_record.rb#L4-L11
train
dkubb/memoizable
lib/memoizable/method_builder.rb
Memoizable.MethodBuilder.create_memoized_method
def create_memoized_method name, method, freezer = @method_name, @original_method, @freezer @descendant.module_eval do define_method(name) do |&block| fail BlockNotAllowedError.new(self.class, name) if block memoized_method_cache.fetch(name) do freezer.call(method.bind(self).call) end end end end
ruby
def create_memoized_method name, method, freezer = @method_name, @original_method, @freezer @descendant.module_eval do define_method(name) do |&block| fail BlockNotAllowedError.new(self.class, name) if block memoized_method_cache.fetch(name) do freezer.call(method.bind(self).call) end end end end
[ "def", "create_memoized_method", "name", ",", "method", ",", "freezer", "=", "@method_name", ",", "@original_method", ",", "@freezer", "@descendant", ".", "module_eval", "do", "define_method", "(", "name", ")", "do", "|", "&", "block", "|", "fail", "BlockNotAllowedError", ".", "new", "(", "self", ".", "class", ",", "name", ")", "if", "block", "memoized_method_cache", ".", "fetch", "(", "name", ")", "do", "freezer", ".", "call", "(", "method", ".", "bind", "(", "self", ")", ".", "call", ")", "end", "end", "end", "end" ]
Create a new memoized method @return [undefined] @api private
[ "Create", "a", "new", "memoized", "method" ]
fd3a0812bee27b64ecbc80d525e1edc838bd1529
https://github.com/dkubb/memoizable/blob/fd3a0812bee27b64ecbc80d525e1edc838bd1529/lib/memoizable/method_builder.rb#L111-L121
train
mikamai/ruby-lol
lib/lol/champion_mastery_request.rb
Lol.ChampionMasteryRequest.all
def all summoner_id: result = perform_request api_url "champion-masteries/by-summoner/#{summoner_id}" result.map { |c| DynamicModel.new c } end
ruby
def all summoner_id: result = perform_request api_url "champion-masteries/by-summoner/#{summoner_id}" result.map { |c| DynamicModel.new c } end
[ "def", "all", "summoner_id", ":", "result", "=", "perform_request", "api_url", "\"champion-masteries/by-summoner/#{summoner_id}\"", "result", ".", "map", "{", "|", "c", "|", "DynamicModel", ".", "new", "c", "}", "end" ]
Get all champion mastery entries sorted by number of champion points descending See: https://developer.riotgames.com/api-methods/#champion-mastery-v3/GET_getAllChampionMasteries @param [Integer] summoner_id Summoner ID associated with the player @return [Array<Lol::DynamicModel>] Champion Masteries
[ "Get", "all", "champion", "mastery", "entries", "sorted", "by", "number", "of", "champion", "points", "descending" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/champion_mastery_request.rb#L25-L28
train
mikamai/ruby-lol
lib/lol/champion_request.rb
Lol.ChampionRequest.all
def all free_to_play: false result = perform_request api_url("champions", "freeToPlay" => free_to_play) result["champions"].map { |c| DynamicModel.new c } end
ruby
def all free_to_play: false result = perform_request api_url("champions", "freeToPlay" => free_to_play) result["champions"].map { |c| DynamicModel.new c } end
[ "def", "all", "free_to_play", ":", "false", "result", "=", "perform_request", "api_url", "(", "\"champions\"", ",", "\"freeToPlay\"", "=>", "free_to_play", ")", "result", "[", "\"champions\"", "]", ".", "map", "{", "|", "c", "|", "DynamicModel", ".", "new", "c", "}", "end" ]
Retrieve all champions See: https://developer.riotgames.com/api-methods/#champion-v3/GET_getChampions @param free_to_play [Boolean] filter param to retrieve only free to play champions @return [Array<Lol::DynamicModel>] an array of champions
[ "Retrieve", "all", "champions" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/champion_request.rb#L11-L14
train
contactually/zuora-ruby
lib/zuora/response.rb
Zuora.Response.symbolize_key
def symbolize_key(key) return key unless key.respond_to?(:split) key.split(':').last.underscore.to_sym end
ruby
def symbolize_key(key) return key unless key.respond_to?(:split) key.split(':').last.underscore.to_sym end
[ "def", "symbolize_key", "(", "key", ")", "return", "key", "unless", "key", ".", "respond_to?", "(", ":split", ")", "key", ".", "split", "(", "':'", ")", ".", "last", ".", "underscore", ".", "to_sym", "end" ]
Given a key, convert to symbol, removing XML namespace, if any. @param [String] key - a key, either "abc" or "abc:def" @return [Symbol]
[ "Given", "a", "key", "convert", "to", "symbol", "removing", "XML", "namespace", "if", "any", "." ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/zuora/response.rb#L53-L56
train
contactually/zuora-ruby
lib/zuora/response.rb
Zuora.Response.symbolize_keys_deep
def symbolize_keys_deep(hash) return hash unless hash.is_a?(Hash) Hash[hash.map do |key, value| # if value is array, loop each element and recursively symbolize keys if value.is_a? Array value = value.map { |element| symbolize_keys_deep(element) } # if value is hash, recursively symbolize keys elsif value.is_a? Hash value = symbolize_keys_deep(value) end [symbolize_key(key), value] end] end
ruby
def symbolize_keys_deep(hash) return hash unless hash.is_a?(Hash) Hash[hash.map do |key, value| # if value is array, loop each element and recursively symbolize keys if value.is_a? Array value = value.map { |element| symbolize_keys_deep(element) } # if value is hash, recursively symbolize keys elsif value.is_a? Hash value = symbolize_keys_deep(value) end [symbolize_key(key), value] end] end
[ "def", "symbolize_keys_deep", "(", "hash", ")", "return", "hash", "unless", "hash", ".", "is_a?", "(", "Hash", ")", "Hash", "[", "hash", ".", "map", "do", "|", "key", ",", "value", "|", "if", "value", ".", "is_a?", "Array", "value", "=", "value", ".", "map", "{", "|", "element", "|", "symbolize_keys_deep", "(", "element", ")", "}", "elsif", "value", ".", "is_a?", "Hash", "value", "=", "symbolize_keys_deep", "(", "value", ")", "end", "[", "symbolize_key", "(", "key", ")", ",", "value", "]", "end", "]", "end" ]
Recursively transforms a hash @param [Hash] hash @return [Hash]
[ "Recursively", "transforms", "a", "hash" ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/zuora/response.rb#L61-L75
train
contactually/zuora-ruby
lib/zuora/client.rb
Zuora.Client.to_s
def to_s public_vars = instance_variables.reject do |var| INSTANCE_VARIABLE_LOG_BLACKLIST.include? var end public_vars.map! do |var| "#{var}=\"#{instance_variable_get(var)}\"" end public_vars = public_vars.join(' ') "<##{self.class}:#{object_id.to_s(8)} #{public_vars}>" end
ruby
def to_s public_vars = instance_variables.reject do |var| INSTANCE_VARIABLE_LOG_BLACKLIST.include? var end public_vars.map! do |var| "#{var}=\"#{instance_variable_get(var)}\"" end public_vars = public_vars.join(' ') "<##{self.class}:#{object_id.to_s(8)} #{public_vars}>" end
[ "def", "to_s", "public_vars", "=", "instance_variables", ".", "reject", "do", "|", "var", "|", "INSTANCE_VARIABLE_LOG_BLACKLIST", ".", "include?", "var", "end", "public_vars", ".", "map!", "do", "|", "var", "|", "\"#{var}=\\\"#{instance_variable_get(var)}\\\"\"", "end", "public_vars", "=", "public_vars", ".", "join", "(", "' '", ")", "\"<##{self.class}:#{object_id.to_s(8)} #{public_vars}>\"", "end" ]
Like Object.to_s, except excludes BLACKLISTed instance vars
[ "Like", "Object", ".", "to_s", "except", "excludes", "BLACKLISTed", "instance", "vars" ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/zuora/client.rb#L32-L44
train
mikamai/ruby-lol
lib/lol/tournament_request.rb
Lol.TournamentRequest.create_tournament
def create_tournament provider_id:, name: nil body = { "providerId" => provider_id, "name" => name }.delete_if do |k, v| v.nil? end perform_request api_url("tournaments"), :post, body end
ruby
def create_tournament provider_id:, name: nil body = { "providerId" => provider_id, "name" => name }.delete_if do |k, v| v.nil? end perform_request api_url("tournaments"), :post, body end
[ "def", "create_tournament", "provider_id", ":", ",", "name", ":", "nil", "body", "=", "{", "\"providerId\"", "=>", "provider_id", ",", "\"name\"", "=>", "name", "}", ".", "delete_if", "do", "|", "k", ",", "v", "|", "v", ".", "nil?", "end", "perform_request", "api_url", "(", "\"tournaments\"", ")", ",", ":post", ",", "body", "end" ]
Creates a tournament and returns its ID. @param [Integer] provider_id The provider ID to specify the regional registered provider data to associate this tournament. @param [String] name Name of the tournament @return [Integer] Tournament ID
[ "Creates", "a", "tournament", "and", "returns", "its", "ID", "." ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/tournament_request.rb#L28-L33
train
mikamai/ruby-lol
lib/lol/tournament_request.rb
Lol.TournamentRequest.create_codes
def create_codes tournament_id:, count: nil, allowed_participants: nil, map_type: "SUMMONERS_RIFT", metadata: nil, team_size: 5, pick_type: "TOURNAMENT_DRAFT", spectator_type: "ALL" body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "metadata" => metadata, "pickType" => pick_type, "spectatorType" => spectator_type, "teamSize" => team_size }.compact uri_params = { "tournamentId" => tournament_id, "count" => count }.compact perform_request api_url("codes", uri_params), :post, body end
ruby
def create_codes tournament_id:, count: nil, allowed_participants: nil, map_type: "SUMMONERS_RIFT", metadata: nil, team_size: 5, pick_type: "TOURNAMENT_DRAFT", spectator_type: "ALL" body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "metadata" => metadata, "pickType" => pick_type, "spectatorType" => spectator_type, "teamSize" => team_size }.compact uri_params = { "tournamentId" => tournament_id, "count" => count }.compact perform_request api_url("codes", uri_params), :post, body end
[ "def", "create_codes", "tournament_id", ":", ",", "count", ":", "nil", ",", "allowed_participants", ":", "nil", ",", "map_type", ":", "\"SUMMONERS_RIFT\"", ",", "metadata", ":", "nil", ",", "team_size", ":", "5", ",", "pick_type", ":", "\"TOURNAMENT_DRAFT\"", ",", "spectator_type", ":", "\"ALL\"", "body", "=", "{", "\"allowedSummonerIds\"", "=>", "allowed_participants", ",", "\"mapType\"", "=>", "map_type", ",", "\"metadata\"", "=>", "metadata", ",", "\"pickType\"", "=>", "pick_type", ",", "\"spectatorType\"", "=>", "spectator_type", ",", "\"teamSize\"", "=>", "team_size", "}", ".", "compact", "uri_params", "=", "{", "\"tournamentId\"", "=>", "tournament_id", ",", "\"count\"", "=>", "count", "}", ".", "compact", "perform_request", "api_url", "(", "\"codes\"", ",", "uri_params", ")", ",", ":post", ",", "body", "end" ]
Create a tournament code for the given tournament. @param [Integer] count The number of codes to create (max 1000) @param [Integer] tournament_id The tournament ID @param [String] spectator_type The spectator type of the game. Valid values are NONE, LOBBYONLY, ALL. @param [Integer] team_size The team size of the game. Valid values are 1-5. @param [String] pick_type The pick type of the game. Valid values are BLIND_PICK, DRAFT_MODE, ALL_RANDOM, TOURNAMENT_DRAFT. @param [String] map_type The map type of the game. Valid values are SUMMONERS_RIFT, TWISTED_TREELINE, CRYSTAL_SCAR, and HOWLING_ABYSS. @param [Array<Integer>] allowed_participants List of participants in order to validate the players eligible to join the lobby. @param [String] metadata Optional string that may contain any data in any format, if specified at all. Used to denote any custom information about the game. @return [Array<String>] generated tournament codes
[ "Create", "a", "tournament", "code", "for", "the", "given", "tournament", "." ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/tournament_request.rb#L45-L61
train
mikamai/ruby-lol
lib/lol/tournament_request.rb
Lol.TournamentRequest.update_code
def update_code tournament_code, allowed_participants: nil, map_type: nil, pick_type: nil, spectator_type: nil body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "pickType" => pick_type, "spectatorType" => spectator_type }.compact perform_request api_url("codes/#{tournament_code}"), :put, body end
ruby
def update_code tournament_code, allowed_participants: nil, map_type: nil, pick_type: nil, spectator_type: nil body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "pickType" => pick_type, "spectatorType" => spectator_type }.compact perform_request api_url("codes/#{tournament_code}"), :put, body end
[ "def", "update_code", "tournament_code", ",", "allowed_participants", ":", "nil", ",", "map_type", ":", "nil", ",", "pick_type", ":", "nil", ",", "spectator_type", ":", "nil", "body", "=", "{", "\"allowedSummonerIds\"", "=>", "allowed_participants", ",", "\"mapType\"", "=>", "map_type", ",", "\"pickType\"", "=>", "pick_type", ",", "\"spectatorType\"", "=>", "spectator_type", "}", ".", "compact", "perform_request", "api_url", "(", "\"codes/#{tournament_code}\"", ")", ",", ":put", ",", "body", "end" ]
Update the pick type, map, spectator type, or allowed summoners for a code. @param [String] tournament_code The tournament code to update @param [Array<Integer>] allowed_participants List of participants in order to validate the players eligible to join the lobby. @param [String] map_type The map type of the game. Valid values are SUMMONERS_RIFT, TWISTED_TREELINE, CRYSTAL_SCAR, and HOWLING_ABYSS. @param [String] pick_type The pick type of the game. Valid values are BLIND_PICK, DRAFT_MODE, ALL_RANDOM, TOURNAMENT_DRAFT. @param [String] spectator_type The spectator type of the game. Valid values are NONE, LOBBYONLY, ALL.
[ "Update", "the", "pick", "type", "map", "spectator", "type", "or", "allowed", "summoners", "for", "a", "code", "." ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/tournament_request.rb#L69-L77
train
mikamai/ruby-lol
lib/lol/tournament_request.rb
Lol.TournamentRequest.all_lobby_events
def all_lobby_events tournament_code: result = perform_request api_url "lobby-events/by-code/#{tournament_code}" result["eventList"].map { |e| DynamicModel.new e } end
ruby
def all_lobby_events tournament_code: result = perform_request api_url "lobby-events/by-code/#{tournament_code}" result["eventList"].map { |e| DynamicModel.new e } end
[ "def", "all_lobby_events", "tournament_code", ":", "result", "=", "perform_request", "api_url", "\"lobby-events/by-code/#{tournament_code}\"", "result", "[", "\"eventList\"", "]", ".", "map", "{", "|", "e", "|", "DynamicModel", ".", "new", "e", "}", "end" ]
Gets a list of lobby events by tournament code @param [String] tournament_code the tournament code string @return [Array<DynamicModel>] List of lobby events
[ "Gets", "a", "list", "of", "lobby", "events", "by", "tournament", "code" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/tournament_request.rb#L89-L92
train
mikamai/ruby-lol
lib/lol/summoner_request.rb
Lol.SummonerRequest.find_by_name
def find_by_name name name = CGI.escape name.downcase.gsub(/\s/, '') DynamicModel.new perform_request api_url "summoners/by-name/#{name}" end
ruby
def find_by_name name name = CGI.escape name.downcase.gsub(/\s/, '') DynamicModel.new perform_request api_url "summoners/by-name/#{name}" end
[ "def", "find_by_name", "name", "name", "=", "CGI", ".", "escape", "name", ".", "downcase", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", "DynamicModel", ".", "new", "perform_request", "api_url", "\"summoners/by-name/#{name}\"", "end" ]
Get a summoner by summoner name. @param [String] name Summoner name @return [DynamicModel] Summoner representation
[ "Get", "a", "summoner", "by", "summoner", "name", "." ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/summoner_request.rb#L21-L24
train
pazdera/scriptster
lib/scriptster/configuration.rb
Scriptster.Configuration.apply
def apply Logger.set_name @name if @name Logger.set_verbosity @verbosity if @verbosity Logger.set_file @file if @file Logger.set_format @log_format if @log_format if @colours.is_a? Proc @colours.call else ColourThemes.send @colours.to_sym end end
ruby
def apply Logger.set_name @name if @name Logger.set_verbosity @verbosity if @verbosity Logger.set_file @file if @file Logger.set_format @log_format if @log_format if @colours.is_a? Proc @colours.call else ColourThemes.send @colours.to_sym end end
[ "def", "apply", "Logger", ".", "set_name", "@name", "if", "@name", "Logger", ".", "set_verbosity", "@verbosity", "if", "@verbosity", "Logger", ".", "set_file", "@file", "if", "@file", "Logger", ".", "set_format", "@log_format", "if", "@log_format", "if", "@colours", ".", "is_a?", "Proc", "@colours", ".", "call", "else", "ColourThemes", ".", "send", "@colours", ".", "to_sym", "end", "end" ]
Put the settings from this object in effect. This function will distribute the configuration to the appropriate objects and modules.
[ "Put", "the", "settings", "from", "this", "object", "in", "effect", "." ]
8d4fcdaf06e867f1f460e980a9defdf36d0ac29d
https://github.com/pazdera/scriptster/blob/8d4fcdaf06e867f1f460e980a9defdf36d0ac29d/lib/scriptster/configuration.rb#L52-L63
train
mikamai/ruby-lol
lib/lol/request.rb
Lol.Request.api_url
def api_url path, params = {} url = File.join File.join(api_base_url, api_base_path), path "#{url}?#{api_query_string params}" end
ruby
def api_url path, params = {} url = File.join File.join(api_base_url, api_base_path), path "#{url}?#{api_query_string params}" end
[ "def", "api_url", "path", ",", "params", "=", "{", "}", "url", "=", "File", ".", "join", "File", ".", "join", "(", "api_base_url", ",", "api_base_path", ")", ",", "path", "\"#{url}?#{api_query_string params}\"", "end" ]
Returns a full url for an API call @param path [String] API path to call @return [String] full fledged url
[ "Returns", "a", "full", "url", "for", "an", "API", "call" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/request.rb#L82-L85
train
mikamai/ruby-lol
lib/lol/request.rb
Lol.Request.clean_url
def clean_url(url) uri = URI.parse(url) uri.query = CGI.parse(uri.query || '').reject { |k| k == 'api_key' }.to_query uri.to_s end
ruby
def clean_url(url) uri = URI.parse(url) uri.query = CGI.parse(uri.query || '').reject { |k| k == 'api_key' }.to_query uri.to_s end
[ "def", "clean_url", "(", "url", ")", "uri", "=", "URI", ".", "parse", "(", "url", ")", "uri", ".", "query", "=", "CGI", ".", "parse", "(", "uri", ".", "query", "||", "''", ")", ".", "reject", "{", "|", "k", "|", "k", "==", "'api_key'", "}", ".", "to_query", "uri", ".", "to_s", "end" ]
Returns just a path from a full api url @return [String]
[ "Returns", "just", "a", "path", "from", "a", "full", "api", "url" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/request.rb#L105-L109
train
mikamai/ruby-lol
lib/lol/request.rb
Lol.Request.perform_request
def perform_request url, verb = :get, body = nil, options = {} options_id = options.inspect can_cache = [:post, :put].include?(verb) ? false : cached? if can_cache && result = store.get("#{clean_url(url)}#{options_id}") return JSON.parse(result) end response = perform_rate_limited_request(url, verb, body, options) store.setex "#{clean_url(url)}#{options_id}", ttl, response.to_json if can_cache response end
ruby
def perform_request url, verb = :get, body = nil, options = {} options_id = options.inspect can_cache = [:post, :put].include?(verb) ? false : cached? if can_cache && result = store.get("#{clean_url(url)}#{options_id}") return JSON.parse(result) end response = perform_rate_limited_request(url, verb, body, options) store.setex "#{clean_url(url)}#{options_id}", ttl, response.to_json if can_cache response end
[ "def", "perform_request", "url", ",", "verb", "=", ":get", ",", "body", "=", "nil", ",", "options", "=", "{", "}", "options_id", "=", "options", ".", "inspect", "can_cache", "=", "[", ":post", ",", ":put", "]", ".", "include?", "(", "verb", ")", "?", "false", ":", "cached?", "if", "can_cache", "&&", "result", "=", "store", ".", "get", "(", "\"#{clean_url(url)}#{options_id}\"", ")", "return", "JSON", ".", "parse", "(", "result", ")", "end", "response", "=", "perform_rate_limited_request", "(", "url", ",", "verb", ",", "body", ",", "options", ")", "store", ".", "setex", "\"#{clean_url(url)}#{options_id}\"", ",", "ttl", ",", "response", ".", "to_json", "if", "can_cache", "response", "end" ]
Calls the API via HTTParty and handles errors caching it if a cache is enabled and rate limiting it if a rate limiter is configured @param url [String] the url to call @param verb [Symbol] HTTP verb to use. Defaults to :get @param body [Hash] Body for POST request @param options [Hash] Options passed to HTTParty @return [String] raw response of the call
[ "Calls", "the", "API", "via", "HTTParty", "and", "handles", "errors", "caching", "it", "if", "a", "cache", "is", "enabled", "and", "rate", "limiting", "it", "if", "a", "rate", "limiter", "is", "configured" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/request.rb#L118-L127
train
pazdera/scriptster
lib/scriptster/shellcmd.rb
Scriptster.ShellCmd.run
def run Open3.popen3(@cmd) do |stdin, stdout, stderr, wait_thr| stdin.close # leaving stdin open when we don't use it can cause some commands to hang stdout_buffer="" stderr_buffer="" streams = [stdout, stderr] while streams.length > 0 IO.select(streams).flatten.compact.each do |io| if io.eof? streams.delete io next end stdout_buffer += io.readpartial(1) if io.fileno == stdout.fileno stderr_buffer += io.readpartial(1) if io.fileno == stderr.fileno end # Remove and process all the finished lines from the output buffer stdout_buffer.sub!(/.*\n/m) do @out += $& if @show_out $&.strip.split("\n").each do |line| line = @tag.style("cmd") + " " + line if @tag log(@out_level, line) end end '' end # Remove and process all the finished lines from the error buffer stderr_buffer.sub!(/.*\n/m) do @err += $& if @show_err $&.strip.split("\n").each do |line| line = @tag.style("cmd") + " " + line if @tag log(:err, line) end end '' end end @status = wait_thr.value end if (@expect.is_a?(Array) && [email protected]?(@status.exitstatus)) || (@expect.is_a?(Integer) && @status.exitstatus != @expect) unless @show_err err_lines = @err.split "\n" err_lines.each do |l| l = @tag.style("cmd") + " " + l if @tag log(:err, l.chomp) end end raise "'#{@cmd}' failed!" if @raise end end
ruby
def run Open3.popen3(@cmd) do |stdin, stdout, stderr, wait_thr| stdin.close # leaving stdin open when we don't use it can cause some commands to hang stdout_buffer="" stderr_buffer="" streams = [stdout, stderr] while streams.length > 0 IO.select(streams).flatten.compact.each do |io| if io.eof? streams.delete io next end stdout_buffer += io.readpartial(1) if io.fileno == stdout.fileno stderr_buffer += io.readpartial(1) if io.fileno == stderr.fileno end # Remove and process all the finished lines from the output buffer stdout_buffer.sub!(/.*\n/m) do @out += $& if @show_out $&.strip.split("\n").each do |line| line = @tag.style("cmd") + " " + line if @tag log(@out_level, line) end end '' end # Remove and process all the finished lines from the error buffer stderr_buffer.sub!(/.*\n/m) do @err += $& if @show_err $&.strip.split("\n").each do |line| line = @tag.style("cmd") + " " + line if @tag log(:err, line) end end '' end end @status = wait_thr.value end if (@expect.is_a?(Array) && [email protected]?(@status.exitstatus)) || (@expect.is_a?(Integer) && @status.exitstatus != @expect) unless @show_err err_lines = @err.split "\n" err_lines.each do |l| l = @tag.style("cmd") + " " + l if @tag log(:err, l.chomp) end end raise "'#{@cmd}' failed!" if @raise end end
[ "def", "run", "Open3", ".", "popen3", "(", "@cmd", ")", "do", "|", "stdin", ",", "stdout", ",", "stderr", ",", "wait_thr", "|", "stdin", ".", "close", "stdout_buffer", "=", "\"\"", "stderr_buffer", "=", "\"\"", "streams", "=", "[", "stdout", ",", "stderr", "]", "while", "streams", ".", "length", ">", "0", "IO", ".", "select", "(", "streams", ")", ".", "flatten", ".", "compact", ".", "each", "do", "|", "io", "|", "if", "io", ".", "eof?", "streams", ".", "delete", "io", "next", "end", "stdout_buffer", "+=", "io", ".", "readpartial", "(", "1", ")", "if", "io", ".", "fileno", "==", "stdout", ".", "fileno", "stderr_buffer", "+=", "io", ".", "readpartial", "(", "1", ")", "if", "io", ".", "fileno", "==", "stderr", ".", "fileno", "end", "stdout_buffer", ".", "sub!", "(", "/", "\\n", "/m", ")", "do", "@out", "+=", "$&", "if", "@show_out", "$&", ".", "strip", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "line", "=", "@tag", ".", "style", "(", "\"cmd\"", ")", "+", "\" \"", "+", "line", "if", "@tag", "log", "(", "@out_level", ",", "line", ")", "end", "end", "''", "end", "stderr_buffer", ".", "sub!", "(", "/", "\\n", "/m", ")", "do", "@err", "+=", "$&", "if", "@show_err", "$&", ".", "strip", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "line", "=", "@tag", ".", "style", "(", "\"cmd\"", ")", "+", "\" \"", "+", "line", "if", "@tag", "log", "(", ":err", ",", "line", ")", "end", "end", "''", "end", "end", "@status", "=", "wait_thr", ".", "value", "end", "if", "(", "@expect", ".", "is_a?", "(", "Array", ")", "&&", "!", "@expect", ".", "include?", "(", "@status", ".", "exitstatus", ")", ")", "||", "(", "@expect", ".", "is_a?", "(", "Integer", ")", "&&", "@status", ".", "exitstatus", "!=", "@expect", ")", "unless", "@show_err", "err_lines", "=", "@err", ".", "split", "\"\\n\"", "err_lines", ".", "each", "do", "|", "l", "|", "l", "=", "@tag", ".", "style", "(", "\"cmd\"", ")", "+", "\" \"", "+", "l", "if", "@tag", "log", "(", ":err", ",", "l", ".", "chomp", ")", "end", "end", "raise", "\"'#{@cmd}' failed!\"", "if", "@raise", "end", "end" ]
Execute the command and collect all the data from it. The function will block until the command has finished.
[ "Execute", "the", "command", "and", "collect", "all", "the", "data", "from", "it", "." ]
8d4fcdaf06e867f1f460e980a9defdf36d0ac29d
https://github.com/pazdera/scriptster/blob/8d4fcdaf06e867f1f460e980a9defdf36d0ac29d/lib/scriptster/shellcmd.rb#L81-L140
train
mikamai/ruby-lol
lib/lol/masteries_request.rb
Lol.MasteriesRequest.by_summoner_id
def by_summoner_id summoner_id result = perform_request api_url "masteries/by-summoner/#{summoner_id}" result["pages"].map { |p| DynamicModel.new p } end
ruby
def by_summoner_id summoner_id result = perform_request api_url "masteries/by-summoner/#{summoner_id}" result["pages"].map { |p| DynamicModel.new p } end
[ "def", "by_summoner_id", "summoner_id", "result", "=", "perform_request", "api_url", "\"masteries/by-summoner/#{summoner_id}\"", "result", "[", "\"pages\"", "]", ".", "map", "{", "|", "p", "|", "DynamicModel", ".", "new", "p", "}", "end" ]
Get mastery pages for a given summoner ID @param [Integer] summoner_id Summoner ID @return [Array<DynamicModel>] Mastery pages
[ "Get", "mastery", "pages", "for", "a", "given", "summoner", "ID" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/masteries_request.rb#L9-L12
train
contactually/zuora-ruby
lib/utils/schema_model.rb
SchemaModel.ClassMethods.define_writer!
def define_writer!(k, definition) define_method("#{k}=") do |value| # Recursively convert hash and array of hash to schematized objects value = ensure_schema value, definition[:schema] # Initial value instance_variable_set "@#{k}", value # Dirty tracking self.changed_attributes ||= Set.new self.changed_attributes << k end end
ruby
def define_writer!(k, definition) define_method("#{k}=") do |value| # Recursively convert hash and array of hash to schematized objects value = ensure_schema value, definition[:schema] # Initial value instance_variable_set "@#{k}", value # Dirty tracking self.changed_attributes ||= Set.new self.changed_attributes << k end end
[ "def", "define_writer!", "(", "k", ",", "definition", ")", "define_method", "(", "\"#{k}=\"", ")", "do", "|", "value", "|", "value", "=", "ensure_schema", "value", ",", "definition", "[", ":schema", "]", "instance_variable_set", "\"@#{k}\"", ",", "value", "self", ".", "changed_attributes", "||=", "Set", ".", "new", "self", ".", "changed_attributes", "<<", "k", "end", "end" ]
Helper for dynamically defining writer method @param [Symbol] k - name of attribute @param [Hash] definition - See docstring for schema above
[ "Helper", "for", "dynamically", "defining", "writer", "method" ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/utils/schema_model.rb#L48-L60
train
contactually/zuora-ruby
lib/utils/schema_model.rb
SchemaModel.InstanceMethods.check_children
def check_children(child_schema, value) return unless child_schema && value.present? if value.is_a? Array value.map(&:errors).reject(&:empty?) else value.errors end end
ruby
def check_children(child_schema, value) return unless child_schema && value.present? if value.is_a? Array value.map(&:errors).reject(&:empty?) else value.errors end end
[ "def", "check_children", "(", "child_schema", ",", "value", ")", "return", "unless", "child_schema", "&&", "value", ".", "present?", "if", "value", ".", "is_a?", "Array", "value", ".", "map", "(", "&", ":errors", ")", ".", "reject", "(", "&", ":empty?", ")", "else", "value", ".", "errors", "end", "end" ]
Given a schema and a value which may be a single record or collection, collect and return any errors. @param [SchemaModel] child_schema - A schema object class @param [Object] value - Array of models or single model @return [Object] Array of errors hashes, or one hash. Structure matches 'value' input
[ "Given", "a", "schema", "and", "a", "value", "which", "may", "be", "a", "single", "record", "or", "collection", "collect", "and", "return", "any", "errors", "." ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/utils/schema_model.rb#L110-L118
train
contactually/zuora-ruby
lib/utils/schema_model.rb
SchemaModel.InstanceMethods.check_validation
def check_validation(valid, value) return unless valid && value passes_validation = begin valid.call(value) rescue StandardError false end passes_validation ? nil : 'is invalid' end
ruby
def check_validation(valid, value) return unless valid && value passes_validation = begin valid.call(value) rescue StandardError false end passes_validation ? nil : 'is invalid' end
[ "def", "check_validation", "(", "valid", ",", "value", ")", "return", "unless", "valid", "&&", "value", "passes_validation", "=", "begin", "valid", ".", "call", "(", "value", ")", "rescue", "StandardError", "false", "end", "passes_validation", "?", "nil", ":", "'is invalid'", "end" ]
Checks that required field meets validation @param [Boolean or Callable] valid - callable validation fn or boolean function will be called with value @param [Object] value - value to check @return [Maybe String] error message
[ "Checks", "that", "required", "field", "meets", "validation" ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/utils/schema_model.rb#L135-L144
train
contactually/zuora-ruby
lib/utils/schema_model.rb
SchemaModel.InstanceMethods.append!
def append!(errors, attr, key, val) return unless val.present? errors ||= {} errors[attr] ||= {} errors[attr][key] = val end
ruby
def append!(errors, attr, key, val) return unless val.present? errors ||= {} errors[attr] ||= {} errors[attr][key] = val end
[ "def", "append!", "(", "errors", ",", "attr", ",", "key", ",", "val", ")", "return", "unless", "val", ".", "present?", "errors", "||=", "{", "}", "errors", "[", "attr", "]", "||=", "{", "}", "errors", "[", "attr", "]", "[", "key", "]", "=", "val", "end" ]
Mutates errors, adding in error messages scoped to the attribute and key @param [Maybe Hash] errors - @param [Symbol] attr - name of attribute under check @param [Symbol] key - name of validation step @param [Object] val - data to append
[ "Mutates", "errors", "adding", "in", "error", "messages", "scoped", "to", "the", "attribute", "and", "key" ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/utils/schema_model.rb#L151-L157
train
delighted/delighted-ruby
lib/delighted/resource.rb
Delighted.Resource.to_hash
def to_hash serialized_attributes = attributes.dup self.class.expandable_attributes.each_pair.select do |attribute_name, expanded_class| if expanded_class === attributes[attribute_name] serialized_attributes[attribute_name] = serialized_attributes[attribute_name].id end end serialized_attributes end
ruby
def to_hash serialized_attributes = attributes.dup self.class.expandable_attributes.each_pair.select do |attribute_name, expanded_class| if expanded_class === attributes[attribute_name] serialized_attributes[attribute_name] = serialized_attributes[attribute_name].id end end serialized_attributes end
[ "def", "to_hash", "serialized_attributes", "=", "attributes", ".", "dup", "self", ".", "class", ".", "expandable_attributes", ".", "each_pair", ".", "select", "do", "|", "attribute_name", ",", "expanded_class", "|", "if", "expanded_class", "===", "attributes", "[", "attribute_name", "]", "serialized_attributes", "[", "attribute_name", "]", "=", "serialized_attributes", "[", "attribute_name", "]", ".", "id", "end", "end", "serialized_attributes", "end" ]
Attributes used for serialization
[ "Attributes", "used", "for", "serialization" ]
843fe0c1453d651fd609b4a10d05b121fd37fe98
https://github.com/delighted/delighted-ruby/blob/843fe0c1453d651fd609b4a10d05b121fd37fe98/lib/delighted/resource.rb#L41-L51
train
HashNuke/mailgun
lib/mailgun/webhook.rb
Mailgun.Webhook.update
def update(id, url=default_webhook_url) params = {:url => url} Mailgun.submit :put, webhook_url(id), params end
ruby
def update(id, url=default_webhook_url) params = {:url => url} Mailgun.submit :put, webhook_url(id), params end
[ "def", "update", "(", "id", ",", "url", "=", "default_webhook_url", ")", "params", "=", "{", ":url", "=>", "url", "}", "Mailgun", ".", "submit", ":put", ",", "webhook_url", "(", "id", ")", ",", "params", "end" ]
Updates an existing webhook
[ "Updates", "an", "existing", "webhook" ]
5476618ae1208cd0e563b6f84d26e2cfc68417ba
https://github.com/HashNuke/mailgun/blob/5476618ae1208cd0e563b6f84d26e2cfc68417ba/lib/mailgun/webhook.rb#L37-L40
train
HashNuke/mailgun
lib/mailgun/list.rb
Mailgun.MailingList.update
def update(address, new_address, options={}) params = {:address => new_address} Mailgun.submit :put, list_url(address), params.merge(options) end
ruby
def update(address, new_address, options={}) params = {:address => new_address} Mailgun.submit :put, list_url(address), params.merge(options) end
[ "def", "update", "(", "address", ",", "new_address", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":address", "=>", "new_address", "}", "Mailgun", ".", "submit", ":put", ",", "list_url", "(", "address", ")", ",", "params", ".", "merge", "(", "options", ")", "end" ]
Update a mailing list with a given address with an optional new address, name or description
[ "Update", "a", "mailing", "list", "with", "a", "given", "address", "with", "an", "optional", "new", "address", "name", "or", "description" ]
5476618ae1208cd0e563b6f84d26e2cfc68417ba
https://github.com/HashNuke/mailgun/blob/5476618ae1208cd0e563b6f84d26e2cfc68417ba/lib/mailgun/list.rb#L30-L33
train
pluginaweek/encrypted_strings
lib/encrypted_strings/asymmetric_cipher.rb
EncryptedStrings.AsymmetricCipher.encrypt
def encrypt(data) raise NoPublicKeyError, "Public key file: #{public_key_file}" unless public? encrypted_data = public_rsa.public_encrypt(data) [encrypted_data].pack('m') end
ruby
def encrypt(data) raise NoPublicKeyError, "Public key file: #{public_key_file}" unless public? encrypted_data = public_rsa.public_encrypt(data) [encrypted_data].pack('m') end
[ "def", "encrypt", "(", "data", ")", "raise", "NoPublicKeyError", ",", "\"Public key file: #{public_key_file}\"", "unless", "public?", "encrypted_data", "=", "public_rsa", ".", "public_encrypt", "(", "data", ")", "[", "encrypted_data", "]", ".", "pack", "(", "'m'", ")", "end" ]
Creates a new cipher that uses an asymmetric encryption strategy. Configuration options: * <tt>:private_key_file</tt> - Encrypted private key file * <tt>:public_key_file</tt> - Public key file * <tt>:password</tt> - The password to use in the symmetric cipher * <tt>:algorithm</tt> - Algorithm to use symmetrically encrypted strings Encrypts the given data. If no public key file has been specified, then a NoPublicKeyError will be raised.
[ "Creates", "a", "new", "cipher", "that", "uses", "an", "asymmetric", "encryption", "strategy", "." ]
a9bea6b48b910e24e762662d8816709100906756
https://github.com/pluginaweek/encrypted_strings/blob/a9bea6b48b910e24e762662d8816709100906756/lib/encrypted_strings/asymmetric_cipher.rb#L106-L111
train
pluginaweek/encrypted_strings
lib/encrypted_strings/asymmetric_cipher.rb
EncryptedStrings.AsymmetricCipher.decrypt
def decrypt(data) raise NoPrivateKeyError, "Private key file: #{private_key_file}" unless private? decrypted_data = data.unpack('m')[0] private_rsa.private_decrypt(decrypted_data) end
ruby
def decrypt(data) raise NoPrivateKeyError, "Private key file: #{private_key_file}" unless private? decrypted_data = data.unpack('m')[0] private_rsa.private_decrypt(decrypted_data) end
[ "def", "decrypt", "(", "data", ")", "raise", "NoPrivateKeyError", ",", "\"Private key file: #{private_key_file}\"", "unless", "private?", "decrypted_data", "=", "data", ".", "unpack", "(", "'m'", ")", "[", "0", "]", "private_rsa", ".", "private_decrypt", "(", "decrypted_data", ")", "end" ]
Decrypts the given data. If no private key file has been specified, then a NoPrivateKeyError will be raised.
[ "Decrypts", "the", "given", "data", ".", "If", "no", "private", "key", "file", "has", "been", "specified", "then", "a", "NoPrivateKeyError", "will", "be", "raised", "." ]
a9bea6b48b910e24e762662d8816709100906756
https://github.com/pluginaweek/encrypted_strings/blob/a9bea6b48b910e24e762662d8816709100906756/lib/encrypted_strings/asymmetric_cipher.rb#L115-L120
train
pluginaweek/encrypted_strings
lib/encrypted_strings/asymmetric_cipher.rb
EncryptedStrings.AsymmetricCipher.private_rsa
def private_rsa if password options = {:password => password} options[:algorithm] = algorithm if algorithm private_key = @private_key.decrypt(:symmetric, options) OpenSSL::PKey::RSA.new(private_key) else @private_rsa ||= OpenSSL::PKey::RSA.new(@private_key) end end
ruby
def private_rsa if password options = {:password => password} options[:algorithm] = algorithm if algorithm private_key = @private_key.decrypt(:symmetric, options) OpenSSL::PKey::RSA.new(private_key) else @private_rsa ||= OpenSSL::PKey::RSA.new(@private_key) end end
[ "def", "private_rsa", "if", "password", "options", "=", "{", ":password", "=>", "password", "}", "options", "[", ":algorithm", "]", "=", "algorithm", "if", "algorithm", "private_key", "=", "@private_key", ".", "decrypt", "(", ":symmetric", ",", "options", ")", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "private_key", ")", "else", "@private_rsa", "||=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "@private_key", ")", "end", "end" ]
Retrieves the private RSA from the private key
[ "Retrieves", "the", "private", "RSA", "from", "the", "private", "key" ]
a9bea6b48b910e24e762662d8816709100906756
https://github.com/pluginaweek/encrypted_strings/blob/a9bea6b48b910e24e762662d8816709100906756/lib/encrypted_strings/asymmetric_cipher.rb#L168-L178
train
pluginaweek/encrypted_strings
lib/encrypted_strings/sha_cipher.rb
EncryptedStrings.ShaCipher.encrypt
def encrypt(data) Digest::const_get(algorithm.upcase).hexdigest(build(data, salt)) end
ruby
def encrypt(data) Digest::const_get(algorithm.upcase).hexdigest(build(data, salt)) end
[ "def", "encrypt", "(", "data", ")", "Digest", "::", "const_get", "(", "algorithm", ".", "upcase", ")", ".", "hexdigest", "(", "build", "(", "data", ",", "salt", ")", ")", "end" ]
Returns the encrypted value of the data
[ "Returns", "the", "encrypted", "value", "of", "the", "data" ]
a9bea6b48b910e24e762662d8816709100906756
https://github.com/pluginaweek/encrypted_strings/blob/a9bea6b48b910e24e762662d8816709100906756/lib/encrypted_strings/sha_cipher.rb#L110-L112
train
pluginaweek/encrypted_strings
lib/encrypted_strings/sha_cipher.rb
EncryptedStrings.ShaCipher.build
def build(data, salt) if builder.is_a?(Proc) builder.call(data, salt) else builder.send(:build, data, salt) end end
ruby
def build(data, salt) if builder.is_a?(Proc) builder.call(data, salt) else builder.send(:build, data, salt) end end
[ "def", "build", "(", "data", ",", "salt", ")", "if", "builder", ".", "is_a?", "(", "Proc", ")", "builder", ".", "call", "(", "data", ",", "salt", ")", "else", "builder", ".", "send", "(", ":build", ",", "data", ",", "salt", ")", "end", "end" ]
Builds the value to hash based on the data being encrypted and the salt being used to seed the encryption algorithm
[ "Builds", "the", "value", "to", "hash", "based", "on", "the", "data", "being", "encrypted", "and", "the", "salt", "being", "used", "to", "seed", "the", "encryption", "algorithm" ]
a9bea6b48b910e24e762662d8816709100906756
https://github.com/pluginaweek/encrypted_strings/blob/a9bea6b48b910e24e762662d8816709100906756/lib/encrypted_strings/sha_cipher.rb#L132-L138
train
HashNuke/mailgun
lib/mailgun/secure.rb
Mailgun.Secure.check_request_auth
def check_request_auth(timestamp, token, signature, offset=-5) if offset != 0 offset = Time.now.to_i + offset * 60 return false if timestamp < offset end return signature == OpenSSL::HMAC.hexdigest( OpenSSL::Digest::Digest.new('sha256'), Mailgun.api_key, '%s%s' % [timestamp, token]) end
ruby
def check_request_auth(timestamp, token, signature, offset=-5) if offset != 0 offset = Time.now.to_i + offset * 60 return false if timestamp < offset end return signature == OpenSSL::HMAC.hexdigest( OpenSSL::Digest::Digest.new('sha256'), Mailgun.api_key, '%s%s' % [timestamp, token]) end
[ "def", "check_request_auth", "(", "timestamp", ",", "token", ",", "signature", ",", "offset", "=", "-", "5", ")", "if", "offset", "!=", "0", "offset", "=", "Time", ".", "now", ".", "to_i", "+", "offset", "*", "60", "return", "false", "if", "timestamp", "<", "offset", "end", "return", "signature", "==", "OpenSSL", "::", "HMAC", ".", "hexdigest", "(", "OpenSSL", "::", "Digest", "::", "Digest", ".", "new", "(", "'sha256'", ")", ",", "Mailgun", ".", "api_key", ",", "'%s%s'", "%", "[", "timestamp", ",", "token", "]", ")", "end" ]
check request auth
[ "check", "request", "auth" ]
5476618ae1208cd0e563b6f84d26e2cfc68417ba
https://github.com/HashNuke/mailgun/blob/5476618ae1208cd0e563b6f84d26e2cfc68417ba/lib/mailgun/secure.rb#L18-L28
train
bbc/res
lib/res/ir.rb
Res.IR.json
def json hash = { :started => @started, :finished => @finished, :results => @results, :type => @type } # Merge in the world information if it's available hash[:world] = world if world hash[:hive_job_id] = hive_job_id if hive_job_id JSON.pretty_generate( hash ) end
ruby
def json hash = { :started => @started, :finished => @finished, :results => @results, :type => @type } # Merge in the world information if it's available hash[:world] = world if world hash[:hive_job_id] = hive_job_id if hive_job_id JSON.pretty_generate( hash ) end
[ "def", "json", "hash", "=", "{", ":started", "=>", "@started", ",", ":finished", "=>", "@finished", ",", ":results", "=>", "@results", ",", ":type", "=>", "@type", "}", "hash", "[", ":world", "]", "=", "world", "if", "world", "hash", "[", ":hive_job_id", "]", "=", "hive_job_id", "if", "hive_job_id", "JSON", ".", "pretty_generate", "(", "hash", ")", "end" ]
Dump as json
[ "Dump", "as", "json" ]
2a7e86191acf1da957a08ead7a7367c19f20bc21
https://github.com/bbc/res/blob/2a7e86191acf1da957a08ead7a7367c19f20bc21/lib/res/ir.rb#L47-L59
train
pluginaweek/encrypted_strings
lib/encrypted_strings/symmetric_cipher.rb
EncryptedStrings.SymmetricCipher.decrypt
def decrypt(data) cipher = build_cipher(:decrypt) cipher.update(data.unpack('m')[0]) + cipher.final end
ruby
def decrypt(data) cipher = build_cipher(:decrypt) cipher.update(data.unpack('m')[0]) + cipher.final end
[ "def", "decrypt", "(", "data", ")", "cipher", "=", "build_cipher", "(", ":decrypt", ")", "cipher", ".", "update", "(", "data", ".", "unpack", "(", "'m'", ")", "[", "0", "]", ")", "+", "cipher", ".", "final", "end" ]
Creates a new cipher that uses a symmetric encryption strategy. Configuration options: * <tt>:algorithm</tt> - The algorithm to use for generating the encrypted string * <tt>:password</tt> - The secret value to use for generating the key/initialization vector for the algorithm Decrypts the current string using the current key and algorithm specified
[ "Creates", "a", "new", "cipher", "that", "uses", "a", "symmetric", "encryption", "strategy", "." ]
a9bea6b48b910e24e762662d8816709100906756
https://github.com/pluginaweek/encrypted_strings/blob/a9bea6b48b910e24e762662d8816709100906756/lib/encrypted_strings/symmetric_cipher.rb#L83-L86
train
pluginaweek/encrypted_strings
lib/encrypted_strings/symmetric_cipher.rb
EncryptedStrings.SymmetricCipher.encrypt
def encrypt(data) cipher = build_cipher(:encrypt) [cipher.update(data) + cipher.final].pack('m') end
ruby
def encrypt(data) cipher = build_cipher(:encrypt) [cipher.update(data) + cipher.final].pack('m') end
[ "def", "encrypt", "(", "data", ")", "cipher", "=", "build_cipher", "(", ":encrypt", ")", "[", "cipher", ".", "update", "(", "data", ")", "+", "cipher", ".", "final", "]", ".", "pack", "(", "'m'", ")", "end" ]
Encrypts the current string using the current key and algorithm specified
[ "Encrypts", "the", "current", "string", "using", "the", "current", "key", "and", "algorithm", "specified" ]
a9bea6b48b910e24e762662d8816709100906756
https://github.com/pluginaweek/encrypted_strings/blob/a9bea6b48b910e24e762662d8816709100906756/lib/encrypted_strings/symmetric_cipher.rb#L89-L92
train
HashNuke/mailgun
lib/mailgun/domain.rb
Mailgun.Domain.create
def create(domain, opts = {}) opts = {name: domain}.merge(opts) Mailgun.submit :post, domain_url, opts end
ruby
def create(domain, opts = {}) opts = {name: domain}.merge(opts) Mailgun.submit :post, domain_url, opts end
[ "def", "create", "(", "domain", ",", "opts", "=", "{", "}", ")", "opts", "=", "{", "name", ":", "domain", "}", ".", "merge", "(", "opts", ")", "Mailgun", ".", "submit", ":post", ",", "domain_url", ",", "opts", "end" ]
Add domain to account
[ "Add", "domain", "to", "account" ]
5476618ae1208cd0e563b6f84d26e2cfc68417ba
https://github.com/HashNuke/mailgun/blob/5476618ae1208cd0e563b6f84d26e2cfc68417ba/lib/mailgun/domain.rb#L21-L24
train
junegunn/perlin_noise
lib/perlin/gradient_table.rb
Perlin.GradientTable.index
def index(*coords) s = coords.last coords.reverse[1..-1].each do |c| s = perm(s) + c end perm(s) end
ruby
def index(*coords) s = coords.last coords.reverse[1..-1].each do |c| s = perm(s) + c end perm(s) end
[ "def", "index", "(", "*", "coords", ")", "s", "=", "coords", ".", "last", "coords", ".", "reverse", "[", "1", "..", "-", "1", "]", ".", "each", "do", "|", "c", "|", "s", "=", "perm", "(", "s", ")", "+", "c", "end", "perm", "(", "s", ")", "end" ]
A simple hashing
[ "A", "simple", "hashing" ]
ac402f5c4a4f54f9b26c8a8166f06ba7f06454d3
https://github.com/junegunn/perlin_noise/blob/ac402f5c4a4f54f9b26c8a8166f06ba7f06454d3/lib/perlin/gradient_table.rb#L38-L44
train
HashNuke/mailgun
lib/mailgun/list/member.rb
Mailgun.MailingList::Member.add
def add(member_address, options={}) params = {:address => member_address} Mailgun.submit :post, list_member_url, params.merge(options) end
ruby
def add(member_address, options={}) params = {:address => member_address} Mailgun.submit :post, list_member_url, params.merge(options) end
[ "def", "add", "(", "member_address", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":address", "=>", "member_address", "}", "Mailgun", ".", "submit", ":post", ",", "list_member_url", ",", "params", ".", "merge", "(", "options", ")", "end" ]
Adds a mailing list member with a given address NOTE Use create instead of add?
[ "Adds", "a", "mailing", "list", "member", "with", "a", "given", "address", "NOTE", "Use", "create", "instead", "of", "add?" ]
5476618ae1208cd0e563b6f84d26e2cfc68417ba
https://github.com/HashNuke/mailgun/blob/5476618ae1208cd0e563b6f84d26e2cfc68417ba/lib/mailgun/list/member.rb#L25-L28
train
HashNuke/mailgun
lib/mailgun/list/member.rb
Mailgun.MailingList::Member.update
def update(member_address, options={}) params = {:address => member_address} Mailgun.submit :put, list_member_url(member_address), params.merge(options) end
ruby
def update(member_address, options={}) params = {:address => member_address} Mailgun.submit :put, list_member_url(member_address), params.merge(options) end
[ "def", "update", "(", "member_address", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":address", "=>", "member_address", "}", "Mailgun", ".", "submit", ":put", ",", "list_member_url", "(", "member_address", ")", ",", "params", ".", "merge", "(", "options", ")", "end" ]
Update a mailing list member with a given address
[ "Update", "a", "mailing", "list", "member", "with", "a", "given", "address" ]
5476618ae1208cd0e563b6f84d26e2cfc68417ba
https://github.com/HashNuke/mailgun/blob/5476618ae1208cd0e563b6f84d26e2cfc68417ba/lib/mailgun/list/member.rb#L39-L42
train
sdalu/ruby-ble
lib/ble/device.rb
BLE.Device.cancel_pairing
def cancel_pairing block_given? ? @o_dev[I_DEVICE].CancelPairing(&Proc.new) : @o_dev[I_DEVICE].CancelPairing() true rescue DBus::Error => e case e.name when E_DOES_NOT_EXIST then true when E_FAILED then false else raise ScriptError end end
ruby
def cancel_pairing block_given? ? @o_dev[I_DEVICE].CancelPairing(&Proc.new) : @o_dev[I_DEVICE].CancelPairing() true rescue DBus::Error => e case e.name when E_DOES_NOT_EXIST then true when E_FAILED then false else raise ScriptError end end
[ "def", "cancel_pairing", "block_given?", "?", "@o_dev", "[", "I_DEVICE", "]", ".", "CancelPairing", "(", "&", "Proc", ".", "new", ")", ":", "@o_dev", "[", "I_DEVICE", "]", ".", "CancelPairing", "(", ")", "true", "rescue", "DBus", "::", "Error", "=>", "e", "case", "e", ".", "name", "when", "E_DOES_NOT_EXIST", "then", "true", "when", "E_FAILED", "then", "false", "else", "raise", "ScriptError", "end", "end" ]
This method can be used to cancel a pairing operation initiated by the Pair method. @return [Boolean]
[ "This", "method", "can", "be", "used", "to", "cancel", "a", "pairing", "operation", "initiated", "by", "the", "Pair", "method", "." ]
4c3b32d0ee65f787be235f1a5ee3878e6dcd995a
https://github.com/sdalu/ruby-ble/blob/4c3b32d0ee65f787be235f1a5ee3878e6dcd995a/lib/ble/device.rb#L101-L111
train
sdalu/ruby-ble
lib/ble/device.rb
BLE.Device.is_paired?
def is_paired? @o_dev[I_DEVICE]['Paired'] rescue DBus::Error => e case e.name when E_UNKNOWN_OBJECT raise StalledObject else raise ScriptError end end
ruby
def is_paired? @o_dev[I_DEVICE]['Paired'] rescue DBus::Error => e case e.name when E_UNKNOWN_OBJECT raise StalledObject else raise ScriptError end end
[ "def", "is_paired?", "@o_dev", "[", "I_DEVICE", "]", "[", "'Paired'", "]", "rescue", "DBus", "::", "Error", "=>", "e", "case", "e", ".", "name", "when", "E_UNKNOWN_OBJECT", "raise", "StalledObject", "else", "raise", "ScriptError", "end", "end" ]
Indicates if the remote device is paired
[ "Indicates", "if", "the", "remote", "device", "is", "paired" ]
4c3b32d0ee65f787be235f1a5ee3878e6dcd995a
https://github.com/sdalu/ruby-ble/blob/4c3b32d0ee65f787be235f1a5ee3878e6dcd995a/lib/ble/device.rb#L185-L193
train
sdalu/ruby-ble
lib/ble/device.rb
BLE.Device.trusted=
def trusted=(val) if ! [ true, false ].include?(val) raise ArgumentError, "value must be a boolean" end @o_dev[I_DEVICE]['Trusted'] = val end
ruby
def trusted=(val) if ! [ true, false ].include?(val) raise ArgumentError, "value must be a boolean" end @o_dev[I_DEVICE]['Trusted'] = val end
[ "def", "trusted", "=", "(", "val", ")", "if", "!", "[", "true", ",", "false", "]", ".", "include?", "(", "val", ")", "raise", "ArgumentError", ",", "\"value must be a boolean\"", "end", "@o_dev", "[", "I_DEVICE", "]", "[", "'Trusted'", "]", "=", "val", "end" ]
Indicates if the remote is seen as trusted. This setting can be changed by the application. @param val [Boolean] @return [void]
[ "Indicates", "if", "the", "remote", "is", "seen", "as", "trusted", ".", "This", "setting", "can", "be", "changed", "by", "the", "application", "." ]
4c3b32d0ee65f787be235f1a5ee3878e6dcd995a
https://github.com/sdalu/ruby-ble/blob/4c3b32d0ee65f787be235f1a5ee3878e6dcd995a/lib/ble/device.rb#L291-L296
train
sdalu/ruby-ble
lib/ble/device.rb
BLE.Device.blocked=
def blocked=(val) if ! [ true, false ].include?(val) raise ArgumentError, "value must be a boolean" end @o_dev[I_DEVICE]['Blocked'] = val end
ruby
def blocked=(val) if ! [ true, false ].include?(val) raise ArgumentError, "value must be a boolean" end @o_dev[I_DEVICE]['Blocked'] = val end
[ "def", "blocked", "=", "(", "val", ")", "if", "!", "[", "true", ",", "false", "]", ".", "include?", "(", "val", ")", "raise", "ArgumentError", ",", "\"value must be a boolean\"", "end", "@o_dev", "[", "I_DEVICE", "]", "[", "'Blocked'", "]", "=", "val", "end" ]
If set to true any incoming connections from the device will be immediately rejected. Any device drivers will also be removed and no new ones will be probed as long as the device is blocked @param val [Boolean] @return [void]
[ "If", "set", "to", "true", "any", "incoming", "connections", "from", "the", "device", "will", "be", "immediately", "rejected", ".", "Any", "device", "drivers", "will", "also", "be", "removed", "and", "no", "new", "ones", "will", "be", "probed", "as", "long", "as", "the", "device", "is", "blocked" ]
4c3b32d0ee65f787be235f1a5ee3878e6dcd995a
https://github.com/sdalu/ruby-ble/blob/4c3b32d0ee65f787be235f1a5ee3878e6dcd995a/lib/ble/device.rb#L310-L315
train
sdalu/ruby-ble
lib/ble/device.rb
BLE.Device.refresh!
def refresh! _require_connection! max_wait ||= 1.5 # Use ||= due to the retry @services = Hash[@o_dev.subnodes.map {|p_srv| p_srv = [@o_dev.path, p_srv].join '/' o_srv = BLUEZ.object(p_srv) o_srv.introspect srv = o_srv.GetAll(I_GATT_SERVICE).first char = Hash[o_srv.subnodes.map {|char| p_char = [o_srv.path, char].join '/' o_char = BLUEZ.object(p_char) o_char.introspect uuid = o_char[I_GATT_CHARACTERISTIC]['UUID' ].downcase flags = o_char[I_GATT_CHARACTERISTIC]['Flags'] [ uuid, Characteristic.new({ :uuid => uuid, :flags => flags, :obj => o_char }) ] }] uuid = srv['UUID'].downcase [ uuid, { :uuid => uuid, :primary => srv['Primary'], :characteristics => char } ] }] self rescue DBus::Error => e case e.name when E_UNKNOWN_OBJECT raise StalledObject when E_INVALID_ARGS # That's probably because all the bluez information # haven't been collected yet on dbus for GattServices if max_wait > 0 sleep(0.25) ; max_wait -= 0.25 ; retry end raise NotReady else raise ScriptError end end
ruby
def refresh! _require_connection! max_wait ||= 1.5 # Use ||= due to the retry @services = Hash[@o_dev.subnodes.map {|p_srv| p_srv = [@o_dev.path, p_srv].join '/' o_srv = BLUEZ.object(p_srv) o_srv.introspect srv = o_srv.GetAll(I_GATT_SERVICE).first char = Hash[o_srv.subnodes.map {|char| p_char = [o_srv.path, char].join '/' o_char = BLUEZ.object(p_char) o_char.introspect uuid = o_char[I_GATT_CHARACTERISTIC]['UUID' ].downcase flags = o_char[I_GATT_CHARACTERISTIC]['Flags'] [ uuid, Characteristic.new({ :uuid => uuid, :flags => flags, :obj => o_char }) ] }] uuid = srv['UUID'].downcase [ uuid, { :uuid => uuid, :primary => srv['Primary'], :characteristics => char } ] }] self rescue DBus::Error => e case e.name when E_UNKNOWN_OBJECT raise StalledObject when E_INVALID_ARGS # That's probably because all the bluez information # haven't been collected yet on dbus for GattServices if max_wait > 0 sleep(0.25) ; max_wait -= 0.25 ; retry end raise NotReady else raise ScriptError end end
[ "def", "refresh!", "_require_connection!", "max_wait", "||=", "1.5", "@services", "=", "Hash", "[", "@o_dev", ".", "subnodes", ".", "map", "{", "|", "p_srv", "|", "p_srv", "=", "[", "@o_dev", ".", "path", ",", "p_srv", "]", ".", "join", "'/'", "o_srv", "=", "BLUEZ", ".", "object", "(", "p_srv", ")", "o_srv", ".", "introspect", "srv", "=", "o_srv", ".", "GetAll", "(", "I_GATT_SERVICE", ")", ".", "first", "char", "=", "Hash", "[", "o_srv", ".", "subnodes", ".", "map", "{", "|", "char", "|", "p_char", "=", "[", "o_srv", ".", "path", ",", "char", "]", ".", "join", "'/'", "o_char", "=", "BLUEZ", ".", "object", "(", "p_char", ")", "o_char", ".", "introspect", "uuid", "=", "o_char", "[", "I_GATT_CHARACTERISTIC", "]", "[", "'UUID'", "]", ".", "downcase", "flags", "=", "o_char", "[", "I_GATT_CHARACTERISTIC", "]", "[", "'Flags'", "]", "[", "uuid", ",", "Characteristic", ".", "new", "(", "{", ":uuid", "=>", "uuid", ",", ":flags", "=>", "flags", ",", ":obj", "=>", "o_char", "}", ")", "]", "}", "]", "uuid", "=", "srv", "[", "'UUID'", "]", ".", "downcase", "[", "uuid", ",", "{", ":uuid", "=>", "uuid", ",", ":primary", "=>", "srv", "[", "'Primary'", "]", ",", ":characteristics", "=>", "char", "}", "]", "}", "]", "self", "rescue", "DBus", "::", "Error", "=>", "e", "case", "e", ".", "name", "when", "E_UNKNOWN_OBJECT", "raise", "StalledObject", "when", "E_INVALID_ARGS", "if", "max_wait", ">", "0", "sleep", "(", "0.25", ")", ";", "max_wait", "-=", "0.25", ";", "retry", "end", "raise", "NotReady", "else", "raise", "ScriptError", "end", "end" ]
Refresh list of services and characteristics @raise [NotConnected] if device is not in a connected state @return [self]
[ "Refresh", "list", "of", "services", "and", "characteristics" ]
4c3b32d0ee65f787be235f1a5ee3878e6dcd995a
https://github.com/sdalu/ruby-ble/blob/4c3b32d0ee65f787be235f1a5ee3878e6dcd995a/lib/ble/device.rb#L353-L389
train
infinitered/bluepotion
lib/project/pro_motion/fragments/pm_screen_module.rb
PMScreenModule.ClassMethods.action_bar
def action_bar(show_action_bar, opts={}) @action_bar_options = ({show:true, back: true, icon: false}).merge(opts).merge({show: show_action_bar}) end
ruby
def action_bar(show_action_bar, opts={}) @action_bar_options = ({show:true, back: true, icon: false}).merge(opts).merge({show: show_action_bar}) end
[ "def", "action_bar", "(", "show_action_bar", ",", "opts", "=", "{", "}", ")", "@action_bar_options", "=", "(", "{", "show", ":", "true", ",", "back", ":", "true", ",", "icon", ":", "false", "}", ")", ".", "merge", "(", "opts", ")", ".", "merge", "(", "{", "show", ":", "show_action_bar", "}", ")", "end" ]
Sets up the action bar for this screen. Example: action_bar true, back: true, icon: true, custom_icon: "resourcename", custom_back: "custombackicon"
[ "Sets", "up", "the", "action", "bar", "for", "this", "screen", "." ]
293730b31e3bdeec2887bfa014bcd2d354b3e608
https://github.com/infinitered/bluepotion/blob/293730b31e3bdeec2887bfa014bcd2d354b3e608/lib/project/pro_motion/fragments/pm_screen_module.rb#L30-L32
train
zevarito/mixpanel
lib/mixpanel/tracker.rb
Mixpanel.Tracker.escape_object_for_js
def escape_object_for_js(object, i = 0) if object.kind_of? Hash # Recursive case Hash.new.tap do |h| object.each do |k, v| h[escape_object_for_js(k, i + 1)] = escape_object_for_js(v, i + 1) end end elsif object.kind_of? Enumerable # Recursive case object.map do |elt| escape_object_for_js(elt, i + 1) end elsif object.respond_to? :iso8601 # Base case - safe object object.iso8601 elsif object.kind_of?(Numeric) # Base case - safe object object elsif [true, false, nil].member?(object) # Base case - safe object object else # Base case - use string sanitizer from ActiveSupport escape_javascript(object.to_s) end end
ruby
def escape_object_for_js(object, i = 0) if object.kind_of? Hash # Recursive case Hash.new.tap do |h| object.each do |k, v| h[escape_object_for_js(k, i + 1)] = escape_object_for_js(v, i + 1) end end elsif object.kind_of? Enumerable # Recursive case object.map do |elt| escape_object_for_js(elt, i + 1) end elsif object.respond_to? :iso8601 # Base case - safe object object.iso8601 elsif object.kind_of?(Numeric) # Base case - safe object object elsif [true, false, nil].member?(object) # Base case - safe object object else # Base case - use string sanitizer from ActiveSupport escape_javascript(object.to_s) end end
[ "def", "escape_object_for_js", "(", "object", ",", "i", "=", "0", ")", "if", "object", ".", "kind_of?", "Hash", "Hash", ".", "new", ".", "tap", "do", "|", "h", "|", "object", ".", "each", "do", "|", "k", ",", "v", "|", "h", "[", "escape_object_for_js", "(", "k", ",", "i", "+", "1", ")", "]", "=", "escape_object_for_js", "(", "v", ",", "i", "+", "1", ")", "end", "end", "elsif", "object", ".", "kind_of?", "Enumerable", "object", ".", "map", "do", "|", "elt", "|", "escape_object_for_js", "(", "elt", ",", "i", "+", "1", ")", "end", "elsif", "object", ".", "respond_to?", ":iso8601", "object", ".", "iso8601", "elsif", "object", ".", "kind_of?", "(", "Numeric", ")", "object", "elsif", "[", "true", ",", "false", ",", "nil", "]", ".", "member?", "(", "object", ")", "object", "else", "escape_javascript", "(", "object", ".", "to_s", ")", "end", "end" ]
Recursively escape anything in a primitive, array, or hash, in preparation for jsonifying it
[ "Recursively", "escape", "anything", "in", "a", "primitive", "array", "or", "hash", "in", "preparation", "for", "jsonifying", "it" ]
e36b2e1d054c38cc2974e677ecd60f6f424ff33d
https://github.com/zevarito/mixpanel/blob/e36b2e1d054c38cc2974e677ecd60f6f424ff33d/lib/mixpanel/tracker.rb#L97-L130
train
nbudin/heroku_external_db
lib/heroku_external_db.rb
HerokuExternalDb.Configuration.db_configuration
def db_configuration(opts) return {} unless opts raise "ca_path for #{opts.inspect} cannot be determined from Rails root; please set it explicitly" unless ca_path config = {} [ :sslca, # Needed when using X.509 :sslcert, :sslkey, ].each do |k| if value = opts[k] filepath = File.join(ca_path, value) raise "File #{filepath.inspect} does not exist!" unless File.exists?(filepath) config[k] = filepath end end return config end
ruby
def db_configuration(opts) return {} unless opts raise "ca_path for #{opts.inspect} cannot be determined from Rails root; please set it explicitly" unless ca_path config = {} [ :sslca, # Needed when using X.509 :sslcert, :sslkey, ].each do |k| if value = opts[k] filepath = File.join(ca_path, value) raise "File #{filepath.inspect} does not exist!" unless File.exists?(filepath) config[k] = filepath end end return config end
[ "def", "db_configuration", "(", "opts", ")", "return", "{", "}", "unless", "opts", "raise", "\"ca_path for #{opts.inspect} cannot be determined from Rails root; please set it explicitly\"", "unless", "ca_path", "config", "=", "{", "}", "[", ":sslca", ",", ":sslcert", ",", ":sslkey", ",", "]", ".", "each", "do", "|", "k", "|", "if", "value", "=", "opts", "[", "k", "]", "filepath", "=", "File", ".", "join", "(", "ca_path", ",", "value", ")", "raise", "\"File #{filepath.inspect} does not exist!\"", "unless", "File", ".", "exists?", "(", "filepath", ")", "config", "[", "k", "]", "=", "filepath", "end", "end", "return", "config", "end" ]
Returns a partial ActiveRecord configuration hash for the given SSL CA certificate. Checks to make sure the given filename actually exists, and raises an error if it does not.
[ "Returns", "a", "partial", "ActiveRecord", "configuration", "hash", "for", "the", "given", "SSL", "CA", "certificate", ".", "Checks", "to", "make", "sure", "the", "given", "filename", "actually", "exists", "and", "raises", "an", "error", "if", "it", "does", "not", "." ]
1eec5b85e85e03645fa2c478cbaf8aec574ad5a5
https://github.com/nbudin/heroku_external_db/blob/1eec5b85e85e03645fa2c478cbaf8aec574ad5a5/lib/heroku_external_db.rb#L79-L100
train
nbudin/heroku_external_db
lib/heroku_external_db.rb
HerokuExternalDb.Configuration.db_config
def db_config @db_config ||= begin raise "ENV['#{env_prefix}_DATABASE_URL'] expected but not found!" unless ENV["#{env_prefix}_DATABASE_URL"] config = parse_db_uri(ENV["#{env_prefix}_DATABASE_URL"]) if ENV["#{env_prefix}_DATABASE_CA"] config.merge!(db_configuration({ :sslca => ENV["#{env_prefix}_DATABASE_CA"], :sslcert => ENV["#{env_prefix}_DATABASE_CERT"], :sslkey => ENV["#{env_prefix}_DATABASE_KEY"], })) end config end end
ruby
def db_config @db_config ||= begin raise "ENV['#{env_prefix}_DATABASE_URL'] expected but not found!" unless ENV["#{env_prefix}_DATABASE_URL"] config = parse_db_uri(ENV["#{env_prefix}_DATABASE_URL"]) if ENV["#{env_prefix}_DATABASE_CA"] config.merge!(db_configuration({ :sslca => ENV["#{env_prefix}_DATABASE_CA"], :sslcert => ENV["#{env_prefix}_DATABASE_CERT"], :sslkey => ENV["#{env_prefix}_DATABASE_KEY"], })) end config end end
[ "def", "db_config", "@db_config", "||=", "begin", "raise", "\"ENV['#{env_prefix}_DATABASE_URL'] expected but not found!\"", "unless", "ENV", "[", "\"#{env_prefix}_DATABASE_URL\"", "]", "config", "=", "parse_db_uri", "(", "ENV", "[", "\"#{env_prefix}_DATABASE_URL\"", "]", ")", "if", "ENV", "[", "\"#{env_prefix}_DATABASE_CA\"", "]", "config", ".", "merge!", "(", "db_configuration", "(", "{", ":sslca", "=>", "ENV", "[", "\"#{env_prefix}_DATABASE_CA\"", "]", ",", ":sslcert", "=>", "ENV", "[", "\"#{env_prefix}_DATABASE_CERT\"", "]", ",", ":sslkey", "=>", "ENV", "[", "\"#{env_prefix}_DATABASE_KEY\"", "]", ",", "}", ")", ")", "end", "config", "end", "end" ]
Returns an ActiveRecord configuration hash based on the environment variables.
[ "Returns", "an", "ActiveRecord", "configuration", "hash", "based", "on", "the", "environment", "variables", "." ]
1eec5b85e85e03645fa2c478cbaf8aec574ad5a5
https://github.com/nbudin/heroku_external_db/blob/1eec5b85e85e03645fa2c478cbaf8aec574ad5a5/lib/heroku_external_db.rb#L103-L118
train
sdalu/ruby-ble
lib/ble/notifications.rb
BLE.Notifications.start_notify!
def start_notify!(service, characteristic) char= _find_characteristic(service, characteristic) if char.flag?('notify') char.notify! else raise OperationNotSupportedError.new("No notifications available for characteristic #{characteristic}") end end
ruby
def start_notify!(service, characteristic) char= _find_characteristic(service, characteristic) if char.flag?('notify') char.notify! else raise OperationNotSupportedError.new("No notifications available for characteristic #{characteristic}") end end
[ "def", "start_notify!", "(", "service", ",", "characteristic", ")", "char", "=", "_find_characteristic", "(", "service", ",", "characteristic", ")", "if", "char", ".", "flag?", "(", "'notify'", ")", "char", ".", "notify!", "else", "raise", "OperationNotSupportedError", ".", "new", "(", "\"No notifications available for characteristic #{characteristic}\"", ")", "end", "end" ]
Registers current device for notifications of the given _characteristic_. Synonym for 'subscribe' or 'activate'. This step is required in order to later receive notifications. @param service [String, Symbol] @param characteristic [String, Symbol]
[ "Registers", "current", "device", "for", "notifications", "of", "the", "given", "_characteristic_", ".", "Synonym", "for", "subscribe", "or", "activate", ".", "This", "step", "is", "required", "in", "order", "to", "later", "receive", "notifications", "." ]
4c3b32d0ee65f787be235f1a5ee3878e6dcd995a
https://github.com/sdalu/ruby-ble/blob/4c3b32d0ee65f787be235f1a5ee3878e6dcd995a/lib/ble/notifications.rb#L10-L17
train
sdalu/ruby-ble
lib/ble/notifications.rb
BLE.Notifications.on_notification
def on_notification(service, characteristic, raw: false, &callback) _require_connection! char= _find_characteristic(service, characteristic) if char.flag?('notify') char.on_change(raw: raw) { |val| callback.call(val) } elsif char.flag?('encrypt-read') || char.flag?('encrypt-authenticated-read') raise NotYetImplemented else raise AccessUnavailable end end
ruby
def on_notification(service, characteristic, raw: false, &callback) _require_connection! char= _find_characteristic(service, characteristic) if char.flag?('notify') char.on_change(raw: raw) { |val| callback.call(val) } elsif char.flag?('encrypt-read') || char.flag?('encrypt-authenticated-read') raise NotYetImplemented else raise AccessUnavailable end end
[ "def", "on_notification", "(", "service", ",", "characteristic", ",", "raw", ":", "false", ",", "&", "callback", ")", "_require_connection!", "char", "=", "_find_characteristic", "(", "service", ",", "characteristic", ")", "if", "char", ".", "flag?", "(", "'notify'", ")", "char", ".", "on_change", "(", "raw", ":", "raw", ")", "{", "|", "val", "|", "callback", ".", "call", "(", "val", ")", "}", "elsif", "char", ".", "flag?", "(", "'encrypt-read'", ")", "||", "char", ".", "flag?", "(", "'encrypt-authenticated-read'", ")", "raise", "NotYetImplemented", "else", "raise", "AccessUnavailable", "end", "end" ]
Registers the callback to be invoked when a notification from the given _characteristic_ is received. NOTE: Requires the device to be subscribed to _characteristic_ notifications. @param service [String, Symbol] @param characteristic [String, Symbol] @param raw [Boolean] When raw is true the value (set/get) is a binary string, instead of an object corresponding to the decoded characteristic (float, integer, array, ...) @param callback [Proc] This callback will have the notified value as argument.
[ "Registers", "the", "callback", "to", "be", "invoked", "when", "a", "notification", "from", "the", "given", "_characteristic_", "is", "received", "." ]
4c3b32d0ee65f787be235f1a5ee3878e6dcd995a
https://github.com/sdalu/ruby-ble/blob/4c3b32d0ee65f787be235f1a5ee3878e6dcd995a/lib/ble/notifications.rb#L28-L41
train
bhaberer/steam-api
lib/steam-api/client.rb
Steam.Client.get
def get(resource, params: {}, key: Steam.apikey) params[:key] = key response = @conn.get resource, params JSON.parse(response.body) rescue JSON::ParserError # If the steam web api returns an error it's virtually never in json, so # lets pretend that we're getting some sort of consistant response # for errors. { error: '500 Internal Server Error' } end
ruby
def get(resource, params: {}, key: Steam.apikey) params[:key] = key response = @conn.get resource, params JSON.parse(response.body) rescue JSON::ParserError # If the steam web api returns an error it's virtually never in json, so # lets pretend that we're getting some sort of consistant response # for errors. { error: '500 Internal Server Error' } end
[ "def", "get", "(", "resource", ",", "params", ":", "{", "}", ",", "key", ":", "Steam", ".", "apikey", ")", "params", "[", ":key", "]", "=", "key", "response", "=", "@conn", ".", "get", "resource", ",", "params", "JSON", ".", "parse", "(", "response", ".", "body", ")", "rescue", "JSON", "::", "ParserError", "{", "error", ":", "'500 Internal Server Error'", "}", "end" ]
overriding the get method of Faraday to make things simpler. @param [String] resource the resource you're targeting @param [Hash] params Hash of parameters to pass to the resource @param [String] key Steam API key
[ "overriding", "the", "get", "method", "of", "Faraday", "to", "make", "things", "simpler", "." ]
e7613b7689497d0d691397d600ec72164b7a3b96
https://github.com/bhaberer/steam-api/blob/e7613b7689497d0d691397d600ec72164b7a3b96/lib/steam-api/client.rb#L13-L22
train
PublicHealthEngland/ndr_ui
app/helpers/ndr_ui/bootstrap_helper.rb
NdrUi.BootstrapHelper.bootstrap_tab_nav_tag
def bootstrap_tab_nav_tag(title, linkto, active = false) content_tag('li', link_to(title, linkto, "data-toggle": 'tab'), active ? { class: 'active' } : {}) end
ruby
def bootstrap_tab_nav_tag(title, linkto, active = false) content_tag('li', link_to(title, linkto, "data-toggle": 'tab'), active ? { class: 'active' } : {}) end
[ "def", "bootstrap_tab_nav_tag", "(", "title", ",", "linkto", ",", "active", "=", "false", ")", "content_tag", "(", "'li'", ",", "link_to", "(", "title", ",", "linkto", ",", "\"data-toggle\"", ":", "'tab'", ")", ",", "active", "?", "{", "class", ":", "'active'", "}", ":", "{", "}", ")", "end" ]
Creates a simple bootstrap tab navigation. ==== Signatures bootstrap_tab_nav_tag(title, linkto, active = false) ==== Examples <%= bootstrap_tab_nav_tag("Fruits", "#fruits", true) %> # => <li class="active"><a href="#fruits" data-toggle="tab">Fruits</a></li>
[ "Creates", "a", "simple", "bootstrap", "tab", "navigation", "." ]
1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec
https://github.com/PublicHealthEngland/ndr_ui/blob/1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec/app/helpers/ndr_ui/bootstrap_helper.rb#L188-L192
train
PublicHealthEngland/ndr_ui
app/helpers/ndr_ui/bootstrap_helper.rb
NdrUi.BootstrapHelper.bootstrap_list_badge_and_link_to
def bootstrap_list_badge_and_link_to(type, count, name, path) html = content_tag(:div, bootstrap_badge_tag(type, count), class: 'pull-right') + name bootstrap_list_link_to(html, path) end
ruby
def bootstrap_list_badge_and_link_to(type, count, name, path) html = content_tag(:div, bootstrap_badge_tag(type, count), class: 'pull-right') + name bootstrap_list_link_to(html, path) end
[ "def", "bootstrap_list_badge_and_link_to", "(", "type", ",", "count", ",", "name", ",", "path", ")", "html", "=", "content_tag", "(", ":div", ",", "bootstrap_badge_tag", "(", "type", ",", "count", ")", ",", "class", ":", "'pull-right'", ")", "+", "name", "bootstrap_list_link_to", "(", "html", ",", "path", ")", "end" ]
Convenience wrapper for a bootstrap_list_link_to with badge
[ "Convenience", "wrapper", "for", "a", "bootstrap_list_link_to", "with", "badge" ]
1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec
https://github.com/PublicHealthEngland/ndr_ui/blob/1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec/app/helpers/ndr_ui/bootstrap_helper.rb#L195-L198
train
PublicHealthEngland/ndr_ui
app/helpers/ndr_ui/bootstrap_helper.rb
NdrUi.BootstrapHelper.bootstrap_progressbar_tag
def bootstrap_progressbar_tag(*args) percentage = args[0].to_i options = args[1] || {} options.stringify_keys! options['title'] ||= "#{percentage}%" classes = ['progress'] classes << options.delete('class') classes << 'progress-striped' type = options.delete('type').to_s type = " progress-bar-#{type}" unless type.blank? # Animate the progress bar unless something has broken: classes << 'active' unless type == 'danger' inner = content_tag(:div, '', class: "progress-bar#{type}", style: "width:#{percentage}%") options['class'] = classes.compact.join(' ') content_tag(:div, inner, options) end
ruby
def bootstrap_progressbar_tag(*args) percentage = args[0].to_i options = args[1] || {} options.stringify_keys! options['title'] ||= "#{percentage}%" classes = ['progress'] classes << options.delete('class') classes << 'progress-striped' type = options.delete('type').to_s type = " progress-bar-#{type}" unless type.blank? # Animate the progress bar unless something has broken: classes << 'active' unless type == 'danger' inner = content_tag(:div, '', class: "progress-bar#{type}", style: "width:#{percentage}%") options['class'] = classes.compact.join(' ') content_tag(:div, inner, options) end
[ "def", "bootstrap_progressbar_tag", "(", "*", "args", ")", "percentage", "=", "args", "[", "0", "]", ".", "to_i", "options", "=", "args", "[", "1", "]", "||", "{", "}", "options", ".", "stringify_keys!", "options", "[", "'title'", "]", "||=", "\"#{percentage}%\"", "classes", "=", "[", "'progress'", "]", "classes", "<<", "options", ".", "delete", "(", "'class'", ")", "classes", "<<", "'progress-striped'", "type", "=", "options", ".", "delete", "(", "'type'", ")", ".", "to_s", "type", "=", "\" progress-bar-#{type}\"", "unless", "type", ".", "blank?", "classes", "<<", "'active'", "unless", "type", "==", "'danger'", "inner", "=", "content_tag", "(", ":div", ",", "''", ",", "class", ":", "\"progress-bar#{type}\"", ",", "style", ":", "\"width:#{percentage}%\"", ")", "options", "[", "'class'", "]", "=", "classes", ".", "compact", ".", "join", "(", "' '", ")", "content_tag", "(", ":div", ",", "inner", ",", "options", ")", "end" ]
Creates a Boostrap progress bar. ==== Signatures bootstrap_progressbar_tag(options) ==== Examples <%= bootstrap_progressbar_tag(40) %> # => <div class="progress progress-striped active" title="40%"><div class="progress-bar" style="width:40%"></div></div> <%= bootstrap_progressbar_tag(40), type: :danger %> # => <div class="progress progress-striped active" title="40%"><div class="progress-bar progress-bar-danger" style="width:40%"></div></div> ==== Browser compatibility Bootstrap Progress bars use CSS3 gradients, transitions, and animations to achieve all their effects. These features are not supported in IE7-9 or older versions of Firefox. Versions earlier than Internet Explorer 10 and Opera 12 do not support animations.
[ "Creates", "a", "Boostrap", "progress", "bar", "." ]
1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec
https://github.com/PublicHealthEngland/ndr_ui/blob/1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec/app/helpers/ndr_ui/bootstrap_helper.rb#L330-L350
train
PublicHealthEngland/ndr_ui
app/helpers/ndr_ui/bootstrap_helper.rb
NdrUi.BootstrapHelper.description_list_name_value_pair
def description_list_name_value_pair(name, value, blank_value_placeholder = nil) # SECURE: TPG 2013-08-07: The output is sanitised by content_tag return unless value.present? || blank_value_placeholder.present? content_tag(:dt, name) + content_tag(:dd, value || content_tag(:span, blank_value_placeholder, class: 'text-muted')) end
ruby
def description_list_name_value_pair(name, value, blank_value_placeholder = nil) # SECURE: TPG 2013-08-07: The output is sanitised by content_tag return unless value.present? || blank_value_placeholder.present? content_tag(:dt, name) + content_tag(:dd, value || content_tag(:span, blank_value_placeholder, class: 'text-muted')) end
[ "def", "description_list_name_value_pair", "(", "name", ",", "value", ",", "blank_value_placeholder", "=", "nil", ")", "return", "unless", "value", ".", "present?", "||", "blank_value_placeholder", ".", "present?", "content_tag", "(", ":dt", ",", "name", ")", "+", "content_tag", "(", ":dd", ",", "value", "||", "content_tag", "(", ":span", ",", "blank_value_placeholder", ",", "class", ":", "'text-muted'", ")", ")", "end" ]
This helper produces a pair of HTML dt, dd tags to display name and value pairs. If a blank_value_placeholder is not defined then the pair are not shown if the value is blank. Otherwise the placeholder is shown in the text-muted style. ==== Signature description_list_name_value_pair(name, value, blank_value_placeholder = nil) ==== Examples <%= description_list_name_value_pair("Pear", "Value") %> # => <dt>Pear</dt><dd>Value</dd> <%= description_list_name_value_pair("Pear", nil, "[none]") %> # => <dt>Pear</dt><dd><span class="text-muted">[none]</span></dd>
[ "This", "helper", "produces", "a", "pair", "of", "HTML", "dt", "dd", "tags", "to", "display", "name", "and", "value", "pairs", ".", "If", "a", "blank_value_placeholder", "is", "not", "defined", "then", "the", "pair", "are", "not", "shown", "if", "the", "value", "is", "blank", ".", "Otherwise", "the", "placeholder", "is", "shown", "in", "the", "text", "-", "muted", "style", "." ]
1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec
https://github.com/PublicHealthEngland/ndr_ui/blob/1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec/app/helpers/ndr_ui/bootstrap_helper.rb#L400-L405
train
PublicHealthEngland/ndr_ui
app/helpers/ndr_ui/bootstrap_helper.rb
NdrUi.BootstrapHelper.details_link
def details_link(path, options = {}) return unless ndr_can?(:read, path) link_to_with_icon({ icon: 'share-alt', title: 'Details', path: path }.merge(options)) end
ruby
def details_link(path, options = {}) return unless ndr_can?(:read, path) link_to_with_icon({ icon: 'share-alt', title: 'Details', path: path }.merge(options)) end
[ "def", "details_link", "(", "path", ",", "options", "=", "{", "}", ")", "return", "unless", "ndr_can?", "(", ":read", ",", "path", ")", "link_to_with_icon", "(", "{", "icon", ":", "'share-alt'", ",", "title", ":", "'Details'", ",", "path", ":", "path", "}", ".", "merge", "(", "options", ")", ")", "end" ]
Creates a Boostrap 'Details' link. ==== Signatures details_link(path, options = {}) ==== Examples <%= details_link('#') %> # => <a title="Details" class="btn btn-default btn-xs" href="#"> <span class="glyphicon glyphicon-share-alt"></span> </a>
[ "Creates", "a", "Boostrap", "Details", "link", "." ]
1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec
https://github.com/PublicHealthEngland/ndr_ui/blob/1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec/app/helpers/ndr_ui/bootstrap_helper.rb#L450-L454
train
PublicHealthEngland/ndr_ui
app/helpers/ndr_ui/bootstrap_helper.rb
NdrUi.BootstrapHelper.edit_link
def edit_link(path, options = {}) return unless ndr_can?(:edit, path) path = edit_polymorphic_path(path) if path.is_a?(ActiveRecord::Base) link_to_with_icon({ icon: 'pencil', title: 'Edit', path: path }.merge(options)) end
ruby
def edit_link(path, options = {}) return unless ndr_can?(:edit, path) path = edit_polymorphic_path(path) if path.is_a?(ActiveRecord::Base) link_to_with_icon({ icon: 'pencil', title: 'Edit', path: path }.merge(options)) end
[ "def", "edit_link", "(", "path", ",", "options", "=", "{", "}", ")", "return", "unless", "ndr_can?", "(", ":edit", ",", "path", ")", "path", "=", "edit_polymorphic_path", "(", "path", ")", "if", "path", ".", "is_a?", "(", "ActiveRecord", "::", "Base", ")", "link_to_with_icon", "(", "{", "icon", ":", "'pencil'", ",", "title", ":", "'Edit'", ",", "path", ":", "path", "}", ".", "merge", "(", "options", ")", ")", "end" ]
Creates a Boostrap 'Edit' link. ==== Signatures edit_link(path, options = {}) ==== Examples <%= edit_link(#) %> # => <a title="Edit" class="btn btn-default btn-xs" href="#"> <span class="glyphicon glyphicon-pencil"></span> </a>
[ "Creates", "a", "Boostrap", "Edit", "link", "." ]
1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec
https://github.com/PublicHealthEngland/ndr_ui/blob/1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec/app/helpers/ndr_ui/bootstrap_helper.rb#L469-L475
train
PublicHealthEngland/ndr_ui
app/helpers/ndr_ui/bootstrap_helper.rb
NdrUi.BootstrapHelper.delete_link
def delete_link(path, options = {}) return unless ndr_can?(:delete, path) defaults = { icon: 'trash icon-white', title: 'Delete', path: path, class: 'btn btn-xs btn-danger', method: :delete, 'data-confirm': I18n.translate(:'ndr_ui.confirm_delete', locale: options[:locale]) } link_to_with_icon(defaults.merge(options)) end
ruby
def delete_link(path, options = {}) return unless ndr_can?(:delete, path) defaults = { icon: 'trash icon-white', title: 'Delete', path: path, class: 'btn btn-xs btn-danger', method: :delete, 'data-confirm': I18n.translate(:'ndr_ui.confirm_delete', locale: options[:locale]) } link_to_with_icon(defaults.merge(options)) end
[ "def", "delete_link", "(", "path", ",", "options", "=", "{", "}", ")", "return", "unless", "ndr_can?", "(", ":delete", ",", "path", ")", "defaults", "=", "{", "icon", ":", "'trash icon-white'", ",", "title", ":", "'Delete'", ",", "path", ":", "path", ",", "class", ":", "'btn btn-xs btn-danger'", ",", "method", ":", ":delete", ",", "'data-confirm'", ":", "I18n", ".", "translate", "(", ":'", "'", ",", "locale", ":", "options", "[", ":locale", "]", ")", "}", "link_to_with_icon", "(", "defaults", ".", "merge", "(", "options", ")", ")", "end" ]
Creates a Boostrap 'Delete' link. ==== Signatures delete_link(path, options = {}) ==== Examples <%= delete_link('#') %> # => <a title="Delete" class="btn btn-xs btn-danger" rel="nofollow" href="#" data-method="delete" data-confirm="Are you sure?"> <span class="glyphicon glyphicon-trash icon-white"></span> </a>'
[ "Creates", "a", "Boostrap", "Delete", "link", "." ]
1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec
https://github.com/PublicHealthEngland/ndr_ui/blob/1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec/app/helpers/ndr_ui/bootstrap_helper.rb#L490-L500
train
PublicHealthEngland/ndr_ui
app/helpers/ndr_ui/bootstrap_helper.rb
NdrUi.BootstrapHelper.link_to_with_icon
def link_to_with_icon(options = {}) options[:class] ||= 'btn btn-default btn-xs' icon = bootstrap_icon_tag(options.delete(:icon)) content = options.delete(:text) ? icon + ' ' + options[:title] : icon link_to content, options.delete(:path), options end
ruby
def link_to_with_icon(options = {}) options[:class] ||= 'btn btn-default btn-xs' icon = bootstrap_icon_tag(options.delete(:icon)) content = options.delete(:text) ? icon + ' ' + options[:title] : icon link_to content, options.delete(:path), options end
[ "def", "link_to_with_icon", "(", "options", "=", "{", "}", ")", "options", "[", ":class", "]", "||=", "'btn btn-default btn-xs'", "icon", "=", "bootstrap_icon_tag", "(", "options", ".", "delete", "(", ":icon", ")", ")", "content", "=", "options", ".", "delete", "(", ":text", ")", "?", "icon", "+", "' '", "+", "options", "[", ":title", "]", ":", "icon", "link_to", "content", ",", "options", ".", "delete", "(", ":path", ")", ",", "options", "end" ]
Creates a Boostrap link with icon. ==== Signatures link_to_with_icon(options) ==== Examples <%= link_to_with_icon( { icon: 'trash icon-white', title: 'Delete', path: '#' } ) %> # => <a title="Delete" class="btn btn-default btn-xs" href="#"> <span class="glyphicon glyphicon-trash icon-white"></span> </a>'
[ "Creates", "a", "Boostrap", "link", "with", "icon", "." ]
1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec
https://github.com/PublicHealthEngland/ndr_ui/blob/1fb8ef2eb8bfed43ff54cf4b9cafe53b3d1843ec/app/helpers/ndr_ui/bootstrap_helper.rb#L540-L545
train