id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
800
potatosalad/ruby-jose
lib/jose/jwe.rb
JOSE.JWE.key_encrypt
def key_encrypt(key, decrypted_key) encrypted_key, new_alg = alg.key_encrypt(key, enc, decrypted_key) new_jwe = JOSE::JWE.from_map(to_map) new_jwe.alg = new_alg return encrypted_key, new_jwe end
ruby
def key_encrypt(key, decrypted_key) encrypted_key, new_alg = alg.key_encrypt(key, enc, decrypted_key) new_jwe = JOSE::JWE.from_map(to_map) new_jwe.alg = new_alg return encrypted_key, new_jwe end
[ "def", "key_encrypt", "(", "key", ",", "decrypted_key", ")", "encrypted_key", ",", "new_alg", "=", "alg", ".", "key_encrypt", "(", "key", ",", "enc", ",", "decrypted_key", ")", "new_jwe", "=", "JOSE", "::", "JWE", ".", "from_map", "(", "to_map", ")", "new_jwe", ".", "alg", "=", "new_alg", "return", "encrypted_key", ",", "new_jwe", "end" ]
Encrypts the `decrypted_key` using the `key` and the `"alg"` and `"enc"` specified by the `jwe`. @param [JOSE::JWK, [JOSE::JWK]] key @param [String] decrypted_key @return [[String, JOSE::JWE]]
[ "Encrypts", "the", "decrypted_key", "using", "the", "key", "and", "the", "alg", "and", "enc", "specified", "by", "the", "jwe", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwe.rb#L865-L870
801
potatosalad/ruby-jose
lib/jose/jwe.rb
JOSE.JWE.next_cek
def next_cek(key) decrypted_key, new_alg = alg.next_cek(key, enc) new_jwe = JOSE::JWE.from_map(to_map) new_jwe.alg = new_alg return decrypted_key, new_jwe end
ruby
def next_cek(key) decrypted_key, new_alg = alg.next_cek(key, enc) new_jwe = JOSE::JWE.from_map(to_map) new_jwe.alg = new_alg return decrypted_key, new_jwe end
[ "def", "next_cek", "(", "key", ")", "decrypted_key", ",", "new_alg", "=", "alg", ".", "next_cek", "(", "key", ",", "enc", ")", "new_jwe", "=", "JOSE", "::", "JWE", ".", "from_map", "(", "to_map", ")", "new_jwe", ".", "alg", "=", "new_alg", "return", "decrypted_key", ",", "new_jwe", "end" ]
Returns the next `cek` using the `jwk` and the `"alg"` and `"enc"` specified by the `jwe`. @param [JOSE::JWK, [JOSE::JWK, JOSE::JWK]] key @return [[String, JOSE::JWE]]
[ "Returns", "the", "next", "cek", "using", "the", "jwk", "and", "the", "alg", "and", "enc", "specified", "by", "the", "jwe", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwe.rb#L940-L945
802
tas50/stove
lib/stove/validator.rb
Stove.Validator.run
def run(cookbook, options = {}) log.info("Running validations for `#{klass.id}.#{id}'") inside(cookbook) do instance = klass.new(cookbook, options) unless result = instance.instance_eval(&block) log.debug("Validation failed, result: #{result.inspect}") # Convert the class and id to their magical equivalents error = Error.const_get("#{Util.camelize(klass.id)}#{Util.camelize(id)}ValidationFailed") raise error.new(path: Dir.pwd, result: result) end end log.debug("Validation #{id} passed!") end
ruby
def run(cookbook, options = {}) log.info("Running validations for `#{klass.id}.#{id}'") inside(cookbook) do instance = klass.new(cookbook, options) unless result = instance.instance_eval(&block) log.debug("Validation failed, result: #{result.inspect}") # Convert the class and id to their magical equivalents error = Error.const_get("#{Util.camelize(klass.id)}#{Util.camelize(id)}ValidationFailed") raise error.new(path: Dir.pwd, result: result) end end log.debug("Validation #{id} passed!") end
[ "def", "run", "(", "cookbook", ",", "options", "=", "{", "}", ")", "log", ".", "info", "(", "\"Running validations for `#{klass.id}.#{id}'\"", ")", "inside", "(", "cookbook", ")", "do", "instance", "=", "klass", ".", "new", "(", "cookbook", ",", "options", ")", "unless", "result", "=", "instance", ".", "instance_eval", "(", "block", ")", "log", ".", "debug", "(", "\"Validation failed, result: #{result.inspect}\"", ")", "# Convert the class and id to their magical equivalents", "error", "=", "Error", ".", "const_get", "(", "\"#{Util.camelize(klass.id)}#{Util.camelize(id)}ValidationFailed\"", ")", "raise", "error", ".", "new", "(", "path", ":", "Dir", ".", "pwd", ",", "result", ":", "result", ")", "end", "end", "log", ".", "debug", "(", "\"Validation #{id} passed!\"", ")", "end" ]
Create a new validator object. @param [~Class] klass the class that created this validator @param [Symbol] id the identifier or field this validator runs against @param [Proc] block the block to execute to see if the validation passes Execute this validation in the context of the creating class, inside the given cookbook's path. @param [Cookbook] the cookbook to run this validation against
[ "Create", "a", "new", "validator", "object", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/validator.rb#L51-L66
803
tas50/stove
lib/stove/packager.rb
Stove.Packager.tar
def tar(root, slip) io = StringIO.new('', 'r+b') Gem::Package::TarWriter.new(io) do |tar| slip.each do |original_file, tarball_file| mode = File.stat(original_file).mode if File.directory?(original_file) tar.mkdir(tarball_file, mode) else tar.add_file(tarball_file, mode) do |tf| File.open(original_file, 'rb') { |f| tf.write(f.read) } end end end end io.rewind io end
ruby
def tar(root, slip) io = StringIO.new('', 'r+b') Gem::Package::TarWriter.new(io) do |tar| slip.each do |original_file, tarball_file| mode = File.stat(original_file).mode if File.directory?(original_file) tar.mkdir(tarball_file, mode) else tar.add_file(tarball_file, mode) do |tf| File.open(original_file, 'rb') { |f| tf.write(f.read) } end end end end io.rewind io end
[ "def", "tar", "(", "root", ",", "slip", ")", "io", "=", "StringIO", ".", "new", "(", "''", ",", "'r+b'", ")", "Gem", "::", "Package", "::", "TarWriter", ".", "new", "(", "io", ")", "do", "|", "tar", "|", "slip", ".", "each", "do", "|", "original_file", ",", "tarball_file", "|", "mode", "=", "File", ".", "stat", "(", "original_file", ")", ".", "mode", "if", "File", ".", "directory?", "(", "original_file", ")", "tar", ".", "mkdir", "(", "tarball_file", ",", "mode", ")", "else", "tar", ".", "add_file", "(", "tarball_file", ",", "mode", ")", "do", "|", "tf", "|", "File", ".", "open", "(", "original_file", ",", "'rb'", ")", "{", "|", "f", "|", "tf", ".", "write", "(", "f", ".", "read", ")", "}", "end", "end", "end", "end", "io", ".", "rewind", "io", "end" ]
Create a tar file from the given root and packaging slip @param [String] root the root where the tar files are being created @param [Hash<String, String>] slip the map from physical file path to tarball file path @return [StringIO] the io object that contains the tarball contents
[ "Create", "a", "tar", "file", "from", "the", "given", "root", "and", "packaging", "slip" ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/packager.rb#L116-L134
804
tas50/stove
lib/stove/cli.rb
Stove.Cli.option_parser
def option_parser @option_parser ||= OptionParser.new do |opts| opts.banner = 'Usage: stove [OPTIONS]' opts.separator '' opts.separator 'Plugins:' opts.on('--no-git', 'Do not use the git plugin. Skips tagging if specified.') do options[:no_git] = true end opts.separator '' opts.separator 'Upload Options:' opts.on('--endpoint [URL]', 'Supermarket endpoint') do |v| options[:endpoint] = v end opts.on('--username [USERNAME]', 'Username to authenticate with') do |v| options[:username] = v end opts.on('--key [PATH]', 'Path to the private key on disk') do |v| options[:key] = v end opts.on('--[no-]extended-metadata', 'Include non-backwards compatible metadata keys such as `issues_url`') do |v| options[:extended_metadata] = v end opts.on('--no-ssl-verify', 'Turn off ssl verify') do options[:ssl_verify] = false end opts.separator '' opts.separator 'Git Options:' opts.on('--remote [REMOTE]', 'Name of the git remote') do |v| options[:remote] = v end opts.on('--branch [BRANCH]', 'Name of the git branch') do |v| options[:branch] = v end opts.on('--sign', 'Sign git tags') do options[:sign] = true end opts.separator '' opts.separator 'Artifactory Options:' opts.on('--artifactory [URL]', 'URL for the Artifactory repository') do |v| options[:artifactory] = v end opts.on('--artifactory-key [KEY]', 'Artifactory API key to use') do |v| options[:artifactory_key] = if v[0] == '@' # If passed a key looking like @foo, read it as a file. This allows # passing in the key securely. IO.read(File.expand_path(v[1..-1])) else v end end opts.separator '' opts.separator 'Global Options:' opts.on('--log-level [LEVEL]', 'Set the log verbosity') do |v| options[:log_level] = v end opts.on('--path [PATH]', 'Change the path to a cookbook') do |v| options[:path] = v end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('-v', '--version', 'Show version') do puts Stove::VERSION exit(0) end end end
ruby
def option_parser @option_parser ||= OptionParser.new do |opts| opts.banner = 'Usage: stove [OPTIONS]' opts.separator '' opts.separator 'Plugins:' opts.on('--no-git', 'Do not use the git plugin. Skips tagging if specified.') do options[:no_git] = true end opts.separator '' opts.separator 'Upload Options:' opts.on('--endpoint [URL]', 'Supermarket endpoint') do |v| options[:endpoint] = v end opts.on('--username [USERNAME]', 'Username to authenticate with') do |v| options[:username] = v end opts.on('--key [PATH]', 'Path to the private key on disk') do |v| options[:key] = v end opts.on('--[no-]extended-metadata', 'Include non-backwards compatible metadata keys such as `issues_url`') do |v| options[:extended_metadata] = v end opts.on('--no-ssl-verify', 'Turn off ssl verify') do options[:ssl_verify] = false end opts.separator '' opts.separator 'Git Options:' opts.on('--remote [REMOTE]', 'Name of the git remote') do |v| options[:remote] = v end opts.on('--branch [BRANCH]', 'Name of the git branch') do |v| options[:branch] = v end opts.on('--sign', 'Sign git tags') do options[:sign] = true end opts.separator '' opts.separator 'Artifactory Options:' opts.on('--artifactory [URL]', 'URL for the Artifactory repository') do |v| options[:artifactory] = v end opts.on('--artifactory-key [KEY]', 'Artifactory API key to use') do |v| options[:artifactory_key] = if v[0] == '@' # If passed a key looking like @foo, read it as a file. This allows # passing in the key securely. IO.read(File.expand_path(v[1..-1])) else v end end opts.separator '' opts.separator 'Global Options:' opts.on('--log-level [LEVEL]', 'Set the log verbosity') do |v| options[:log_level] = v end opts.on('--path [PATH]', 'Change the path to a cookbook') do |v| options[:path] = v end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('-v', '--version', 'Show version') do puts Stove::VERSION exit(0) end end end
[ "def", "option_parser", "@option_parser", "||=", "OptionParser", ".", "new", "do", "|", "opts", "|", "opts", ".", "banner", "=", "'Usage: stove [OPTIONS]'", "opts", ".", "separator", "''", "opts", ".", "separator", "'Plugins:'", "opts", ".", "on", "(", "'--no-git'", ",", "'Do not use the git plugin. Skips tagging if specified.'", ")", "do", "options", "[", ":no_git", "]", "=", "true", "end", "opts", ".", "separator", "''", "opts", ".", "separator", "'Upload Options:'", "opts", ".", "on", "(", "'--endpoint [URL]'", ",", "'Supermarket endpoint'", ")", "do", "|", "v", "|", "options", "[", ":endpoint", "]", "=", "v", "end", "opts", ".", "on", "(", "'--username [USERNAME]'", ",", "'Username to authenticate with'", ")", "do", "|", "v", "|", "options", "[", ":username", "]", "=", "v", "end", "opts", ".", "on", "(", "'--key [PATH]'", ",", "'Path to the private key on disk'", ")", "do", "|", "v", "|", "options", "[", ":key", "]", "=", "v", "end", "opts", ".", "on", "(", "'--[no-]extended-metadata'", ",", "'Include non-backwards compatible metadata keys such as `issues_url`'", ")", "do", "|", "v", "|", "options", "[", ":extended_metadata", "]", "=", "v", "end", "opts", ".", "on", "(", "'--no-ssl-verify'", ",", "'Turn off ssl verify'", ")", "do", "options", "[", ":ssl_verify", "]", "=", "false", "end", "opts", ".", "separator", "''", "opts", ".", "separator", "'Git Options:'", "opts", ".", "on", "(", "'--remote [REMOTE]'", ",", "'Name of the git remote'", ")", "do", "|", "v", "|", "options", "[", ":remote", "]", "=", "v", "end", "opts", ".", "on", "(", "'--branch [BRANCH]'", ",", "'Name of the git branch'", ")", "do", "|", "v", "|", "options", "[", ":branch", "]", "=", "v", "end", "opts", ".", "on", "(", "'--sign'", ",", "'Sign git tags'", ")", "do", "options", "[", ":sign", "]", "=", "true", "end", "opts", ".", "separator", "''", "opts", ".", "separator", "'Artifactory Options:'", "opts", ".", "on", "(", "'--artifactory [URL]'", ",", "'URL for the Artifactory repository'", ")", "do", "|", "v", "|", "options", "[", ":artifactory", "]", "=", "v", "end", "opts", ".", "on", "(", "'--artifactory-key [KEY]'", ",", "'Artifactory API key to use'", ")", "do", "|", "v", "|", "options", "[", ":artifactory_key", "]", "=", "if", "v", "[", "0", "]", "==", "'@'", "# If passed a key looking like @foo, read it as a file. This allows", "# passing in the key securely.", "IO", ".", "read", "(", "File", ".", "expand_path", "(", "v", "[", "1", "..", "-", "1", "]", ")", ")", "else", "v", "end", "end", "opts", ".", "separator", "''", "opts", ".", "separator", "'Global Options:'", "opts", ".", "on", "(", "'--log-level [LEVEL]'", ",", "'Set the log verbosity'", ")", "do", "|", "v", "|", "options", "[", ":log_level", "]", "=", "v", "end", "opts", ".", "on", "(", "'--path [PATH]'", ",", "'Change the path to a cookbook'", ")", "do", "|", "v", "|", "options", "[", ":path", "]", "=", "v", "end", "opts", ".", "on_tail", "(", "'-h'", ",", "'--help'", ",", "'Show this message'", ")", "do", "puts", "opts", "exit", "end", "opts", ".", "on_tail", "(", "'-v'", ",", "'--version'", ",", "'Show version'", ")", "do", "puts", "Stove", "::", "VERSION", "exit", "(", "0", ")", "end", "end", "end" ]
The option parser for handling command line flags. @return [OptionParser]
[ "The", "option", "parser", "for", "handling", "command", "line", "flags", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/cli.rb#L82-L169
805
tas50/stove
lib/stove/cli.rb
Stove.Cli.options
def options @options ||= { # Upload options :endpoint => nil, :username => Config.username, :key => Config.key, :extended_metadata => true, :ssl_verify => true, # Git options :remote => 'origin', :branch => 'master', :sign => false, # Artifactory options :artifactory => false, :artifactory_key => ENV['ARTIFACTORY_API_KEY'], # Global options :log_level => :warn, :path => Dir.pwd, } end
ruby
def options @options ||= { # Upload options :endpoint => nil, :username => Config.username, :key => Config.key, :extended_metadata => true, :ssl_verify => true, # Git options :remote => 'origin', :branch => 'master', :sign => false, # Artifactory options :artifactory => false, :artifactory_key => ENV['ARTIFACTORY_API_KEY'], # Global options :log_level => :warn, :path => Dir.pwd, } end
[ "def", "options", "@options", "||=", "{", "# Upload options", ":endpoint", "=>", "nil", ",", ":username", "=>", "Config", ".", "username", ",", ":key", "=>", "Config", ".", "key", ",", ":extended_metadata", "=>", "true", ",", ":ssl_verify", "=>", "true", ",", "# Git options", ":remote", "=>", "'origin'", ",", ":branch", "=>", "'master'", ",", ":sign", "=>", "false", ",", "# Artifactory options", ":artifactory", "=>", "false", ",", ":artifactory_key", "=>", "ENV", "[", "'ARTIFACTORY_API_KEY'", "]", ",", "# Global options", ":log_level", "=>", ":warn", ",", ":path", "=>", "Dir", ".", "pwd", ",", "}", "end" ]
The options to pass to the cookbook. Includes default values that are manipulated by the option parser. @return [Hash]
[ "The", "options", "to", "pass", "to", "the", "cookbook", ".", "Includes", "default", "values", "that", "are", "manipulated", "by", "the", "option", "parser", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/cli.rb#L175-L197
806
tas50/stove
lib/stove/supermarket.rb
Stove.Supermarket.upload
def upload(cookbook, extended_metadata = false) connection.post('cookbooks', { 'tarball' => cookbook.tarball(extended_metadata), # This is for legacy, backwards-compatability reasons. The new # Supermarket site does not require a category, but many of the testing # tools still assume a cookbook category is present. We just hardcode # "Other" here. 'cookbook' => JSON.fast_generate(category: 'Other'), }) end
ruby
def upload(cookbook, extended_metadata = false) connection.post('cookbooks', { 'tarball' => cookbook.tarball(extended_metadata), # This is for legacy, backwards-compatability reasons. The new # Supermarket site does not require a category, but many of the testing # tools still assume a cookbook category is present. We just hardcode # "Other" here. 'cookbook' => JSON.fast_generate(category: 'Other'), }) end
[ "def", "upload", "(", "cookbook", ",", "extended_metadata", "=", "false", ")", "connection", ".", "post", "(", "'cookbooks'", ",", "{", "'tarball'", "=>", "cookbook", ".", "tarball", "(", "extended_metadata", ")", ",", "# This is for legacy, backwards-compatability reasons. The new", "# Supermarket site does not require a category, but many of the testing", "# tools still assume a cookbook category is present. We just hardcode", "# \"Other\" here.", "'cookbook'", "=>", "JSON", ".", "fast_generate", "(", "category", ":", "'Other'", ")", ",", "}", ")", "end" ]
Upload a cookbook to the community site. @param [Cookbook] cookbook the cookbook to upload
[ "Upload", "a", "cookbook", "to", "the", "community", "site", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/supermarket.rb#L53-L63
807
tas50/stove
lib/stove/supermarket.rb
Stove.Supermarket.connection
def connection @connection ||= ChefAPI::Connection.new do |conn| conn.endpoint = ENV['STOVE_ENDPOINT'] || Config.endpoint || DEFAULT_ENDPOINT conn.client = ENV['STOVE_USERNAME'] || Config.username conn.key = ENV['STOVE_KEY'] || Config.key conn.ssl_verify = ENV['STOVE_NO_SSL_VERIFY'] || Config.ssl_verify end end
ruby
def connection @connection ||= ChefAPI::Connection.new do |conn| conn.endpoint = ENV['STOVE_ENDPOINT'] || Config.endpoint || DEFAULT_ENDPOINT conn.client = ENV['STOVE_USERNAME'] || Config.username conn.key = ENV['STOVE_KEY'] || Config.key conn.ssl_verify = ENV['STOVE_NO_SSL_VERIFY'] || Config.ssl_verify end end
[ "def", "connection", "@connection", "||=", "ChefAPI", "::", "Connection", ".", "new", "do", "|", "conn", "|", "conn", ".", "endpoint", "=", "ENV", "[", "'STOVE_ENDPOINT'", "]", "||", "Config", ".", "endpoint", "||", "DEFAULT_ENDPOINT", "conn", ".", "client", "=", "ENV", "[", "'STOVE_USERNAME'", "]", "||", "Config", ".", "username", "conn", ".", "key", "=", "ENV", "[", "'STOVE_KEY'", "]", "||", "Config", ".", "key", "conn", ".", "ssl_verify", "=", "ENV", "[", "'STOVE_NO_SSL_VERIFY'", "]", "||", "Config", ".", "ssl_verify", "end", "end" ]
The ChefAPI connection object with lots of pretty middleware.
[ "The", "ChefAPI", "connection", "object", "with", "lots", "of", "pretty", "middleware", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/supermarket.rb#L70-L77
808
tas50/stove
lib/stove/artifactory.rb
Stove.Artifactory.upload
def upload(cookbook, extended_metadata = false) # Artifactory doesn't prevent uploading over an existing release in # some cases so let's check for that. Seriously never do this, go delete # and then re-upload if you have to. response = request(:get, "api/v1/cookbooks/#{cookbook.name}/versions/#{cookbook.version}") # Artifactory's version of the cookbook_version endpoint returns an # empty 200 on an unknown version. unless response.code == '404' || (response.code == '200' && response.body.to_s == '') raise Error::CookbookAlreadyExists.new(cookbook: cookbook) end # Run the upload. response = request(:post, "api/v1/cookbooks/#{cookbook.name}.tgz") do |req| req.body_stream = cookbook.tarball(extended_metadata) req.content_length = req.body_stream.size req['Content-Type'] = 'application/x-binary' end response.error! unless response.code == '201' end
ruby
def upload(cookbook, extended_metadata = false) # Artifactory doesn't prevent uploading over an existing release in # some cases so let's check for that. Seriously never do this, go delete # and then re-upload if you have to. response = request(:get, "api/v1/cookbooks/#{cookbook.name}/versions/#{cookbook.version}") # Artifactory's version of the cookbook_version endpoint returns an # empty 200 on an unknown version. unless response.code == '404' || (response.code == '200' && response.body.to_s == '') raise Error::CookbookAlreadyExists.new(cookbook: cookbook) end # Run the upload. response = request(:post, "api/v1/cookbooks/#{cookbook.name}.tgz") do |req| req.body_stream = cookbook.tarball(extended_metadata) req.content_length = req.body_stream.size req['Content-Type'] = 'application/x-binary' end response.error! unless response.code == '201' end
[ "def", "upload", "(", "cookbook", ",", "extended_metadata", "=", "false", ")", "# Artifactory doesn't prevent uploading over an existing release in", "# some cases so let's check for that. Seriously never do this, go delete", "# and then re-upload if you have to.", "response", "=", "request", "(", ":get", ",", "\"api/v1/cookbooks/#{cookbook.name}/versions/#{cookbook.version}\"", ")", "# Artifactory's version of the cookbook_version endpoint returns an", "# empty 200 on an unknown version.", "unless", "response", ".", "code", "==", "'404'", "||", "(", "response", ".", "code", "==", "'200'", "&&", "response", ".", "body", ".", "to_s", "==", "''", ")", "raise", "Error", "::", "CookbookAlreadyExists", ".", "new", "(", "cookbook", ":", "cookbook", ")", "end", "# Run the upload.", "response", "=", "request", "(", ":post", ",", "\"api/v1/cookbooks/#{cookbook.name}.tgz\"", ")", "do", "|", "req", "|", "req", ".", "body_stream", "=", "cookbook", ".", "tarball", "(", "extended_metadata", ")", "req", ".", "content_length", "=", "req", ".", "body_stream", ".", "size", "req", "[", "'Content-Type'", "]", "=", "'application/x-binary'", "end", "response", ".", "error!", "unless", "response", ".", "code", "==", "'201'", "end" ]
Upload a cookbook to an Artifactory server. @param [Cookbook] cookbook the cookbook to upload
[ "Upload", "a", "cookbook", "to", "an", "Artifactory", "server", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/artifactory.rb#L13-L31
809
tas50/stove
lib/stove/artifactory.rb
Stove.Artifactory.connection
def connection @connection ||= begin uri = URI(Config.artifactory.strip) # Open the HTTP connection to artifactory. http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' http.use_ssl = true # Mimic the behavior of the Cookbook uploader for SSL verification. if ENV['STOVE_NO_SSL_VERIFY'] || !Config.ssl_verify http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end http.start end end
ruby
def connection @connection ||= begin uri = URI(Config.artifactory.strip) # Open the HTTP connection to artifactory. http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' http.use_ssl = true # Mimic the behavior of the Cookbook uploader for SSL verification. if ENV['STOVE_NO_SSL_VERIFY'] || !Config.ssl_verify http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end http.start end end
[ "def", "connection", "@connection", "||=", "begin", "uri", "=", "URI", "(", "Config", ".", "artifactory", ".", "strip", ")", "# Open the HTTP connection to artifactory.", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "if", "uri", ".", "scheme", "==", "'https'", "http", ".", "use_ssl", "=", "true", "# Mimic the behavior of the Cookbook uploader for SSL verification.", "if", "ENV", "[", "'STOVE_NO_SSL_VERIFY'", "]", "||", "!", "Config", ".", "ssl_verify", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "end", "http", ".", "start", "end", "end" ]
Create an HTTP connect to the Artifactory server. @return [Net::HTTP]
[ "Create", "an", "HTTP", "connect", "to", "the", "Artifactory", "server", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/artifactory.rb#L40-L54
810
tas50/stove
lib/stove/artifactory.rb
Stove.Artifactory.request
def request(method, path, &block) uri_string = Config.artifactory.strip # Make sure we end up with the right number of separators. uri_string << '/' unless uri_string.end_with?('/') uri_string << path uri = URI(uri_string) request = Net::HTTP.const_get(method.to_s.capitalize).new(uri) request['X-Jfrog-Art-Api'] = Config.artifactory_key.strip block.call(request) if block connection.request(request) end
ruby
def request(method, path, &block) uri_string = Config.artifactory.strip # Make sure we end up with the right number of separators. uri_string << '/' unless uri_string.end_with?('/') uri_string << path uri = URI(uri_string) request = Net::HTTP.const_get(method.to_s.capitalize).new(uri) request['X-Jfrog-Art-Api'] = Config.artifactory_key.strip block.call(request) if block connection.request(request) end
[ "def", "request", "(", "method", ",", "path", ",", "&", "block", ")", "uri_string", "=", "Config", ".", "artifactory", ".", "strip", "# Make sure we end up with the right number of separators.", "uri_string", "<<", "'/'", "unless", "uri_string", ".", "end_with?", "(", "'/'", ")", "uri_string", "<<", "path", "uri", "=", "URI", "(", "uri_string", ")", "request", "=", "Net", "::", "HTTP", ".", "const_get", "(", "method", ".", "to_s", ".", "capitalize", ")", ".", "new", "(", "uri", ")", "request", "[", "'X-Jfrog-Art-Api'", "]", "=", "Config", ".", "artifactory_key", ".", "strip", "block", ".", "call", "(", "request", ")", "if", "block", "connection", ".", "request", "(", "request", ")", "end" ]
Send an HTTP request to the Artifactory server. @param [Symbol] method HTTP method to use @param [String] path URI path to request @param [Proc] block Optional block to set request values @return [Net::HTTPResponse]
[ "Send", "an", "HTTP", "request", "to", "the", "Artifactory", "server", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/artifactory.rb#L70-L80
811
tas50/stove
lib/stove/cookbook.rb
Stove.Cookbook.released?
def released? Supermarket.cookbook(name, version) true rescue ChefAPI::Error::HTTPNotFound false end
ruby
def released? Supermarket.cookbook(name, version) true rescue ChefAPI::Error::HTTPNotFound false end
[ "def", "released?", "Supermarket", ".", "cookbook", "(", "name", ",", "version", ")", "true", "rescue", "ChefAPI", "::", "Error", "::", "HTTPNotFound", "false", "end" ]
Deterine if this cookbook version is released on the Supermarket @warn This is a fairly expensive operation and the result cannot be reliably cached! @return [Boolean] true if this cookbook at the current version exists on the community site, false otherwise
[ "Deterine", "if", "this", "cookbook", "version", "is", "released", "on", "the", "Supermarket" ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/cookbook.rb#L84-L89
812
tas50/stove
lib/stove/filter.rb
Stove.Filter.run
def run(cookbook, options = {}) log.info(message) instance = klass.new(cookbook, options) inside(cookbook) do instance.instance_eval(&block) end end
ruby
def run(cookbook, options = {}) log.info(message) instance = klass.new(cookbook, options) inside(cookbook) do instance.instance_eval(&block) end end
[ "def", "run", "(", "cookbook", ",", "options", "=", "{", "}", ")", "log", ".", "info", "(", "message", ")", "instance", "=", "klass", ".", "new", "(", "cookbook", ",", "options", ")", "inside", "(", "cookbook", ")", "do", "instance", ".", "instance_eval", "(", "block", ")", "end", "end" ]
Create a new filter object. @param [~Plugin::Base] klass the class that created this filter @param [String] message the message given by the filter @param [Proc] block the block captured by this filter Execute this filter in the context of the creating class, inside the given cookbook's path. @param [Cookbook] the cookbook to run this filter against
[ "Create", "a", "new", "filter", "object", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/filter.rb#L51-L58
813
kwatch/erubis
lib/erubis/evaluator.rb
Erubis.RubyEvaluator.evaluate
def evaluate(_context=Context.new) _context = Context.new(_context) if _context.is_a?(Hash) #return _context.instance_eval(@src, @filename || '(erubis)') #@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)') @_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)') return _context.instance_eval(&@_proc) end
ruby
def evaluate(_context=Context.new) _context = Context.new(_context) if _context.is_a?(Hash) #return _context.instance_eval(@src, @filename || '(erubis)') #@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)') @_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)') return _context.instance_eval(&@_proc) end
[ "def", "evaluate", "(", "_context", "=", "Context", ".", "new", ")", "_context", "=", "Context", ".", "new", "(", "_context", ")", "if", "_context", ".", "is_a?", "(", "Hash", ")", "#return _context.instance_eval(@src, @filename || '(erubis)')", "#@_proc ||= eval(\"proc { #{@src} }\", Erubis::EMPTY_BINDING, @filename || '(erubis)')", "@_proc", "||=", "eval", "(", "\"proc { #{@src} }\"", ",", "binding", "(", ")", ",", "@filename", "||", "'(erubis)'", ")", "return", "_context", ".", "instance_eval", "(", "@_proc", ")", "end" ]
invoke context.instance_eval(@src)
[ "invoke", "context", ".", "instance_eval", "(" ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/evaluator.rb#L69-L75
814
kwatch/erubis
lib/erubis/evaluator.rb
Erubis.RubyEvaluator.def_method
def def_method(object, method_name, filename=nil) m = object.is_a?(Module) ? :module_eval : :instance_eval object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)') end
ruby
def def_method(object, method_name, filename=nil) m = object.is_a?(Module) ? :module_eval : :instance_eval object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)') end
[ "def", "def_method", "(", "object", ",", "method_name", ",", "filename", "=", "nil", ")", "m", "=", "object", ".", "is_a?", "(", "Module", ")", "?", ":module_eval", ":", ":instance_eval", "object", ".", "__send__", "(", "m", ",", "\"def #{method_name}; #{@src}; end\"", ",", "filename", "||", "@filename", "||", "'(erubis)'", ")", "end" ]
if object is an Class or Module then define instance method to it, else define singleton method to it.
[ "if", "object", "is", "an", "Class", "or", "Module", "then", "define", "instance", "method", "to", "it", "else", "define", "singleton", "method", "to", "it", "." ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/evaluator.rb#L79-L82
815
kwatch/erubis
lib/erubis/converter.rb
Erubis.Converter.convert
def convert(input) codebuf = "" # or [] @preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble)) convert_input(codebuf, input) @postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble)) @_proc = nil # clear cached proc object return codebuf # or codebuf.join() end
ruby
def convert(input) codebuf = "" # or [] @preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble)) convert_input(codebuf, input) @postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble)) @_proc = nil # clear cached proc object return codebuf # or codebuf.join() end
[ "def", "convert", "(", "input", ")", "codebuf", "=", "\"\"", "# or []", "@preamble", ".", "nil?", "?", "add_preamble", "(", "codebuf", ")", ":", "(", "@preamble", "&&", "(", "codebuf", "<<", "@preamble", ")", ")", "convert_input", "(", "codebuf", ",", "input", ")", "@postamble", ".", "nil?", "?", "add_postamble", "(", "codebuf", ")", ":", "(", "@postamble", "&&", "(", "codebuf", "<<", "@postamble", ")", ")", "@_proc", "=", "nil", "# clear cached proc object", "return", "codebuf", "# or codebuf.join()", "end" ]
convert input string into target language
[ "convert", "input", "string", "into", "target", "language" ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/converter.rb#L33-L40
816
kwatch/erubis
lib/erubis/converter.rb
Erubis.Converter.detect_spaces_at_bol
def detect_spaces_at_bol(text, is_bol) lspace = nil if text.empty? lspace = "" if is_bol elsif text[-1] == ?\n lspace = "" else rindex = text.rindex(?\n) if rindex s = text[rindex+1..-1] if s =~ /\A[ \t]*\z/ lspace = s #text = text[0..rindex] text[rindex+1..-1] = '' end else if is_bol && text =~ /\A[ \t]*\z/ #lspace = text #text = nil lspace = text.dup text[0..-1] = '' end end end return lspace end
ruby
def detect_spaces_at_bol(text, is_bol) lspace = nil if text.empty? lspace = "" if is_bol elsif text[-1] == ?\n lspace = "" else rindex = text.rindex(?\n) if rindex s = text[rindex+1..-1] if s =~ /\A[ \t]*\z/ lspace = s #text = text[0..rindex] text[rindex+1..-1] = '' end else if is_bol && text =~ /\A[ \t]*\z/ #lspace = text #text = nil lspace = text.dup text[0..-1] = '' end end end return lspace end
[ "def", "detect_spaces_at_bol", "(", "text", ",", "is_bol", ")", "lspace", "=", "nil", "if", "text", ".", "empty?", "lspace", "=", "\"\"", "if", "is_bol", "elsif", "text", "[", "-", "1", "]", "==", "?\\n", "lspace", "=", "\"\"", "else", "rindex", "=", "text", ".", "rindex", "(", "?\\n", ")", "if", "rindex", "s", "=", "text", "[", "rindex", "+", "1", "..", "-", "1", "]", "if", "s", "=~", "/", "\\A", "\\t", "\\z", "/", "lspace", "=", "s", "#text = text[0..rindex]", "text", "[", "rindex", "+", "1", "..", "-", "1", "]", "=", "''", "end", "else", "if", "is_bol", "&&", "text", "=~", "/", "\\A", "\\t", "\\z", "/", "#lspace = text", "#text = nil", "lspace", "=", "text", ".", "dup", "text", "[", "0", "..", "-", "1", "]", "=", "''", "end", "end", "end", "return", "lspace", "end" ]
detect spaces at beginning of line
[ "detect", "spaces", "at", "beginning", "of", "line" ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/converter.rb#L47-L72
817
kwatch/erubis
lib/erubis/engine.rb
Erubis.Engine.process
def process(input, context=nil, filename=nil) code = convert(input) filename ||= '(erubis)' if context.is_a?(Binding) return eval(code, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(code, filename) end end
ruby
def process(input, context=nil, filename=nil) code = convert(input) filename ||= '(erubis)' if context.is_a?(Binding) return eval(code, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(code, filename) end end
[ "def", "process", "(", "input", ",", "context", "=", "nil", ",", "filename", "=", "nil", ")", "code", "=", "convert", "(", "input", ")", "filename", "||=", "'(erubis)'", "if", "context", ".", "is_a?", "(", "Binding", ")", "return", "eval", "(", "code", ",", "context", ",", "filename", ")", "else", "context", "=", "Context", ".", "new", "(", "context", ")", "if", "context", ".", "is_a?", "(", "Hash", ")", "return", "context", ".", "instance_eval", "(", "code", ",", "filename", ")", "end", "end" ]
helper method to convert and evaluate input text with context object. context may be Binding, Hash, or Object.
[ "helper", "method", "to", "convert", "and", "evaluate", "input", "text", "with", "context", "object", ".", "context", "may", "be", "Binding", "Hash", "or", "Object", "." ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/engine.rb#L72-L81
818
kwatch/erubis
lib/erubis/engine.rb
Erubis.Engine.process_proc
def process_proc(proc_obj, context=nil, filename=nil) if context.is_a?(Binding) filename ||= '(erubis)' return eval(proc_obj, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(&proc_obj) end end
ruby
def process_proc(proc_obj, context=nil, filename=nil) if context.is_a?(Binding) filename ||= '(erubis)' return eval(proc_obj, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(&proc_obj) end end
[ "def", "process_proc", "(", "proc_obj", ",", "context", "=", "nil", ",", "filename", "=", "nil", ")", "if", "context", ".", "is_a?", "(", "Binding", ")", "filename", "||=", "'(erubis)'", "return", "eval", "(", "proc_obj", ",", "context", ",", "filename", ")", "else", "context", "=", "Context", ".", "new", "(", "context", ")", "if", "context", ".", "is_a?", "(", "Hash", ")", "return", "context", ".", "instance_eval", "(", "proc_obj", ")", "end", "end" ]
helper method evaluate Proc object with contect object. context may be Binding, Hash, or Object.
[ "helper", "method", "evaluate", "Proc", "object", "with", "contect", "object", ".", "context", "may", "be", "Binding", "Hash", "or", "Object", "." ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/engine.rb#L88-L96
819
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.open
def open ppHandle = FFI::MemoryPointer.new :pointer res = Call.libusb_open(@pDev, ppHandle) LIBUSB.raise_error res, "in libusb_open" if res!=0 handle = DevHandle.new self, ppHandle.read_pointer return handle unless block_given? begin yield handle ensure handle.close end end
ruby
def open ppHandle = FFI::MemoryPointer.new :pointer res = Call.libusb_open(@pDev, ppHandle) LIBUSB.raise_error res, "in libusb_open" if res!=0 handle = DevHandle.new self, ppHandle.read_pointer return handle unless block_given? begin yield handle ensure handle.close end end
[ "def", "open", "ppHandle", "=", "FFI", "::", "MemoryPointer", ".", "new", ":pointer", "res", "=", "Call", ".", "libusb_open", "(", "@pDev", ",", "ppHandle", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_open\"", "if", "res!", "=", "0", "handle", "=", "DevHandle", ".", "new", "self", ",", "ppHandle", ".", "read_pointer", "return", "handle", "unless", "block_given?", "begin", "yield", "handle", "ensure", "handle", ".", "close", "end", "end" ]
Open the device and obtain a device handle. A handle allows you to perform I/O on the device in question. This is a non-blocking function; no requests are sent over the bus. If called with a block, the handle is passed to the block and is closed when the block has finished. You need proper device access: * Linux: read+write permissions to <tt>/dev/bus/usb/<bus>/<dev></tt> * Windows: by installing a WinUSB-driver for the device (see {file:README.rdoc#Usage_on_Windows} ) @return [DevHandle] Handle to the device.
[ "Open", "the", "device", "and", "obtain", "a", "device", "handle", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L55-L66
820
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.max_packet_size
def max_packet_size(endpoint) endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress res = Call.libusb_get_max_packet_size(@pDev, endpoint) LIBUSB.raise_error res, "in libusb_get_max_packet_size" unless res>=0 res end
ruby
def max_packet_size(endpoint) endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress res = Call.libusb_get_max_packet_size(@pDev, endpoint) LIBUSB.raise_error res, "in libusb_get_max_packet_size" unless res>=0 res end
[ "def", "max_packet_size", "(", "endpoint", ")", "endpoint", "=", "endpoint", ".", "bEndpointAddress", "if", "endpoint", ".", "respond_to?", ":bEndpointAddress", "res", "=", "Call", ".", "libusb_get_max_packet_size", "(", "@pDev", ",", "endpoint", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_get_max_packet_size\"", "unless", "res", ">=", "0", "res", "end" ]
Convenience function to retrieve the wMaxPacketSize value for a particular endpoint in the active device configuration. @param [Endpoint, Fixnum] endpoint (address of) the endpoint in question @return [Fixnum] the wMaxPacketSize value
[ "Convenience", "function", "to", "retrieve", "the", "wMaxPacketSize", "value", "for", "a", "particular", "endpoint", "in", "the", "active", "device", "configuration", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L156-L161
821
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.max_iso_packet_size
def max_iso_packet_size(endpoint) endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress res = Call.libusb_get_max_iso_packet_size(@pDev, endpoint) LIBUSB.raise_error res, "in libusb_get_max_iso_packet_size" unless res>=0 res end
ruby
def max_iso_packet_size(endpoint) endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress res = Call.libusb_get_max_iso_packet_size(@pDev, endpoint) LIBUSB.raise_error res, "in libusb_get_max_iso_packet_size" unless res>=0 res end
[ "def", "max_iso_packet_size", "(", "endpoint", ")", "endpoint", "=", "endpoint", ".", "bEndpointAddress", "if", "endpoint", ".", "respond_to?", ":bEndpointAddress", "res", "=", "Call", ".", "libusb_get_max_iso_packet_size", "(", "@pDev", ",", "endpoint", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_get_max_iso_packet_size\"", "unless", "res", ">=", "0", "res", "end" ]
Calculate the maximum packet size which a specific endpoint is capable is sending or receiving in the duration of 1 microframe. Only the active configution is examined. The calculation is based on the wMaxPacketSize field in the endpoint descriptor as described in section 9.6.6 in the USB 2.0 specifications. If acting on an isochronous or interrupt endpoint, this function will multiply the value found in bits 0:10 by the number of transactions per microframe (determined by bits 11:12). Otherwise, this function just returns the numeric value found in bits 0:10. This function is useful for setting up isochronous transfers, for example you might use the return value from this function to call IsoPacket#alloc_buffer in order to set the length field of an isochronous packet in a transfer. @param [Endpoint, Fixnum] endpoint (address of) the endpoint in question @return [Fixnum] the maximum packet size which can be sent/received on this endpoint
[ "Calculate", "the", "maximum", "packet", "size", "which", "a", "specific", "endpoint", "is", "capable", "is", "sending", "or", "receiving", "in", "the", "duration", "of", "1", "microframe", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L182-L187
822
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.config_descriptor
def config_descriptor(index) ppConfig = FFI::MemoryPointer.new :pointer res = Call.libusb_get_config_descriptor(@pDev, index, ppConfig) LIBUSB.raise_error res, "in libusb_get_config_descriptor" if res!=0 pConfig = ppConfig.read_pointer config = Configuration.new(self, pConfig) config end
ruby
def config_descriptor(index) ppConfig = FFI::MemoryPointer.new :pointer res = Call.libusb_get_config_descriptor(@pDev, index, ppConfig) LIBUSB.raise_error res, "in libusb_get_config_descriptor" if res!=0 pConfig = ppConfig.read_pointer config = Configuration.new(self, pConfig) config end
[ "def", "config_descriptor", "(", "index", ")", "ppConfig", "=", "FFI", "::", "MemoryPointer", ".", "new", ":pointer", "res", "=", "Call", ".", "libusb_get_config_descriptor", "(", "@pDev", ",", "index", ",", "ppConfig", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_get_config_descriptor\"", "if", "res!", "=", "0", "pConfig", "=", "ppConfig", ".", "read_pointer", "config", "=", "Configuration", ".", "new", "(", "self", ",", "pConfig", ")", "config", "end" ]
Obtain a config descriptor of the device. @param [Fixnum] index number of the config descriptor @return Configuration
[ "Obtain", "a", "config", "descriptor", "of", "the", "device", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L193-L200
823
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.configurations
def configurations configs = [] bNumConfigurations.times do |config_index| begin configs << config_descriptor(config_index) rescue RuntimeError # On Windows some devices don't return it's configuration. end end configs end
ruby
def configurations configs = [] bNumConfigurations.times do |config_index| begin configs << config_descriptor(config_index) rescue RuntimeError # On Windows some devices don't return it's configuration. end end configs end
[ "def", "configurations", "configs", "=", "[", "]", "bNumConfigurations", ".", "times", "do", "|", "config_index", "|", "begin", "configs", "<<", "config_descriptor", "(", "config_index", ")", "rescue", "RuntimeError", "# On Windows some devices don't return it's configuration.", "end", "end", "configs", "end" ]
Return configurations of the device. @return [Array<Configuration>]
[ "Return", "configurations", "of", "the", "device", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L337-L347
824
larskanis/libusb
lib/libusb/eventmachine.rb
LIBUSB.Context.eventmachine_register
def eventmachine_register @eventmachine_attached_fds = {} @eventmachine_timer = nil pollfds = self.pollfds if pollfds pollfds.each do |pollfd| eventmachine_add_pollfd(pollfd) end self.on_pollfd_added do |pollfd| eventmachine_add_pollfd(pollfd) end self.on_pollfd_removed do |pollfd| eventmachine_rm_pollfd(pollfd) end else # Libusb pollfd API is not available on this platform. # Use simple polling timer, instead: EventMachine.add_periodic_timer(0.01) do @eventmachine_timer = self.handle_events 0 end end end
ruby
def eventmachine_register @eventmachine_attached_fds = {} @eventmachine_timer = nil pollfds = self.pollfds if pollfds pollfds.each do |pollfd| eventmachine_add_pollfd(pollfd) end self.on_pollfd_added do |pollfd| eventmachine_add_pollfd(pollfd) end self.on_pollfd_removed do |pollfd| eventmachine_rm_pollfd(pollfd) end else # Libusb pollfd API is not available on this platform. # Use simple polling timer, instead: EventMachine.add_periodic_timer(0.01) do @eventmachine_timer = self.handle_events 0 end end end
[ "def", "eventmachine_register", "@eventmachine_attached_fds", "=", "{", "}", "@eventmachine_timer", "=", "nil", "pollfds", "=", "self", ".", "pollfds", "if", "pollfds", "pollfds", ".", "each", "do", "|", "pollfd", "|", "eventmachine_add_pollfd", "(", "pollfd", ")", "end", "self", ".", "on_pollfd_added", "do", "|", "pollfd", "|", "eventmachine_add_pollfd", "(", "pollfd", ")", "end", "self", ".", "on_pollfd_removed", "do", "|", "pollfd", "|", "eventmachine_rm_pollfd", "(", "pollfd", ")", "end", "else", "# Libusb pollfd API is not available on this platform.", "# Use simple polling timer, instead:", "EventMachine", ".", "add_periodic_timer", "(", "0.01", ")", "do", "@eventmachine_timer", "=", "self", ".", "handle_events", "0", "end", "end", "end" ]
Register libusb's file descriptors and timeouts to EventMachine. @example require 'libusb/eventmachine' context = LIBUSB::Context.new EventMachine.run do context.eventmachine_register end @see DevHandle#eventmachine_bulk_transfer DevHandle#eventmachine_control_transfer DevHandle#eventmachine_interrupt_transfer
[ "Register", "libusb", "s", "file", "descriptors", "and", "timeouts", "to", "EventMachine", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/eventmachine.rb#L34-L58
825
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.claim_interface
def claim_interface(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_claim_interface(@pHandle, interface) LIBUSB.raise_error res, "in libusb_claim_interface" if res!=0 return self unless block_given? begin yield self ensure release_interface(interface) end end
ruby
def claim_interface(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_claim_interface(@pHandle, interface) LIBUSB.raise_error res, "in libusb_claim_interface" if res!=0 return self unless block_given? begin yield self ensure release_interface(interface) end end
[ "def", "claim_interface", "(", "interface", ")", "interface", "=", "interface", ".", "bInterfaceNumber", "if", "interface", ".", "respond_to?", ":bInterfaceNumber", "res", "=", "Call", ".", "libusb_claim_interface", "(", "@pHandle", ",", "interface", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_claim_interface\"", "if", "res!", "=", "0", "return", "self", "unless", "block_given?", "begin", "yield", "self", "ensure", "release_interface", "(", "interface", ")", "end", "end" ]
Claim an interface on a given device handle. You must claim the interface you wish to use before you can perform I/O on any of its endpoints. It is legal to attempt to claim an already-claimed interface, in which case libusb just returns without doing anything. Claiming of interfaces is a purely logical operation; it does not cause any requests to be sent over the bus. Interface claiming is used to instruct the underlying operating system that your application wishes to take ownership of the interface. This is a non-blocking function. If called with a block, the device handle is passed through to the block and the interface is released when the block has finished. @param [Interface, Fixnum] interface the interface or it's bInterfaceNumber you wish to claim
[ "Claim", "an", "interface", "on", "a", "given", "device", "handle", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L76-L86
826
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.set_configuration
def set_configuration(configuration) configuration = configuration.bConfigurationValue if configuration.respond_to? :bConfigurationValue res = Call.libusb_set_configuration(@pHandle, configuration || -1) LIBUSB.raise_error res, "in libusb_set_configuration" if res!=0 end
ruby
def set_configuration(configuration) configuration = configuration.bConfigurationValue if configuration.respond_to? :bConfigurationValue res = Call.libusb_set_configuration(@pHandle, configuration || -1) LIBUSB.raise_error res, "in libusb_set_configuration" if res!=0 end
[ "def", "set_configuration", "(", "configuration", ")", "configuration", "=", "configuration", ".", "bConfigurationValue", "if", "configuration", ".", "respond_to?", ":bConfigurationValue", "res", "=", "Call", ".", "libusb_set_configuration", "(", "@pHandle", ",", "configuration", "||", "-", "1", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_set_configuration\"", "if", "res!", "=", "0", "end" ]
Set the active configuration for a device. The operating system may or may not have already set an active configuration on the device. It is up to your application to ensure the correct configuration is selected before you attempt to claim interfaces and perform other operations. If you call this function on a device already configured with the selected configuration, then this function will act as a lightweight device reset: it will issue a SET_CONFIGURATION request using the current configuration, causing most USB-related device state to be reset (altsetting reset to zero, endpoint halts cleared, toggles reset). You cannot change/reset configuration if your application has claimed interfaces - you should free them with {DevHandle#release_interface} first. You cannot change/reset configuration if other applications or drivers have claimed interfaces. A configuration value of +nil+ will put the device in unconfigured state. The USB specifications state that a configuration value of 0 does this, however buggy devices exist which actually have a configuration 0. You should always use this function rather than formulating your own SET_CONFIGURATION control request. This is because the underlying operating system needs to know when such changes happen. This is a blocking function. @param [Configuration, Fixnum] configuration the configuration or it's bConfigurationValue you wish to activate, or +nil+ if you wish to put the device in unconfigured state
[ "Set", "the", "active", "configuration", "for", "a", "device", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L133-L137
827
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.set_interface_alt_setting
def set_interface_alt_setting(setting_or_interface_number, alternate_setting=nil) alternate_setting ||= setting_or_interface_number.bAlternateSetting if setting_or_interface_number.respond_to? :bAlternateSetting setting_or_interface_number = setting_or_interface_number.bInterfaceNumber if setting_or_interface_number.respond_to? :bInterfaceNumber res = Call.libusb_set_interface_alt_setting(@pHandle, setting_or_interface_number, alternate_setting) LIBUSB.raise_error res, "in libusb_set_interface_alt_setting" if res!=0 end
ruby
def set_interface_alt_setting(setting_or_interface_number, alternate_setting=nil) alternate_setting ||= setting_or_interface_number.bAlternateSetting if setting_or_interface_number.respond_to? :bAlternateSetting setting_or_interface_number = setting_or_interface_number.bInterfaceNumber if setting_or_interface_number.respond_to? :bInterfaceNumber res = Call.libusb_set_interface_alt_setting(@pHandle, setting_or_interface_number, alternate_setting) LIBUSB.raise_error res, "in libusb_set_interface_alt_setting" if res!=0 end
[ "def", "set_interface_alt_setting", "(", "setting_or_interface_number", ",", "alternate_setting", "=", "nil", ")", "alternate_setting", "||=", "setting_or_interface_number", ".", "bAlternateSetting", "if", "setting_or_interface_number", ".", "respond_to?", ":bAlternateSetting", "setting_or_interface_number", "=", "setting_or_interface_number", ".", "bInterfaceNumber", "if", "setting_or_interface_number", ".", "respond_to?", ":bInterfaceNumber", "res", "=", "Call", ".", "libusb_set_interface_alt_setting", "(", "@pHandle", ",", "setting_or_interface_number", ",", "alternate_setting", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_set_interface_alt_setting\"", "if", "res!", "=", "0", "end" ]
Activate an alternate setting for an interface. The interface must have been previously claimed with {DevHandle#claim_interface}. You should always use this function rather than formulating your own SET_INTERFACE control request. This is because the underlying operating system needs to know when such changes happen. This is a blocking function. @param [Setting, Fixnum] setting_or_interface_number the alternate setting to activate or the bInterfaceNumber of the previously-claimed interface @param [Fixnum, nil] alternate_setting the bAlternateSetting of the alternate setting to activate (only if first param is a Fixnum)
[ "Activate", "an", "alternate", "setting", "for", "an", "interface", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L154-L159
828
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.kernel_driver_active?
def kernel_driver_active?(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_kernel_driver_active(@pHandle, interface) LIBUSB.raise_error res, "in libusb_kernel_driver_active" unless res>=0 return res==1 end
ruby
def kernel_driver_active?(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_kernel_driver_active(@pHandle, interface) LIBUSB.raise_error res, "in libusb_kernel_driver_active" unless res>=0 return res==1 end
[ "def", "kernel_driver_active?", "(", "interface", ")", "interface", "=", "interface", ".", "bInterfaceNumber", "if", "interface", ".", "respond_to?", ":bInterfaceNumber", "res", "=", "Call", ".", "libusb_kernel_driver_active", "(", "@pHandle", ",", "interface", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_kernel_driver_active\"", "unless", "res", ">=", "0", "return", "res", "==", "1", "end" ]
Determine if a kernel driver is active on an interface. If a kernel driver is active, you cannot claim the interface, and libusb will be unable to perform I/O. @param [Interface, Fixnum] interface the interface to check or it's bInterfaceNumber @return [Boolean]
[ "Determine", "if", "a", "kernel", "driver", "is", "active", "on", "an", "interface", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L257-L262
829
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.detach_kernel_driver
def detach_kernel_driver(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_detach_kernel_driver(@pHandle, interface) LIBUSB.raise_error res, "in libusb_detach_kernel_driver" if res!=0 end
ruby
def detach_kernel_driver(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_detach_kernel_driver(@pHandle, interface) LIBUSB.raise_error res, "in libusb_detach_kernel_driver" if res!=0 end
[ "def", "detach_kernel_driver", "(", "interface", ")", "interface", "=", "interface", ".", "bInterfaceNumber", "if", "interface", ".", "respond_to?", ":bInterfaceNumber", "res", "=", "Call", ".", "libusb_detach_kernel_driver", "(", "@pHandle", ",", "interface", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_detach_kernel_driver\"", "if", "res!", "=", "0", "end" ]
Detach a kernel driver from an interface. If successful, you will then be able to claim the interface and perform I/O. @param [Interface, Fixnum] interface the interface to detach the driver from or it's bInterfaceNumber
[ "Detach", "a", "kernel", "driver", "from", "an", "interface", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L270-L274
830
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.bulk_transfer
def bulk_transfer(args={}, &block) timeout = args.delete(:timeout) || 1000 endpoint = args.delete(:endpoint) || raise(ArgumentError, "no endpoint given") endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress if endpoint&ENDPOINT_IN != 0 dataIn = args.delete(:dataIn) || raise(ArgumentError, "no :dataIn given for bulk read") else dataOut = args.delete(:dataOut) || raise(ArgumentError, "no :dataOut given for bulk write") end raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? # reuse transfer struct to speed up transfer @bulk_transfer ||= BulkTransfer.new dev_handle: self, allow_device_memory: true tr = @bulk_transfer tr.endpoint = endpoint tr.timeout = timeout if dataOut tr.buffer = dataOut else tr.alloc_buffer(dataIn) end submit_transfer(tr, dataIn, 0, &block) end
ruby
def bulk_transfer(args={}, &block) timeout = args.delete(:timeout) || 1000 endpoint = args.delete(:endpoint) || raise(ArgumentError, "no endpoint given") endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress if endpoint&ENDPOINT_IN != 0 dataIn = args.delete(:dataIn) || raise(ArgumentError, "no :dataIn given for bulk read") else dataOut = args.delete(:dataOut) || raise(ArgumentError, "no :dataOut given for bulk write") end raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? # reuse transfer struct to speed up transfer @bulk_transfer ||= BulkTransfer.new dev_handle: self, allow_device_memory: true tr = @bulk_transfer tr.endpoint = endpoint tr.timeout = timeout if dataOut tr.buffer = dataOut else tr.alloc_buffer(dataIn) end submit_transfer(tr, dataIn, 0, &block) end
[ "def", "bulk_transfer", "(", "args", "=", "{", "}", ",", "&", "block", ")", "timeout", "=", "args", ".", "delete", "(", ":timeout", ")", "||", "1000", "endpoint", "=", "args", ".", "delete", "(", ":endpoint", ")", "||", "raise", "(", "ArgumentError", ",", "\"no endpoint given\"", ")", "endpoint", "=", "endpoint", ".", "bEndpointAddress", "if", "endpoint", ".", "respond_to?", ":bEndpointAddress", "if", "endpoint", "ENDPOINT_IN", "!=", "0", "dataIn", "=", "args", ".", "delete", "(", ":dataIn", ")", "||", "raise", "(", "ArgumentError", ",", "\"no :dataIn given for bulk read\"", ")", "else", "dataOut", "=", "args", ".", "delete", "(", ":dataOut", ")", "||", "raise", "(", "ArgumentError", ",", "\"no :dataOut given for bulk write\"", ")", "end", "raise", "ArgumentError", ",", "\"invalid params #{args.inspect}\"", "unless", "args", ".", "empty?", "# reuse transfer struct to speed up transfer", "@bulk_transfer", "||=", "BulkTransfer", ".", "new", "dev_handle", ":", "self", ",", "allow_device_memory", ":", "true", "tr", "=", "@bulk_transfer", "tr", ".", "endpoint", "=", "endpoint", "tr", ".", "timeout", "=", "timeout", "if", "dataOut", "tr", ".", "buffer", "=", "dataOut", "else", "tr", ".", "alloc_buffer", "(", "dataIn", ")", "end", "submit_transfer", "(", "tr", ",", "dataIn", ",", "0", ",", "block", ")", "end" ]
Perform a USB bulk transfer. When called without a block, the transfer is done synchronously - so all events are handled internally and the sent/received data will be returned after completion or an exception will be raised. When called with a block, the method returns immediately after submitting the transfer. You then have to ensure, that {Context#handle_events} is called properly. As soon as the transfer is completed, the block is called with the sent/received data in case of success or the exception instance in case of failure. The direction of the transfer is inferred from the direction bits of the endpoint address. For bulk reads, the +:dataIn+ param indicates the maximum length of data you are expecting to receive. If less data arrives than expected, this function will return that data. You should check the returned number of bytes for bulk writes. Not all of the data may have been written. Also check {Error#transferred} when dealing with a timeout exception. libusb may have to split your transfer into a number of chunks to satisfy underlying O/S requirements, meaning that the timeout may expire after the first few chunks have completed. libusb is careful not to lose any data that may have been transferred; do not assume that timeout conditions indicate a complete lack of I/O. @param [Hash] args @option args [Endpoint, Fixnum] :endpoint the (address of a) valid endpoint to communicate with @option args [String] :dataOut the data to send with an outgoing transfer @option args [Fixnum] :dataIn the number of bytes expected to receive with an ingoing transfer @option args [Fixnum] :timeout timeout (in millseconds) that this function should wait before giving up due to no response being received. For an unlimited timeout, use value 0. Defaults to 1000 ms. @return [Fixnum] Number of bytes sent for an outgoing transfer @return [String] Received data for an ingoing transfer @return [self] When called with a block @yieldparam [String, Integer, LIBUSB::Error] result result of the transfer is yielded to the block, when the asynchronous transfer has finished @raise [ArgumentError, LIBUSB::Error] in case of failure
[ "Perform", "a", "USB", "bulk", "transfer", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L375-L398
831
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.control_transfer
def control_transfer(args={}, &block) bmRequestType = args.delete(:bmRequestType) || raise(ArgumentError, "param :bmRequestType not given") bRequest = args.delete(:bRequest) || raise(ArgumentError, "param :bRequest not given") wValue = args.delete(:wValue) || raise(ArgumentError, "param :wValue not given") wIndex = args.delete(:wIndex) || raise(ArgumentError, "param :wIndex not given") timeout = args.delete(:timeout) || 1000 if bmRequestType&ENDPOINT_IN != 0 dataIn = args.delete(:dataIn) || 0 dataOut = '' else dataOut = args.delete(:dataOut) || '' end raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? # reuse transfer struct to speed up transfer @control_transfer ||= ControlTransfer.new dev_handle: self, allow_device_memory: true tr = @control_transfer tr.timeout = timeout if dataIn setup_data = [bmRequestType, bRequest, wValue, wIndex, dataIn].pack('CCvvv') tr.alloc_buffer( dataIn + CONTROL_SETUP_SIZE, setup_data ) else tr.buffer = [bmRequestType, bRequest, wValue, wIndex, dataOut.bytesize, dataOut].pack('CCvvva*') end submit_transfer(tr, dataIn, CONTROL_SETUP_SIZE, &block) end
ruby
def control_transfer(args={}, &block) bmRequestType = args.delete(:bmRequestType) || raise(ArgumentError, "param :bmRequestType not given") bRequest = args.delete(:bRequest) || raise(ArgumentError, "param :bRequest not given") wValue = args.delete(:wValue) || raise(ArgumentError, "param :wValue not given") wIndex = args.delete(:wIndex) || raise(ArgumentError, "param :wIndex not given") timeout = args.delete(:timeout) || 1000 if bmRequestType&ENDPOINT_IN != 0 dataIn = args.delete(:dataIn) || 0 dataOut = '' else dataOut = args.delete(:dataOut) || '' end raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? # reuse transfer struct to speed up transfer @control_transfer ||= ControlTransfer.new dev_handle: self, allow_device_memory: true tr = @control_transfer tr.timeout = timeout if dataIn setup_data = [bmRequestType, bRequest, wValue, wIndex, dataIn].pack('CCvvv') tr.alloc_buffer( dataIn + CONTROL_SETUP_SIZE, setup_data ) else tr.buffer = [bmRequestType, bRequest, wValue, wIndex, dataOut.bytesize, dataOut].pack('CCvvva*') end submit_transfer(tr, dataIn, CONTROL_SETUP_SIZE, &block) end
[ "def", "control_transfer", "(", "args", "=", "{", "}", ",", "&", "block", ")", "bmRequestType", "=", "args", ".", "delete", "(", ":bmRequestType", ")", "||", "raise", "(", "ArgumentError", ",", "\"param :bmRequestType not given\"", ")", "bRequest", "=", "args", ".", "delete", "(", ":bRequest", ")", "||", "raise", "(", "ArgumentError", ",", "\"param :bRequest not given\"", ")", "wValue", "=", "args", ".", "delete", "(", ":wValue", ")", "||", "raise", "(", "ArgumentError", ",", "\"param :wValue not given\"", ")", "wIndex", "=", "args", ".", "delete", "(", ":wIndex", ")", "||", "raise", "(", "ArgumentError", ",", "\"param :wIndex not given\"", ")", "timeout", "=", "args", ".", "delete", "(", ":timeout", ")", "||", "1000", "if", "bmRequestType", "ENDPOINT_IN", "!=", "0", "dataIn", "=", "args", ".", "delete", "(", ":dataIn", ")", "||", "0", "dataOut", "=", "''", "else", "dataOut", "=", "args", ".", "delete", "(", ":dataOut", ")", "||", "''", "end", "raise", "ArgumentError", ",", "\"invalid params #{args.inspect}\"", "unless", "args", ".", "empty?", "# reuse transfer struct to speed up transfer", "@control_transfer", "||=", "ControlTransfer", ".", "new", "dev_handle", ":", "self", ",", "allow_device_memory", ":", "true", "tr", "=", "@control_transfer", "tr", ".", "timeout", "=", "timeout", "if", "dataIn", "setup_data", "=", "[", "bmRequestType", ",", "bRequest", ",", "wValue", ",", "wIndex", ",", "dataIn", "]", ".", "pack", "(", "'CCvvv'", ")", "tr", ".", "alloc_buffer", "(", "dataIn", "+", "CONTROL_SETUP_SIZE", ",", "setup_data", ")", "else", "tr", ".", "buffer", "=", "[", "bmRequestType", ",", "bRequest", ",", "wValue", ",", "wIndex", ",", "dataOut", ".", "bytesize", ",", "dataOut", "]", ".", "pack", "(", "'CCvvva*'", ")", "end", "submit_transfer", "(", "tr", ",", "dataIn", ",", "CONTROL_SETUP_SIZE", ",", "block", ")", "end" ]
Perform a USB control transfer. When called without a block, the transfer is done synchronously - so all events are handled internally and the sent/received data will be returned after completion or an exception will be raised. When called with a block, the method returns immediately after submitting the transfer. You then have to ensure, that {Context#handle_events} is called properly. As soon as the transfer is completed, the block is called with the sent/received data in case of success or the exception instance in case of failure. The direction of the transfer is inferred from the +:bmRequestType+ field of the setup packet. @param [Hash] args @option args [Fixnum] :bmRequestType the request type field for the setup packet @option args [Fixnum] :bRequest the request field for the setup packet @option args [Fixnum] :wValue the value field for the setup packet @option args [Fixnum] :wIndex the index field for the setup packet @option args [String] :dataOut the data to send with an outgoing transfer, it is appended to the setup packet @option args [Fixnum] :dataIn the number of bytes expected to receive with an ingoing transfer (excluding setup packet) @option args [Fixnum] :timeout timeout (in millseconds) that this function should wait before giving up due to no response being received. For an unlimited timeout, use value 0. Defaults to 1000 ms. @return [Fixnum] Number of bytes sent (excluding setup packet) for outgoing transfer @return [String] Received data (without setup packet) for ingoing transfer @return [self] When called with a block @yieldparam [String, Integer, LIBUSB::Error] result result of the transfer is yielded to the block, when the asynchronous transfer has finished @raise [ArgumentError, LIBUSB::Error] in case of failure
[ "Perform", "a", "USB", "control", "transfer", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L500-L526
832
larskanis/libusb
lib/libusb/bos.rb
LIBUSB.Bos.device_capabilities
def device_capabilities pp_ext = FFI::MemoryPointer.new :pointer caps = [] # Capabilities are appended to the bos header ptr = pointer + offset_of(:dev_capability) bNumDeviceCaps.times do cap = DeviceCapability.new self, ptr.read_pointer case cap.bDevCapabilityType when LIBUSB::BT_WIRELESS_USB_DEVICE_CAPABILITY # no struct defined in libusb -> use generic DeviceCapability when LIBUSB::BT_USB_2_0_EXTENSION res = Call.libusb_get_usb_2_0_extension_descriptor(@ctx, cap.pointer, pp_ext) cap = Usb20Extension.new(pp_ext.read_pointer) if res==0 when LIBUSB::BT_SS_USB_DEVICE_CAPABILITY res = Call.libusb_get_ss_usb_device_capability_descriptor(@ctx, cap.pointer, pp_ext) cap = SsUsbDeviceCapability.new(pp_ext.read_pointer) if res==0 when LIBUSB::BT_CONTAINER_ID res = Call.libusb_get_container_id_descriptor(@ctx, cap.pointer, pp_ext) cap = ContainerId.new(pp_ext.read_pointer) if res==0 else # unknown capability -> use generic DeviceCapability end ptr += FFI.type_size(:pointer) caps << cap end caps end
ruby
def device_capabilities pp_ext = FFI::MemoryPointer.new :pointer caps = [] # Capabilities are appended to the bos header ptr = pointer + offset_of(:dev_capability) bNumDeviceCaps.times do cap = DeviceCapability.new self, ptr.read_pointer case cap.bDevCapabilityType when LIBUSB::BT_WIRELESS_USB_DEVICE_CAPABILITY # no struct defined in libusb -> use generic DeviceCapability when LIBUSB::BT_USB_2_0_EXTENSION res = Call.libusb_get_usb_2_0_extension_descriptor(@ctx, cap.pointer, pp_ext) cap = Usb20Extension.new(pp_ext.read_pointer) if res==0 when LIBUSB::BT_SS_USB_DEVICE_CAPABILITY res = Call.libusb_get_ss_usb_device_capability_descriptor(@ctx, cap.pointer, pp_ext) cap = SsUsbDeviceCapability.new(pp_ext.read_pointer) if res==0 when LIBUSB::BT_CONTAINER_ID res = Call.libusb_get_container_id_descriptor(@ctx, cap.pointer, pp_ext) cap = ContainerId.new(pp_ext.read_pointer) if res==0 else # unknown capability -> use generic DeviceCapability end ptr += FFI.type_size(:pointer) caps << cap end caps end
[ "def", "device_capabilities", "pp_ext", "=", "FFI", "::", "MemoryPointer", ".", "new", ":pointer", "caps", "=", "[", "]", "# Capabilities are appended to the bos header", "ptr", "=", "pointer", "+", "offset_of", "(", ":dev_capability", ")", "bNumDeviceCaps", ".", "times", "do", "cap", "=", "DeviceCapability", ".", "new", "self", ",", "ptr", ".", "read_pointer", "case", "cap", ".", "bDevCapabilityType", "when", "LIBUSB", "::", "BT_WIRELESS_USB_DEVICE_CAPABILITY", "# no struct defined in libusb -> use generic DeviceCapability", "when", "LIBUSB", "::", "BT_USB_2_0_EXTENSION", "res", "=", "Call", ".", "libusb_get_usb_2_0_extension_descriptor", "(", "@ctx", ",", "cap", ".", "pointer", ",", "pp_ext", ")", "cap", "=", "Usb20Extension", ".", "new", "(", "pp_ext", ".", "read_pointer", ")", "if", "res", "==", "0", "when", "LIBUSB", "::", "BT_SS_USB_DEVICE_CAPABILITY", "res", "=", "Call", ".", "libusb_get_ss_usb_device_capability_descriptor", "(", "@ctx", ",", "cap", ".", "pointer", ",", "pp_ext", ")", "cap", "=", "SsUsbDeviceCapability", ".", "new", "(", "pp_ext", ".", "read_pointer", ")", "if", "res", "==", "0", "when", "LIBUSB", "::", "BT_CONTAINER_ID", "res", "=", "Call", ".", "libusb_get_container_id_descriptor", "(", "@ctx", ",", "cap", ".", "pointer", ",", "pp_ext", ")", "cap", "=", "ContainerId", ".", "new", "(", "pp_ext", ".", "read_pointer", ")", "if", "res", "==", "0", "else", "# unknown capability -> use generic DeviceCapability", "end", "ptr", "+=", "FFI", ".", "type_size", "(", ":pointer", ")", "caps", "<<", "cap", "end", "caps", "end" ]
bNumDeviceCap Device Capability Descriptors @return [Array<Bos::DeviceCapability, Bos::Usb20Extension, Bos::SsUsbDeviceCapability, Bos::ContainerId>]
[ "bNumDeviceCap", "Device", "Capability", "Descriptors" ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/bos.rb#L256-L282
833
larskanis/libusb
lib/libusb/transfer.rb
LIBUSB.Transfer.submit!
def submit!(&block) self.callback = block if block_given? # puts "submit transfer #{@transfer.inspect} buffer: #{@transfer[:buffer].inspect} length: #{@transfer[:length].inspect} status: #{@transfer[:status].inspect} callback: #{@transfer[:callback].inspect} dev_handle: #{@transfer[:dev_handle].inspect}" res = Call.libusb_submit_transfer( @transfer ) LIBUSB.raise_error res, "in libusb_submit_transfer" if res!=0 end
ruby
def submit!(&block) self.callback = block if block_given? # puts "submit transfer #{@transfer.inspect} buffer: #{@transfer[:buffer].inspect} length: #{@transfer[:length].inspect} status: #{@transfer[:status].inspect} callback: #{@transfer[:callback].inspect} dev_handle: #{@transfer[:dev_handle].inspect}" res = Call.libusb_submit_transfer( @transfer ) LIBUSB.raise_error res, "in libusb_submit_transfer" if res!=0 end
[ "def", "submit!", "(", "&", "block", ")", "self", ".", "callback", "=", "block", "if", "block_given?", "# puts \"submit transfer #{@transfer.inspect} buffer: #{@transfer[:buffer].inspect} length: #{@transfer[:length].inspect} status: #{@transfer[:status].inspect} callback: #{@transfer[:callback].inspect} dev_handle: #{@transfer[:dev_handle].inspect}\"", "res", "=", "Call", ".", "libusb_submit_transfer", "(", "@transfer", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_submit_transfer\"", "if", "res!", "=", "0", "end" ]
Submit a transfer. This function will fire off the USB transfer and then return immediately. This method can be called with block. It is called when the transfer completes, fails, or is cancelled.
[ "Submit", "a", "transfer", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/transfer.rb#L211-L218
834
larskanis/libusb
lib/libusb/transfer.rb
LIBUSB.Transfer.submit_and_wait
def submit_and_wait raise ArgumentError, "#{self.class}#dev_handle not set" unless @dev_handle @completion_flag.completed = false submit! do |tr2| @completion_flag.completed = true end until @completion_flag.completed? begin @dev_handle.device.context.handle_events nil, @completion_flag rescue ERROR_INTERRUPTED next rescue LIBUSB::Error cancel! until @completion_flag.completed? @dev_handle.device.context.handle_events nil, @completion_flag end raise end end end
ruby
def submit_and_wait raise ArgumentError, "#{self.class}#dev_handle not set" unless @dev_handle @completion_flag.completed = false submit! do |tr2| @completion_flag.completed = true end until @completion_flag.completed? begin @dev_handle.device.context.handle_events nil, @completion_flag rescue ERROR_INTERRUPTED next rescue LIBUSB::Error cancel! until @completion_flag.completed? @dev_handle.device.context.handle_events nil, @completion_flag end raise end end end
[ "def", "submit_and_wait", "raise", "ArgumentError", ",", "\"#{self.class}#dev_handle not set\"", "unless", "@dev_handle", "@completion_flag", ".", "completed", "=", "false", "submit!", "do", "|", "tr2", "|", "@completion_flag", ".", "completed", "=", "true", "end", "until", "@completion_flag", ".", "completed?", "begin", "@dev_handle", ".", "device", ".", "context", ".", "handle_events", "nil", ",", "@completion_flag", "rescue", "ERROR_INTERRUPTED", "next", "rescue", "LIBUSB", "::", "Error", "cancel!", "until", "@completion_flag", ".", "completed?", "@dev_handle", ".", "device", ".", "context", ".", "handle_events", "nil", ",", "@completion_flag", "end", "raise", "end", "end", "end" ]
Submit the transfer and wait until the transfer completes or fails. Inspect {#status} to check for transfer errors.
[ "Submit", "the", "transfer", "and", "wait", "until", "the", "transfer", "completes", "or", "fails", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/transfer.rb#L242-L263
835
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.handle_events
def handle_events(timeout=nil, completion_flag=nil) if completion_flag && !completion_flag.is_a?(Context::CompletionFlag) raise ArgumentError, "completion_flag is not a CompletionFlag" end if timeout timeval = Call::Timeval.new timeval.in_ms = timeout res = if Call.respond_to?(:libusb_handle_events_timeout_completed) Call.libusb_handle_events_timeout_completed(@ctx, timeval, completion_flag) else Call.libusb_handle_events_timeout(@ctx, timeval) end else res = if Call.respond_to?(:libusb_handle_events_completed) Call.libusb_handle_events_completed(@ctx, completion_flag ) else Call.libusb_handle_events(@ctx) end end LIBUSB.raise_error res, "in libusb_handle_events" if res<0 end
ruby
def handle_events(timeout=nil, completion_flag=nil) if completion_flag && !completion_flag.is_a?(Context::CompletionFlag) raise ArgumentError, "completion_flag is not a CompletionFlag" end if timeout timeval = Call::Timeval.new timeval.in_ms = timeout res = if Call.respond_to?(:libusb_handle_events_timeout_completed) Call.libusb_handle_events_timeout_completed(@ctx, timeval, completion_flag) else Call.libusb_handle_events_timeout(@ctx, timeval) end else res = if Call.respond_to?(:libusb_handle_events_completed) Call.libusb_handle_events_completed(@ctx, completion_flag ) else Call.libusb_handle_events(@ctx) end end LIBUSB.raise_error res, "in libusb_handle_events" if res<0 end
[ "def", "handle_events", "(", "timeout", "=", "nil", ",", "completion_flag", "=", "nil", ")", "if", "completion_flag", "&&", "!", "completion_flag", ".", "is_a?", "(", "Context", "::", "CompletionFlag", ")", "raise", "ArgumentError", ",", "\"completion_flag is not a CompletionFlag\"", "end", "if", "timeout", "timeval", "=", "Call", "::", "Timeval", ".", "new", "timeval", ".", "in_ms", "=", "timeout", "res", "=", "if", "Call", ".", "respond_to?", "(", ":libusb_handle_events_timeout_completed", ")", "Call", ".", "libusb_handle_events_timeout_completed", "(", "@ctx", ",", "timeval", ",", "completion_flag", ")", "else", "Call", ".", "libusb_handle_events_timeout", "(", "@ctx", ",", "timeval", ")", "end", "else", "res", "=", "if", "Call", ".", "respond_to?", "(", ":libusb_handle_events_completed", ")", "Call", ".", "libusb_handle_events_completed", "(", "@ctx", ",", "completion_flag", ")", "else", "Call", ".", "libusb_handle_events", "(", "@ctx", ")", "end", "end", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_handle_events\"", "if", "res", "<", "0", "end" ]
Handle any pending events in blocking mode. This method must be called when libusb is running asynchronous transfers. This gives libusb the opportunity to reap pending transfers, invoke callbacks, etc. If a zero timeout is passed, this function will handle any already-pending events and then immediately return in non-blocking style. If a non-zero timeout is passed and no events are currently pending, this method will block waiting for events to handle up until the specified timeout. If an event arrives or a signal is raised, this method will return early. If the parameter completion_flag is used, then after obtaining the event handling lock this function will return immediately if the flag is set to completed. This allows for race free waiting for the completion of a specific transfer. See source of {Transfer#submit_and_wait} for a use case of completion_flag. @param [Integer, nil] timeout the maximum time (in millseconds) to block waiting for events, or 0 for non-blocking mode @param [Context::CompletionFlag, nil] completion_flag CompletionFlag to check @see interrupt_event_handler
[ "Handle", "any", "pending", "events", "in", "blocking", "mode", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L195-L215
836
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.devices
def devices(filter_hash={}) device_list.select do |dev| ( !filter_hash[:bClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceClass).&([filter_hash[:bClass]].flatten).any? : [filter_hash[:bClass]].flatten.include?(dev.bDeviceClass))) && ( !filter_hash[:bSubClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceSubClass).&([filter_hash[:bSubClass]].flatten).any? : [filter_hash[:bSubClass]].flatten.include?(dev.bDeviceSubClass))) && ( !filter_hash[:bProtocol] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceProtocol).&([filter_hash[:bProtocol]].flatten).any? : [filter_hash[:bProtocol]].flatten.include?(dev.bDeviceProtocol))) && ( !filter_hash[:bMaxPacketSize0] || [filter_hash[:bMaxPacketSize0]].flatten.include?(dev.bMaxPacketSize0) ) && ( !filter_hash[:idVendor] || [filter_hash[:idVendor]].flatten.include?(dev.idVendor) ) && ( !filter_hash[:idProduct] || [filter_hash[:idProduct]].flatten.include?(dev.idProduct) ) && ( !filter_hash[:bcdUSB] || [filter_hash[:bcdUSB]].flatten.include?(dev.bcdUSB) ) && ( !filter_hash[:bcdDevice] || [filter_hash[:bcdDevice]].flatten.include?(dev.bcdDevice) ) end end
ruby
def devices(filter_hash={}) device_list.select do |dev| ( !filter_hash[:bClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceClass).&([filter_hash[:bClass]].flatten).any? : [filter_hash[:bClass]].flatten.include?(dev.bDeviceClass))) && ( !filter_hash[:bSubClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceSubClass).&([filter_hash[:bSubClass]].flatten).any? : [filter_hash[:bSubClass]].flatten.include?(dev.bDeviceSubClass))) && ( !filter_hash[:bProtocol] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceProtocol).&([filter_hash[:bProtocol]].flatten).any? : [filter_hash[:bProtocol]].flatten.include?(dev.bDeviceProtocol))) && ( !filter_hash[:bMaxPacketSize0] || [filter_hash[:bMaxPacketSize0]].flatten.include?(dev.bMaxPacketSize0) ) && ( !filter_hash[:idVendor] || [filter_hash[:idVendor]].flatten.include?(dev.idVendor) ) && ( !filter_hash[:idProduct] || [filter_hash[:idProduct]].flatten.include?(dev.idProduct) ) && ( !filter_hash[:bcdUSB] || [filter_hash[:bcdUSB]].flatten.include?(dev.bcdUSB) ) && ( !filter_hash[:bcdDevice] || [filter_hash[:bcdDevice]].flatten.include?(dev.bcdDevice) ) end end
[ "def", "devices", "(", "filter_hash", "=", "{", "}", ")", "device_list", ".", "select", "do", "|", "dev", "|", "(", "!", "filter_hash", "[", ":bClass", "]", "||", "(", "dev", ".", "bDeviceClass", "==", "CLASS_PER_INTERFACE", "?", "dev", ".", "settings", ".", "map", "(", ":bInterfaceClass", ")", ".", "&", "(", "[", "filter_hash", "[", ":bClass", "]", "]", ".", "flatten", ")", ".", "any?", ":", "[", "filter_hash", "[", ":bClass", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bDeviceClass", ")", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bSubClass", "]", "||", "(", "dev", ".", "bDeviceClass", "==", "CLASS_PER_INTERFACE", "?", "dev", ".", "settings", ".", "map", "(", ":bInterfaceSubClass", ")", ".", "&", "(", "[", "filter_hash", "[", ":bSubClass", "]", "]", ".", "flatten", ")", ".", "any?", ":", "[", "filter_hash", "[", ":bSubClass", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bDeviceSubClass", ")", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bProtocol", "]", "||", "(", "dev", ".", "bDeviceClass", "==", "CLASS_PER_INTERFACE", "?", "dev", ".", "settings", ".", "map", "(", ":bInterfaceProtocol", ")", ".", "&", "(", "[", "filter_hash", "[", ":bProtocol", "]", "]", ".", "flatten", ")", ".", "any?", ":", "[", "filter_hash", "[", ":bProtocol", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bDeviceProtocol", ")", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bMaxPacketSize0", "]", "||", "[", "filter_hash", "[", ":bMaxPacketSize0", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bMaxPacketSize0", ")", ")", "&&", "(", "!", "filter_hash", "[", ":idVendor", "]", "||", "[", "filter_hash", "[", ":idVendor", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "idVendor", ")", ")", "&&", "(", "!", "filter_hash", "[", ":idProduct", "]", "||", "[", "filter_hash", "[", ":idProduct", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "idProduct", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bcdUSB", "]", "||", "[", "filter_hash", "[", ":bcdUSB", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bcdUSB", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bcdDevice", "]", "||", "[", "filter_hash", "[", ":bcdDevice", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bcdDevice", ")", ")", "end", "end" ]
Obtain a list of devices currently attached to the USB system, optionally matching certain criteria. @param [Hash] filter_hash A number of criteria can be defined in key-value pairs. Only devices that equal all given criterions will be returned. If a criterion is not specified or its value is +nil+, any device will match that criterion. The following criteria can be filtered: * <tt>:idVendor</tt>, <tt>:idProduct</tt> (+FixNum+) for matching vendor/product ID, * <tt>:bClass</tt>, <tt>:bSubClass</tt>, <tt>:bProtocol</tt> (+FixNum+) for the device type - Devices using CLASS_PER_INTERFACE will match, if any of the interfaces match. * <tt>:bcdUSB</tt>, <tt>:bcdDevice</tt>, <tt>:bMaxPacketSize0</tt> (+FixNum+) for the USB and device release numbers. Criteria can also specified as Array of several alternative values. @example # Return all devices of vendor 0x0ab1 where idProduct is 3 or 4: context.device idVendor: 0x0ab1, idProduct: [0x0003, 0x0004] @return [Array<LIBUSB::Device>]
[ "Obtain", "a", "list", "of", "devices", "currently", "attached", "to", "the", "USB", "system", "optionally", "matching", "certain", "criteria", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L248-L265
837
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.pollfds
def pollfds ppPollfds = Call.libusb_get_pollfds(@ctx) return nil if ppPollfds.null? offs = 0 pollfds = [] while !(pPollfd=ppPollfds.get_pointer(offs)).null? pollfd = Call::Pollfd.new pPollfd pollfds << Pollfd.new(pollfd[:fd], pollfd[:events]) offs += FFI.type_size :pointer end if Call.respond_to?(:libusb_free_pollfds) Call.libusb_free_pollfds(ppPollfds) else Stdio.free(ppPollfds) end pollfds end
ruby
def pollfds ppPollfds = Call.libusb_get_pollfds(@ctx) return nil if ppPollfds.null? offs = 0 pollfds = [] while !(pPollfd=ppPollfds.get_pointer(offs)).null? pollfd = Call::Pollfd.new pPollfd pollfds << Pollfd.new(pollfd[:fd], pollfd[:events]) offs += FFI.type_size :pointer end if Call.respond_to?(:libusb_free_pollfds) Call.libusb_free_pollfds(ppPollfds) else Stdio.free(ppPollfds) end pollfds end
[ "def", "pollfds", "ppPollfds", "=", "Call", ".", "libusb_get_pollfds", "(", "@ctx", ")", "return", "nil", "if", "ppPollfds", ".", "null?", "offs", "=", "0", "pollfds", "=", "[", "]", "while", "!", "(", "pPollfd", "=", "ppPollfds", ".", "get_pointer", "(", "offs", ")", ")", ".", "null?", "pollfd", "=", "Call", "::", "Pollfd", ".", "new", "pPollfd", "pollfds", "<<", "Pollfd", ".", "new", "(", "pollfd", "[", ":fd", "]", ",", "pollfd", "[", ":events", "]", ")", "offs", "+=", "FFI", ".", "type_size", ":pointer", "end", "if", "Call", ".", "respond_to?", "(", ":libusb_free_pollfds", ")", "Call", ".", "libusb_free_pollfds", "(", "ppPollfds", ")", "else", "Stdio", ".", "free", "(", "ppPollfds", ")", "end", "pollfds", "end" ]
Retrieve a list of file descriptors that should be polled by your main loop as libusb event sources. As file descriptors are a Unix-specific concept, this function is not available on Windows and will always return +nil+. @return [Array<Pollfd>] list of Pollfd objects, +nil+ on error, +nil+ on platforms where the functionality is not available
[ "Retrieve", "a", "list", "of", "file", "descriptors", "that", "should", "be", "polled", "by", "your", "main", "loop", "as", "libusb", "event", "sources", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L277-L293
838
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.next_timeout
def next_timeout timeval = Call::Timeval.new res = Call.libusb_get_next_timeout @ctx, timeval LIBUSB.raise_error res, "in libusb_get_next_timeout" if res<0 res == 1 ? timeval.in_s : nil end
ruby
def next_timeout timeval = Call::Timeval.new res = Call.libusb_get_next_timeout @ctx, timeval LIBUSB.raise_error res, "in libusb_get_next_timeout" if res<0 res == 1 ? timeval.in_s : nil end
[ "def", "next_timeout", "timeval", "=", "Call", "::", "Timeval", ".", "new", "res", "=", "Call", ".", "libusb_get_next_timeout", "@ctx", ",", "timeval", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_get_next_timeout\"", "if", "res", "<", "0", "res", "==", "1", "?", "timeval", ".", "in_s", ":", "nil", "end" ]
Determine the next internal timeout that libusb needs to handle. You only need to use this function if you are calling poll() or select() or similar on libusb's file descriptors yourself - you do not need to use it if you are calling {#handle_events} directly. You should call this function in your main loop in order to determine how long to wait for select() or poll() to return results. libusb needs to be called into at this timeout, so you should use it as an upper bound on your select() or poll() call. When the timeout has expired, call into {#handle_events} (perhaps in non-blocking mode) so that libusb can handle the timeout. This function may return zero. If this is the case, it indicates that libusb has a timeout that has already expired so you should call {#handle_events} immediately. A return code of +nil+ indicates that there are no pending timeouts. On some platforms, this function will always returns +nil+ (no pending timeouts). See libusb's notes on time-based events. @return [Float, nil] the timeout in seconds
[ "Determine", "the", "next", "internal", "timeout", "that", "libusb", "needs", "to", "handle", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L318-L323
839
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.on_pollfd_added
def on_pollfd_added &block @on_pollfd_added = proc do |fd, events, _| pollfd = Pollfd.new fd, events block.call pollfd end Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil end
ruby
def on_pollfd_added &block @on_pollfd_added = proc do |fd, events, _| pollfd = Pollfd.new fd, events block.call pollfd end Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil end
[ "def", "on_pollfd_added", "&", "block", "@on_pollfd_added", "=", "proc", "do", "|", "fd", ",", "events", ",", "_", "|", "pollfd", "=", "Pollfd", ".", "new", "fd", ",", "events", "block", ".", "call", "pollfd", "end", "Call", ".", "libusb_set_pollfd_notifiers", "@ctx", ",", "@on_pollfd_added", ",", "@on_pollfd_removed", ",", "nil", "end" ]
Register a notification block for file descriptor additions. This block will be invoked for every new file descriptor that libusb uses as an event source. Note that file descriptors may have been added even before you register these notifiers (e.g. at {Context#initialize} time). @yieldparam [Pollfd] pollfd The added file descriptor is yielded to the block
[ "Register", "a", "notification", "block", "for", "file", "descriptor", "additions", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L334-L340
840
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.on_pollfd_removed
def on_pollfd_removed &block @on_pollfd_removed = proc do |fd, _| pollfd = Pollfd.new fd block.call pollfd end Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil end
ruby
def on_pollfd_removed &block @on_pollfd_removed = proc do |fd, _| pollfd = Pollfd.new fd block.call pollfd end Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil end
[ "def", "on_pollfd_removed", "&", "block", "@on_pollfd_removed", "=", "proc", "do", "|", "fd", ",", "_", "|", "pollfd", "=", "Pollfd", ".", "new", "fd", "block", ".", "call", "pollfd", "end", "Call", ".", "libusb_set_pollfd_notifiers", "@ctx", ",", "@on_pollfd_added", ",", "@on_pollfd_removed", ",", "nil", "end" ]
Register a notification block for file descriptor removals. This block will be invoked for every removed file descriptor that libusb uses as an event source. Note that the removal notifier may be called during {Context#exit} (e.g. when it is closing file descriptors that were opened and added to the poll set at {Context#initialize} time). If you don't want this, overwrite the notifier immediately before calling {Context#exit}. @yieldparam [Pollfd] pollfd The removed file descriptor is yielded to the block
[ "Register", "a", "notification", "block", "for", "file", "descriptor", "removals", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L353-L359
841
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.on_hotplug_event
def on_hotplug_event(args={}, &block) events = args.delete(:events) || (HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT) flags = args.delete(:flags) || 0 vendor_id = args.delete(:vendor_id) || HOTPLUG_MATCH_ANY product_id = args.delete(:product_id) || HOTPLUG_MATCH_ANY dev_class = args.delete(:dev_class) || HOTPLUG_MATCH_ANY raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? handle = HotplugCallback.new self, @ctx, @hotplug_callbacks block2 = proc do |ctx, pDevice, event, _user_data| raise "internal error: unexpected context" unless @ctx==ctx dev = Device.new @ctx, pDevice blres = block.call(dev, event) case blres when :finish 1 when :repeat 0 else raise ArgumentError, "hotplug event handler must return :finish or :repeat" end end res = Call.libusb_hotplug_register_callback(@ctx, events, flags, vendor_id, product_id, dev_class, block2, nil, handle) LIBUSB.raise_error res, "in libusb_hotplug_register_callback" if res<0 # Avoid GC'ing of the block: @hotplug_callbacks[handle[:handle]] = block2 return handle end
ruby
def on_hotplug_event(args={}, &block) events = args.delete(:events) || (HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT) flags = args.delete(:flags) || 0 vendor_id = args.delete(:vendor_id) || HOTPLUG_MATCH_ANY product_id = args.delete(:product_id) || HOTPLUG_MATCH_ANY dev_class = args.delete(:dev_class) || HOTPLUG_MATCH_ANY raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? handle = HotplugCallback.new self, @ctx, @hotplug_callbacks block2 = proc do |ctx, pDevice, event, _user_data| raise "internal error: unexpected context" unless @ctx==ctx dev = Device.new @ctx, pDevice blres = block.call(dev, event) case blres when :finish 1 when :repeat 0 else raise ArgumentError, "hotplug event handler must return :finish or :repeat" end end res = Call.libusb_hotplug_register_callback(@ctx, events, flags, vendor_id, product_id, dev_class, block2, nil, handle) LIBUSB.raise_error res, "in libusb_hotplug_register_callback" if res<0 # Avoid GC'ing of the block: @hotplug_callbacks[handle[:handle]] = block2 return handle end
[ "def", "on_hotplug_event", "(", "args", "=", "{", "}", ",", "&", "block", ")", "events", "=", "args", ".", "delete", "(", ":events", ")", "||", "(", "HOTPLUG_EVENT_DEVICE_ARRIVED", "|", "HOTPLUG_EVENT_DEVICE_LEFT", ")", "flags", "=", "args", ".", "delete", "(", ":flags", ")", "||", "0", "vendor_id", "=", "args", ".", "delete", "(", ":vendor_id", ")", "||", "HOTPLUG_MATCH_ANY", "product_id", "=", "args", ".", "delete", "(", ":product_id", ")", "||", "HOTPLUG_MATCH_ANY", "dev_class", "=", "args", ".", "delete", "(", ":dev_class", ")", "||", "HOTPLUG_MATCH_ANY", "raise", "ArgumentError", ",", "\"invalid params #{args.inspect}\"", "unless", "args", ".", "empty?", "handle", "=", "HotplugCallback", ".", "new", "self", ",", "@ctx", ",", "@hotplug_callbacks", "block2", "=", "proc", "do", "|", "ctx", ",", "pDevice", ",", "event", ",", "_user_data", "|", "raise", "\"internal error: unexpected context\"", "unless", "@ctx", "==", "ctx", "dev", "=", "Device", ".", "new", "@ctx", ",", "pDevice", "blres", "=", "block", ".", "call", "(", "dev", ",", "event", ")", "case", "blres", "when", ":finish", "1", "when", ":repeat", "0", "else", "raise", "ArgumentError", ",", "\"hotplug event handler must return :finish or :repeat\"", "end", "end", "res", "=", "Call", ".", "libusb_hotplug_register_callback", "(", "@ctx", ",", "events", ",", "flags", ",", "vendor_id", ",", "product_id", ",", "dev_class", ",", "block2", ",", "nil", ",", "handle", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_hotplug_register_callback\"", "if", "res", "<", "0", "# Avoid GC'ing of the block:", "@hotplug_callbacks", "[", "handle", "[", ":handle", "]", "]", "=", "block2", "return", "handle", "end" ]
Register a hotplug event notification. Register a callback with the {LIBUSB::Context}. The callback will fire when a matching event occurs on a matching device. The callback is armed until either it is deregistered with {HotplugCallback#deregister} or the supplied block returns +:finish+ to indicate it is finished processing events. If the flag {Call::HotplugFlags HOTPLUG_ENUMERATE} is passed the callback will be called with a {Call::HotplugEvents :HOTPLUG_EVENT_DEVICE_ARRIVED} for all devices already plugged into the machine. Note that libusb modifies its internal device list from a separate thread, while calling hotplug callbacks from {#handle_events}, so it is possible for a device to already be present on, or removed from, its internal device list, while the hotplug callbacks still need to be dispatched. This means that when using {Call::HotplugFlags HOTPLUG_ENUMERATE}, your callback may be called twice for the arrival of the same device, once from {#on_hotplug_event} and once from {#handle_events}; and/or your callback may be called for the removal of a device for which an arrived call was never made. Since libusb version 1.0.16. @param [Hash] args @option args [Fixnum,Symbol] :events bitwise or of events that will trigger this callback. Default is +LIBUSB::HOTPLUG_EVENT_DEVICE_ARRIVED|LIBUSB::HOTPLUG_EVENT_DEVICE_LEFT+ . See {Call::HotplugEvents HotplugEvents} @option args [Fixnum,Symbol] :flags hotplug callback flags. Default is 0. See {Call::HotplugFlags HotplugFlags} @option args [Fixnum] :vendor_id the vendor id to match. Default is {HOTPLUG_MATCH_ANY}. @option args [Fixnum] :product_id the product id to match. Default is {HOTPLUG_MATCH_ANY}. @option args [Fixnum] :dev_class the device class to match. Default is {HOTPLUG_MATCH_ANY}. @return [HotplugCallback] The handle to the registered callback. @yieldparam [Device] device the attached or removed {Device} is yielded to the block @yieldparam [Symbol] event a {Call::HotplugEvents HotplugEvents} symbol @yieldreturn [Symbol] +:finish+ to deregister the callback, +:repeat+ to receive additional events @raise [ArgumentError, LIBUSB::Error] in case of failure
[ "Register", "a", "hotplug", "event", "notification", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L396-L433
842
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_message
def send_message(params) extra_params_validation = { text: { required: true, class: [String] }, parse_mode: { required: false, class: [String] }, disable_web_page_preview: { required: false, class: [TrueClass, FalseClass] } } send_something(:message, params, extra_params_validation) end
ruby
def send_message(params) extra_params_validation = { text: { required: true, class: [String] }, parse_mode: { required: false, class: [String] }, disable_web_page_preview: { required: false, class: [TrueClass, FalseClass] } } send_something(:message, params, extra_params_validation) end
[ "def", "send_message", "(", "params", ")", "extra_params_validation", "=", "{", "text", ":", "{", "required", ":", "true", ",", "class", ":", "[", "String", "]", "}", ",", "parse_mode", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", ",", "disable_web_page_preview", ":", "{", "required", ":", "false", ",", "class", ":", "[", "TrueClass", ",", "FalseClass", "]", "}", "}", "send_something", "(", ":message", ",", "params", ",", "extra_params_validation", ")", "end" ]
Send text messages to a user or group chat. @param [Hash] params hash of paramers to send to the sendMessage API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [String] :text Required. Text of the message to be sent @option params [String] :parse_mode Optional. Send Markdown, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. @option params [Boolean] :disable_web_page_preview Optional. Disables link previews for links in this message @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.send_message( chat_id: 123456789, text: "Hello World!" ) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Send", "text", "messages", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L136-L144
843
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.forward_message
def forward_message(params) params_validation = { chat_id: { required: true, class: [Fixnum] }, from_chat_id: { required: true, class: [String] }, message_id: { required: true, class: [Fixnum] } } response = api_request('forwardMessage', params, params_validation) Telegrammer::DataTypes::Message.new(response.result) end
ruby
def forward_message(params) params_validation = { chat_id: { required: true, class: [Fixnum] }, from_chat_id: { required: true, class: [String] }, message_id: { required: true, class: [Fixnum] } } response = api_request('forwardMessage', params, params_validation) Telegrammer::DataTypes::Message.new(response.result) end
[ "def", "forward_message", "(", "params", ")", "params_validation", "=", "{", "chat_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Fixnum", "]", "}", ",", "from_chat_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "String", "]", "}", ",", "message_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Fixnum", "]", "}", "}", "response", "=", "api_request", "(", "'forwardMessage'", ",", "params", ",", "params_validation", ")", "Telegrammer", "::", "DataTypes", "::", "Message", ".", "new", "(", "response", ".", "result", ")", "end" ]
Forward message to a user or group chat. @param [Hash] params hash of paramers to send to the forwardMessage API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [Integer,String] :from_chat_id Required. Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). @option params [Integer] :message_id Required. Message id to be forwarded. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.forward_message( chat_id: 123456789, from_chat_id: 987654321 message_id: 111222333 ) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Forward", "message", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L166-L176
844
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_photo
def send_photo(params) extra_params_validation = { photo: { required: true, class: [File, String] }, caption: { required: false, class: [String] } } send_something(:photo, params, extra_params_validation) end
ruby
def send_photo(params) extra_params_validation = { photo: { required: true, class: [File, String] }, caption: { required: false, class: [String] } } send_something(:photo, params, extra_params_validation) end
[ "def", "send_photo", "(", "params", ")", "extra_params_validation", "=", "{", "photo", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", ",", "caption", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", "}", "send_something", "(", ":photo", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends a photo to a user or group chat. @param [Hash] params hash of paramers to send to the sendPhoto API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] :photo Required. Photo to send. You can either pass a file_id as String to resend a photo that is already on the Telegram servers, or upload a new photo using multipart/form-data. @option params [String] :caption Optional. Photo caption (may also be used when resending photos by file_id). @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') image_file = File.open("foo.jpg") bot.send_photo(chat_id: 123456789, photo: image_file) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @see #send_document @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "a", "photo", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L197-L204
845
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_audio
def send_audio(params) extra_params_validation = { audio: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] }, performer: { required: false, class: [String] }, title: { required: false, class: [String] } } send_something(:audio, params, extra_params_validation) end
ruby
def send_audio(params) extra_params_validation = { audio: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] }, performer: { required: false, class: [String] }, title: { required: false, class: [String] } } send_something(:audio, params, extra_params_validation) end
[ "def", "send_audio", "(", "params", ")", "extra_params_validation", "=", "{", "audio", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", ",", "duration", ":", "{", "required", ":", "false", ",", "class", ":", "[", "Integer", "]", "}", ",", "performer", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", ",", "title", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", "}", "send_something", "(", ":audio", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends audio file to a user or group chat. At this moment, Telegram only allows Ogg files encoded with the OPUS codec. If you need to send another file format, you must use #send_document. @param [Hash] params hash of paramers to send to the sendAudio API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] audio Required. Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data @option params [Integer] duration Optional. Duration of the audio in seconds. @option params [String] performer Optional. Performer. @option params [String] title Optional. Track name. @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') audio_file = File.open("foo.ogg") bot.send_audio(chat_id: 123456789, audio: audio_file) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @see #send_document @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "audio", "file", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L229-L238
846
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_voice
def send_voice(params) extra_params_validation = { voice: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] } } send_something(:audio, params, extra_params_validation) end
ruby
def send_voice(params) extra_params_validation = { voice: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] } } send_something(:audio, params, extra_params_validation) end
[ "def", "send_voice", "(", "params", ")", "extra_params_validation", "=", "{", "voice", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", ",", "duration", ":", "{", "required", ":", "false", ",", "class", ":", "[", "Integer", "]", "}", "}", "send_something", "(", ":audio", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends audio files file to a user or group chat that the users will see as a playable voice message. At this moment, Telegram only allows Ogg files encoded with the OPUS codec. If you need to send another file format, you must use #send_document. @param [Hash] params hash of paramers to send to the sendAudio API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] voice Required. Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data @option params [Integer] duration Optional. Duration of sent audio in seconds. @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') voice_file = File.open("foo.ogg") bot.send_voice(chat_id: 123456789, voice: audio_file) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @see #send_document @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "audio", "files", "file", "to", "a", "user", "or", "group", "chat", "that", "the", "users", "will", "see", "as", "a", "playable", "voice", "message", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L261-L268
847
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_document
def send_document(params) extra_params_validation = { document: { required: true, class: [File, String] } } send_something(:document, params, extra_params_validation) end
ruby
def send_document(params) extra_params_validation = { document: { required: true, class: [File, String] } } send_something(:document, params, extra_params_validation) end
[ "def", "send_document", "(", "params", ")", "extra_params_validation", "=", "{", "document", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", "}", "send_something", "(", ":document", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends a document to a user or group chat. @param [Hash] params hash of paramers to send to the sendDocument API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] :document Required. File to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/form-data. @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') my_secret_file = File.open("secrets.doc") bot.send_document(chat_id: 123456789, document: my_secret_file) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "a", "document", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L288-L294
848
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_sticker
def send_sticker(params) extra_params_validation = { sticker: { required: true, class: [File, String] } } send_something(:sticker, params, extra_params_validation) end
ruby
def send_sticker(params) extra_params_validation = { sticker: { required: true, class: [File, String] } } send_something(:sticker, params, extra_params_validation) end
[ "def", "send_sticker", "(", "params", ")", "extra_params_validation", "=", "{", "sticker", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", "}", "send_something", "(", ":sticker", ",", "params", ",", "extra_params_validation", ")", "end" ]
Send WebP images as stickers. @param [Hash] params hash of paramers to send to the sendSticker API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] :sticker Required. Sticker to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/form-data. @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') sticker_file = File.open("my-sticker.webp") bot.send_sticker(chat_id: 123456789, sticker: sticker_file) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @see #send_document @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Send", "WebP", "images", "as", "stickers", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L314-L320
849
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_video
def send_video(params) extra_params_validation = { video: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] }, caption: { required: false, class: [String] } } send_something(:video, params, extra_params_validation) end
ruby
def send_video(params) extra_params_validation = { video: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] }, caption: { required: false, class: [String] } } send_something(:video, params, extra_params_validation) end
[ "def", "send_video", "(", "params", ")", "extra_params_validation", "=", "{", "video", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", ",", "duration", ":", "{", "required", ":", "false", ",", "class", ":", "[", "Integer", "]", "}", ",", "caption", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", "}", "send_something", "(", ":video", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends a video file to a user or group chat. At this moment, Telegram only support mp4 videos. If you need to send other formats you must use #send_document. @param [Hash] params hash of paramers to send to the sendVideo API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] :video Required. Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram servers, or upload a new video file. @option params [Integer] :duration Optional. Duration of sent video in seconds. @option params [String] :caption Optional. Video caption (may also be used when resending videos by file_id). @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') my_video = File.open("foo.mp4") bot.send_video(chat_id: 123456789, video: my_video) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @see #send_document @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "a", "video", "file", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L344-L352
850
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_location
def send_location(params) extra_params_validation = { latitude: { required: true, class: [Float] }, longitude: { required: true, class: [Float] } } send_something(:location, params, extra_params_validation) end
ruby
def send_location(params) extra_params_validation = { latitude: { required: true, class: [Float] }, longitude: { required: true, class: [Float] } } send_something(:location, params, extra_params_validation) end
[ "def", "send_location", "(", "params", ")", "extra_params_validation", "=", "{", "latitude", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Float", "]", "}", ",", "longitude", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Float", "]", "}", "}", "send_something", "(", ":location", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends point on the map to a user or group chat. @param [Hash] params hash of paramers to send to the sendAudio API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [Float] :latitude Required. Latitude of location. @option params [Float] :longitude Required. Longitude of location. @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message. @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.send_location(chat_id: 123456789, latitude: 38.775539, longitude: -4.829988) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "point", "on", "the", "map", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L371-L378
851
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_chat_action
def send_chat_action(params) params_validation = { chat_id: { required: true, class: [Fixnum, String] }, action: { required: true, class: [String] } } api_request('sendChatAction', params, params_validation) end
ruby
def send_chat_action(params) params_validation = { chat_id: { required: true, class: [Fixnum, String] }, action: { required: true, class: [String] } } api_request('sendChatAction', params, params_validation) end
[ "def", "send_chat_action", "(", "params", ")", "params_validation", "=", "{", "chat_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Fixnum", ",", "String", "]", "}", ",", "action", ":", "{", "required", ":", "true", ",", "class", ":", "[", "String", "]", "}", "}", "api_request", "(", "'sendChatAction'", ",", "params", ",", "params_validation", ")", "end" ]
Sends a status action to a user or group chat. Used when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). @param [Hash] params hash of paramers to send to the sendChatAction API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [String] :action Required. Type of action to broadcast. Choose one, depending on what the user is about to receive: "typing" for text messages, "upload_photo" for photos, "record_video" or "upload_video" for videos, "record_audio" or "upload_audio" for audio files, "upload_document" for general files, "find_location" for location data. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.send_chat_action(chat_id: 123456789, action: "typing") @raise [Telegrammer::Errors::BadRequestError] @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [Telegrammer::ApiResponse] Response from the API.
[ "Sends", "a", "status", "action", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L396-L403
852
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.get_user_profile_photos
def get_user_profile_photos(params) params_validation = { user_id: { required: true, class: [Fixnum] }, offset: { required: false, class: [Fixnum] }, limit: { required: false, class: [Fixnum] } } response = api_request('getUserProfilePhotos', params, params_validation) Telegrammer::DataTypes::UserProfilePhotos.new(response.result).to_h end
ruby
def get_user_profile_photos(params) params_validation = { user_id: { required: true, class: [Fixnum] }, offset: { required: false, class: [Fixnum] }, limit: { required: false, class: [Fixnum] } } response = api_request('getUserProfilePhotos', params, params_validation) Telegrammer::DataTypes::UserProfilePhotos.new(response.result).to_h end
[ "def", "get_user_profile_photos", "(", "params", ")", "params_validation", "=", "{", "user_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Fixnum", "]", "}", ",", "offset", ":", "{", "required", ":", "false", ",", "class", ":", "[", "Fixnum", "]", "}", ",", "limit", ":", "{", "required", ":", "false", ",", "class", ":", "[", "Fixnum", "]", "}", "}", "response", "=", "api_request", "(", "'getUserProfilePhotos'", ",", "params", ",", "params_validation", ")", "Telegrammer", "::", "DataTypes", "::", "UserProfilePhotos", ".", "new", "(", "response", ".", "result", ")", ".", "to_h", "end" ]
Get a list of profile pictures for a user. @param [Hash] params hash of paramers to send to the getUserProfilePhotos API operation. @option params [Integer] :user_id Required. Unique identifier of the target user. @option params [Integer] :offset Optional. Sequential number of the first photo to be returned. By default, all photos are returned. @option params [Integer] :limit Optional. Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.get_user_profile_photos(user_id: 123456789) @raise [Telegrammer::Errors::BadRequestError] @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [Telegrammer::DataTypes::UserProfilePhotos] Message object sent to the user or group chat
[ "Get", "a", "list", "of", "profile", "pictures", "for", "a", "user", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L420-L430
853
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.get_file
def get_file(params) params_validation = { file_id: { required: true, class: [String] } } response = api_request("getFile", params, params_validation) file_object = Telegrammer::DataTypes::File.new(response.result) "#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}" end
ruby
def get_file(params) params_validation = { file_id: { required: true, class: [String] } } response = api_request("getFile", params, params_validation) file_object = Telegrammer::DataTypes::File.new(response.result) "#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}" end
[ "def", "get_file", "(", "params", ")", "params_validation", "=", "{", "file_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "String", "]", "}", "}", "response", "=", "api_request", "(", "\"getFile\"", ",", "params", ",", "params_validation", ")", "file_object", "=", "Telegrammer", "::", "DataTypes", "::", "File", ".", "new", "(", "response", ".", "result", ")", "\"#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}\"", "end" ]
Get basic info about a file and prepare it for downloading. @param [Hash] params hash of paramers to send to the getFile API operation. @option params [String] :file_id Required. File identifier to get info about. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.get_file(file_id: 123456789) @raise [Telegrammer::Errors::BadRequestError] @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [String] URL of the file (valid for one hour) or BadRequestError if the file_id is wrong
[ "Get", "basic", "info", "about", "a", "file", "and", "prepare", "it", "for", "downloading", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L445-L454
854
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.answer_inline_query
def answer_inline_query(params) params_validation = { inline_query_id: { required: true, class: [String] }, results: { required: true, class: [Array] }, cache_time: { required: false, class: [Fixnum] }, is_personal: { required: false, class: [TrueClass, FalseClass] }, next_offset: { required: false, class: [String] } } response = api_request("answerInlineQuery", params, params_validation) end
ruby
def answer_inline_query(params) params_validation = { inline_query_id: { required: true, class: [String] }, results: { required: true, class: [Array] }, cache_time: { required: false, class: [Fixnum] }, is_personal: { required: false, class: [TrueClass, FalseClass] }, next_offset: { required: false, class: [String] } } response = api_request("answerInlineQuery", params, params_validation) end
[ "def", "answer_inline_query", "(", "params", ")", "params_validation", "=", "{", "inline_query_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "String", "]", "}", ",", "results", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Array", "]", "}", ",", "cache_time", ":", "{", "required", ":", "false", ",", "class", ":", "[", "Fixnum", "]", "}", ",", "is_personal", ":", "{", "required", ":", "false", ",", "class", ":", "[", "TrueClass", ",", "FalseClass", "]", "}", ",", "next_offset", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", "}", "response", "=", "api_request", "(", "\"answerInlineQuery\"", ",", "params", ",", "params_validation", ")", "end" ]
Answer an inline query. On success, True is returned. No more than 50 results per query are allowed. @param [Hash] params hash of paramers to send to the answerInlineQuery API operation. @option params [String] :inline_query_id Required. Unique identifier for the answered query @option params [Array] :results Required. An array of InlineQueryResults objects for the inline query @option params [Fixnum] :cache_time Optional. The maximum amount of time the result of the inline query may be cached on the server @option params [TrueClass,FalseClass] :is_personal Optional. Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query @option params [String] :next_offset Optional. Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.get_updates do |update| if update.is_a?(Telegrammer::DataTypes::InlineQuery) inline_query = message.inline_query if inline_query results = the_search_in_my_app(inline_query.query) bot.answer_inline_query( inline_query_id: "my-internal-query-id", results: results ) end end end @raise [Telegrammer::Errors::BadRequestError] @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [TrueClass] True if all was OK
[ "Answer", "an", "inline", "query", ".", "On", "success", "True", "is", "returned", ".", "No", "more", "than", "50", "results", "per", "query", "are", "allowed", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L489-L499
855
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/apis/distance_matrix.rb
GoogleMapsService::Apis.DistanceMatrix.distance_matrix
def distance_matrix(origins, destinations, mode: nil, language: nil, avoid: nil, units: nil, departure_time: nil, arrival_time: nil, transit_mode: nil, transit_routing_preference: nil) params = { origins: GoogleMapsService::Convert.waypoints(origins), destinations: GoogleMapsService::Convert.waypoints(destinations) } params[:language] = language if language params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode params[:avoid] = GoogleMapsService::Validator.avoid(avoid) if avoid params[:units] = units if units params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time if departure_time and arrival_time raise ArgumentError, 'Should not specify both departure_time and arrival_time.' end params[:transit_mode] = GoogleMapsService::Convert.join_list('|', transit_mode) if transit_mode params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference return get('/maps/api/distancematrix/json', params) end
ruby
def distance_matrix(origins, destinations, mode: nil, language: nil, avoid: nil, units: nil, departure_time: nil, arrival_time: nil, transit_mode: nil, transit_routing_preference: nil) params = { origins: GoogleMapsService::Convert.waypoints(origins), destinations: GoogleMapsService::Convert.waypoints(destinations) } params[:language] = language if language params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode params[:avoid] = GoogleMapsService::Validator.avoid(avoid) if avoid params[:units] = units if units params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time if departure_time and arrival_time raise ArgumentError, 'Should not specify both departure_time and arrival_time.' end params[:transit_mode] = GoogleMapsService::Convert.join_list('|', transit_mode) if transit_mode params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference return get('/maps/api/distancematrix/json', params) end
[ "def", "distance_matrix", "(", "origins", ",", "destinations", ",", "mode", ":", "nil", ",", "language", ":", "nil", ",", "avoid", ":", "nil", ",", "units", ":", "nil", ",", "departure_time", ":", "nil", ",", "arrival_time", ":", "nil", ",", "transit_mode", ":", "nil", ",", "transit_routing_preference", ":", "nil", ")", "params", "=", "{", "origins", ":", "GoogleMapsService", "::", "Convert", ".", "waypoints", "(", "origins", ")", ",", "destinations", ":", "GoogleMapsService", "::", "Convert", ".", "waypoints", "(", "destinations", ")", "}", "params", "[", ":language", "]", "=", "language", "if", "language", "params", "[", ":mode", "]", "=", "GoogleMapsService", "::", "Validator", ".", "travel_mode", "(", "mode", ")", "if", "mode", "params", "[", ":avoid", "]", "=", "GoogleMapsService", "::", "Validator", ".", "avoid", "(", "avoid", ")", "if", "avoid", "params", "[", ":units", "]", "=", "units", "if", "units", "params", "[", ":departure_time", "]", "=", "GoogleMapsService", "::", "Convert", ".", "time", "(", "departure_time", ")", "if", "departure_time", "params", "[", ":arrival_time", "]", "=", "GoogleMapsService", "::", "Convert", ".", "time", "(", "arrival_time", ")", "if", "arrival_time", "if", "departure_time", "and", "arrival_time", "raise", "ArgumentError", ",", "'Should not specify both departure_time and arrival_time.'", "end", "params", "[", ":transit_mode", "]", "=", "GoogleMapsService", "::", "Convert", ".", "join_list", "(", "'|'", ",", "transit_mode", ")", "if", "transit_mode", "params", "[", ":transit_routing_preference", "]", "=", "transit_routing_preference", "if", "transit_routing_preference", "return", "get", "(", "'/maps/api/distancematrix/json'", ",", "params", ")", "end" ]
Gets travel distance and time for a matrix of origins and destinations. @example Simple distance matrix origins = ["Perth, Australia", "Sydney, Australia", "Melbourne, Australia", "Adelaide, Australia", "Brisbane, Australia", "Darwin, Australia", "Hobart, Australia", "Canberra, Australia"] destinations = ["Uluru, Australia", "Kakadu, Australia", "Blue Mountains, Australia", "Bungle Bungles, Australia", "The Pinnacles, Australia"] matrix = client.distance_matrix(origins, destinations) @example Complex distance matrix origins = ["Bobcaygeon ON", [41.43206, -81.38992]] destinations = [[43.012486, -83.6964149], {lat: 42.8863855, lng: -78.8781627}] matrix = client.distance_matrix(origins, destinations, mode: 'driving', language: 'en-AU', avoid: 'tolls', units: 'imperial') @param [Array] origins One or more addresses and/or lat/lon pairs, from which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a lat/lon coordinate to calculate directions. @param [Array] destinations One or more addresses and/or lat/lon pairs, to which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a lat/lon coordinate to calculate directions. @param [String] mode Specifies the mode of transport to use when calculating directions. Valid values are `driving`, `walking`, `transit` or `bicycling`. @param [String] language The language in which to return results. @param [String] avoid Indicates that the calculated route(s) should avoid the indicated features. Valid values are `tolls`, `highways` or `ferries`. @param [String] units Specifies the unit system to use when displaying results. Valid values are `metric` or `imperial`. @param [Integer, DateTime] departure_time Specifies the desired time of departure. @param [Integer, DateTime] arrival_time Specifies the desired time of arrival for transit directions. Note: you can not specify both `departure_time` and `arrival_time`. @param [String, Array<String>] transit_mode Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the mode is transit. Valid values are `bus`, `subway`, `train`, `tram`, or `rail`. `rail` is equivalent to `["train", "tram", "subway"]`. @param [String] transit_routing_preference Specifies preferences for transit requests. Valid values are `less_walking` or `fewer_transfers`. @return [Hash] Matrix of distances. Results are returned in rows, each row containing one origin paired with each destination.
[ "Gets", "travel", "distance", "and", "time", "for", "a", "matrix", "of", "origins", "and", "destinations", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/distance_matrix.rb#L58-L83
856
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/convert.rb
GoogleMapsService.Convert.components
def components(arg) if arg.kind_of?(Hash) arg = arg.sort.map { |k, v| "#{k}:#{v}" } return arg.join("|") end raise ArgumentError, "Expected a Hash for components, but got #{arg.class}" end
ruby
def components(arg) if arg.kind_of?(Hash) arg = arg.sort.map { |k, v| "#{k}:#{v}" } return arg.join("|") end raise ArgumentError, "Expected a Hash for components, but got #{arg.class}" end
[ "def", "components", "(", "arg", ")", "if", "arg", ".", "kind_of?", "(", "Hash", ")", "arg", "=", "arg", ".", "sort", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}:#{v}\"", "}", "return", "arg", ".", "join", "(", "\"|\"", ")", "end", "raise", "ArgumentError", ",", "\"Expected a Hash for components, but got #{arg.class}\"", "end" ]
Converts a dict of components to the format expected by the Google Maps server. @example >> GoogleMapsService::Convert.components({"country": "US", "postal_code": "94043"}) => "country:US|postal_code:94043" @param [Hash] arg The component filter. @return [String]
[ "Converts", "a", "dict", "of", "components", "to", "the", "format", "expected", "by", "the", "Google", "Maps", "server", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/convert.rb#L94-L101
857
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/convert.rb
GoogleMapsService.Convert.waypoint
def waypoint(waypoint) if waypoint.kind_of?(String) return waypoint end return GoogleMapsService::Convert.latlng(waypoint) end
ruby
def waypoint(waypoint) if waypoint.kind_of?(String) return waypoint end return GoogleMapsService::Convert.latlng(waypoint) end
[ "def", "waypoint", "(", "waypoint", ")", "if", "waypoint", ".", "kind_of?", "(", "String", ")", "return", "waypoint", "end", "return", "GoogleMapsService", "::", "Convert", ".", "latlng", "(", "waypoint", ")", "end" ]
Converts a waypoints to the format expected by the Google Maps server. Accept two representation of waypoint: 1. String: Name of place or comma-separated lat/lon pair. 2. Hash/Array: Lat/lon pair. @param [Array, String, Hash] waypoint Path. @return [String]
[ "Converts", "a", "waypoints", "to", "the", "format", "expected", "by", "the", "Google", "Maps", "server", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/convert.rb#L149-L154
858
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/apis/geocoding.rb
GoogleMapsService::Apis.Geocoding.reverse_geocode
def reverse_geocode(latlng, location_type: nil, result_type: nil, language: nil) params = { latlng: GoogleMapsService::Convert.latlng(latlng) } params[:result_type] = GoogleMapsService::Convert.join_list('|', result_type) if result_type params[:location_type] = GoogleMapsService::Convert.join_list('|', location_type) if location_type params[:language] = language if language return get('/maps/api/geocode/json', params)[:results] end
ruby
def reverse_geocode(latlng, location_type: nil, result_type: nil, language: nil) params = { latlng: GoogleMapsService::Convert.latlng(latlng) } params[:result_type] = GoogleMapsService::Convert.join_list('|', result_type) if result_type params[:location_type] = GoogleMapsService::Convert.join_list('|', location_type) if location_type params[:language] = language if language return get('/maps/api/geocode/json', params)[:results] end
[ "def", "reverse_geocode", "(", "latlng", ",", "location_type", ":", "nil", ",", "result_type", ":", "nil", ",", "language", ":", "nil", ")", "params", "=", "{", "latlng", ":", "GoogleMapsService", "::", "Convert", ".", "latlng", "(", "latlng", ")", "}", "params", "[", ":result_type", "]", "=", "GoogleMapsService", "::", "Convert", ".", "join_list", "(", "'|'", ",", "result_type", ")", "if", "result_type", "params", "[", ":location_type", "]", "=", "GoogleMapsService", "::", "Convert", ".", "join_list", "(", "'|'", ",", "location_type", ")", "if", "location_type", "params", "[", ":language", "]", "=", "language", "if", "language", "return", "get", "(", "'/maps/api/geocode/json'", ",", "params", ")", "[", ":results", "]", "end" ]
Reverse geocoding is the process of converting geographic coordinates into a human-readable address. @example Simple lat/lon pair client.reverse_geocode({lat: 40.714224, lng: -73.961452}) @example Multiple parameters client.reverse_geocode([40.714224, -73.961452], location_type: ['ROOFTOP', 'RANGE_INTERPOLATED'], result_type: ['street_address', 'route'], language: 'es') @param [Hash, Array] latlng The latitude/longitude value for which you wish to obtain the closest, human-readable address. @param [String, Array<String>] location_type One or more location types to restrict results to. @param [String, Array<String>] result_type One or more address types to restrict results to. @param [String] language The language in which to return results. @return [Array] Array of reverse geocoding results.
[ "Reverse", "geocoding", "is", "the", "process", "of", "converting", "geographic", "coordinates", "into", "a", "human", "-", "readable", "address", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/geocoding.rb#L72-L82
859
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/apis/time_zone.rb
GoogleMapsService::Apis.TimeZone.timezone
def timezone(location, timestamp: Time.now, language: nil) location = GoogleMapsService::Convert.latlng(location) timestamp = GoogleMapsService::Convert.time(timestamp) params = { location: location, timestamp: timestamp } params[:language] = language if language return get('/maps/api/timezone/json', params) end
ruby
def timezone(location, timestamp: Time.now, language: nil) location = GoogleMapsService::Convert.latlng(location) timestamp = GoogleMapsService::Convert.time(timestamp) params = { location: location, timestamp: timestamp } params[:language] = language if language return get('/maps/api/timezone/json', params) end
[ "def", "timezone", "(", "location", ",", "timestamp", ":", "Time", ".", "now", ",", "language", ":", "nil", ")", "location", "=", "GoogleMapsService", "::", "Convert", ".", "latlng", "(", "location", ")", "timestamp", "=", "GoogleMapsService", "::", "Convert", ".", "time", "(", "timestamp", ")", "params", "=", "{", "location", ":", "location", ",", "timestamp", ":", "timestamp", "}", "params", "[", ":language", "]", "=", "language", "if", "language", "return", "get", "(", "'/maps/api/timezone/json'", ",", "params", ")", "end" ]
Get time zone for a location on the earth, as well as that location's time offset from UTC. @example Current time zone timezone = client.timezone([39.603481, -119.682251]) @example Time zone at certain time timezone = client.timezone([39.603481, -119.682251], timestamp: Time.at(1608)) @param [Hash, Array] location The latitude/longitude value representing the location to look up. @param [Integer, DateTime] timestamp Timestamp specifies the desired time as seconds since midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied. Times before 1970 can be expressed as negative values. Optional. Defaults to `Time.now`. @param [String] language The language in which to return results. @return [Hash] Time zone object.
[ "Get", "time", "zone", "for", "a", "location", "on", "the", "earth", "as", "well", "as", "that", "location", "s", "time", "offset", "from", "UTC", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/time_zone.rb#L27-L39
860
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/url.rb
GoogleMapsService.Url.sign_hmac
def sign_hmac(secret, payload) secret = secret.encode('ASCII') payload = payload.encode('ASCII') # Decode the private key raw_key = Base64.urlsafe_decode64(secret) # Create a signature using the private key and the URL digest = OpenSSL::Digest.new('sha1') raw_signature = OpenSSL::HMAC.digest(digest, raw_key, payload) # Encode the signature into base64 for url use form. signature = Base64.urlsafe_encode64(raw_signature) return signature end
ruby
def sign_hmac(secret, payload) secret = secret.encode('ASCII') payload = payload.encode('ASCII') # Decode the private key raw_key = Base64.urlsafe_decode64(secret) # Create a signature using the private key and the URL digest = OpenSSL::Digest.new('sha1') raw_signature = OpenSSL::HMAC.digest(digest, raw_key, payload) # Encode the signature into base64 for url use form. signature = Base64.urlsafe_encode64(raw_signature) return signature end
[ "def", "sign_hmac", "(", "secret", ",", "payload", ")", "secret", "=", "secret", ".", "encode", "(", "'ASCII'", ")", "payload", "=", "payload", ".", "encode", "(", "'ASCII'", ")", "# Decode the private key", "raw_key", "=", "Base64", ".", "urlsafe_decode64", "(", "secret", ")", "# Create a signature using the private key and the URL", "digest", "=", "OpenSSL", "::", "Digest", ".", "new", "(", "'sha1'", ")", "raw_signature", "=", "OpenSSL", "::", "HMAC", ".", "digest", "(", "digest", ",", "raw_key", ",", "payload", ")", "# Encode the signature into base64 for url use form.", "signature", "=", "Base64", ".", "urlsafe_encode64", "(", "raw_signature", ")", "return", "signature", "end" ]
Returns a base64-encoded HMAC-SHA1 signature of a given string. @param [String] secret The key used for the signature, base64 encoded. @param [String] payload The payload to sign. @return [String] Base64-encoded HMAC-SHA1 signature
[ "Returns", "a", "base64", "-", "encoded", "HMAC", "-", "SHA1", "signature", "of", "a", "given", "string", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/url.rb#L16-L30
861
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/url.rb
GoogleMapsService.Url.unquote_unreserved
def unquote_unreserved(uri) parts = uri.split('%') (1..parts.length-1).each do |i| h = parts[i][0..1] if h =~ /^([\h]{2})(.*)/ and c = $1.to_i(16).chr and UNRESERVED_SET.include?(c) parts[i] = c + $2 else parts[i] = '%' + parts[i] end end parts.join end
ruby
def unquote_unreserved(uri) parts = uri.split('%') (1..parts.length-1).each do |i| h = parts[i][0..1] if h =~ /^([\h]{2})(.*)/ and c = $1.to_i(16).chr and UNRESERVED_SET.include?(c) parts[i] = c + $2 else parts[i] = '%' + parts[i] end end parts.join end
[ "def", "unquote_unreserved", "(", "uri", ")", "parts", "=", "uri", ".", "split", "(", "'%'", ")", "(", "1", "..", "parts", ".", "length", "-", "1", ")", ".", "each", "do", "|", "i", "|", "h", "=", "parts", "[", "i", "]", "[", "0", "..", "1", "]", "if", "h", "=~", "/", "\\h", "/", "and", "c", "=", "$1", ".", "to_i", "(", "16", ")", ".", "chr", "and", "UNRESERVED_SET", ".", "include?", "(", "c", ")", "parts", "[", "i", "]", "=", "c", "+", "$2", "else", "parts", "[", "i", "]", "=", "'%'", "+", "parts", "[", "i", "]", "end", "end", "parts", ".", "join", "end" ]
Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. @param [String] uri @return [String]
[ "Un", "-", "escape", "any", "percent", "-", "escape", "sequences", "in", "a", "URI", "that", "are", "unreserved", "characters", ".", "This", "leaves", "all", "reserved", "illegal", "and", "non", "-", "ASCII", "bytes", "encoded", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/url.rb#L45-L59
862
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/client.rb
GoogleMapsService.Client.new_client
def new_client client = Hurley::Client.new client.request_options.query_class = Hurley::Query::Flat client.request_options.redirection_limit = 0 client.header[:user_agent] = user_agent client.connection = @connection if @connection @request_options.each_pair {|key, value| client.request_options[key] = value } if @request_options @ssl_options.each_pair {|key, value| client.ssl_options[key] = value } if @ssl_options client end
ruby
def new_client client = Hurley::Client.new client.request_options.query_class = Hurley::Query::Flat client.request_options.redirection_limit = 0 client.header[:user_agent] = user_agent client.connection = @connection if @connection @request_options.each_pair {|key, value| client.request_options[key] = value } if @request_options @ssl_options.each_pair {|key, value| client.ssl_options[key] = value } if @ssl_options client end
[ "def", "new_client", "client", "=", "Hurley", "::", "Client", ".", "new", "client", ".", "request_options", ".", "query_class", "=", "Hurley", "::", "Query", "::", "Flat", "client", ".", "request_options", ".", "redirection_limit", "=", "0", "client", ".", "header", "[", ":user_agent", "]", "=", "user_agent", "client", ".", "connection", "=", "@connection", "if", "@connection", "@request_options", ".", "each_pair", "{", "|", "key", ",", "value", "|", "client", ".", "request_options", "[", "key", "]", "=", "value", "}", "if", "@request_options", "@ssl_options", ".", "each_pair", "{", "|", "key", ",", "value", "|", "client", ".", "ssl_options", "[", "key", "]", "=", "value", "}", "if", "@ssl_options", "client", "end" ]
Create a new HTTP client. @return [Hurley::Client]
[ "Create", "a", "new", "HTTP", "client", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L141-L152
863
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/client.rb
GoogleMapsService.Client.get
def get(path, params, base_url: DEFAULT_BASE_URL, accepts_client_id: true, custom_response_decoder: nil) url = base_url + generate_auth_url(path, params, accepts_client_id) Retriable.retriable timeout: @retry_timeout, on: RETRIABLE_ERRORS do |try| begin request_query_ticket response = client.get url ensure release_query_ticket end return custom_response_decoder.call(response) if custom_response_decoder decode_response_body(response) end end
ruby
def get(path, params, base_url: DEFAULT_BASE_URL, accepts_client_id: true, custom_response_decoder: nil) url = base_url + generate_auth_url(path, params, accepts_client_id) Retriable.retriable timeout: @retry_timeout, on: RETRIABLE_ERRORS do |try| begin request_query_ticket response = client.get url ensure release_query_ticket end return custom_response_decoder.call(response) if custom_response_decoder decode_response_body(response) end end
[ "def", "get", "(", "path", ",", "params", ",", "base_url", ":", "DEFAULT_BASE_URL", ",", "accepts_client_id", ":", "true", ",", "custom_response_decoder", ":", "nil", ")", "url", "=", "base_url", "+", "generate_auth_url", "(", "path", ",", "params", ",", "accepts_client_id", ")", "Retriable", ".", "retriable", "timeout", ":", "@retry_timeout", ",", "on", ":", "RETRIABLE_ERRORS", "do", "|", "try", "|", "begin", "request_query_ticket", "response", "=", "client", ".", "get", "url", "ensure", "release_query_ticket", "end", "return", "custom_response_decoder", ".", "call", "(", "response", ")", "if", "custom_response_decoder", "decode_response_body", "(", "response", ")", "end", "end" ]
Make API call. @param [String] path Url path. @param [String] params Request parameters. @param [String] base_url Base Google Maps Web Service API endpoint url. @param [Boolean] accepts_client_id Sign the request using API {#keys} instead of {#client_id}. @param [Method] custom_response_decoder Custom method to decode raw API response. @return [Object] Decoded response body.
[ "Make", "API", "call", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L171-L185
864
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/client.rb
GoogleMapsService.Client.generate_auth_url
def generate_auth_url(path, params, accepts_client_id) # Deterministic ordering through sorting by key. # Useful for tests, and in the future, any caching. if params.kind_of?(Hash) params = params.sort else params = params.dup end if accepts_client_id and @client_id and @client_secret params << ["client", @client_id] path = [path, GoogleMapsService::Url.urlencode_params(params)].join("?") sig = GoogleMapsService::Url.sign_hmac(@client_secret, path) return path + "&signature=" + sig end if @key params << ["key", @key] return path + "?" + GoogleMapsService::Url.urlencode_params(params) end raise ArgumentError, "Must provide API key for this API. It does not accept enterprise credentials." end
ruby
def generate_auth_url(path, params, accepts_client_id) # Deterministic ordering through sorting by key. # Useful for tests, and in the future, any caching. if params.kind_of?(Hash) params = params.sort else params = params.dup end if accepts_client_id and @client_id and @client_secret params << ["client", @client_id] path = [path, GoogleMapsService::Url.urlencode_params(params)].join("?") sig = GoogleMapsService::Url.sign_hmac(@client_secret, path) return path + "&signature=" + sig end if @key params << ["key", @key] return path + "?" + GoogleMapsService::Url.urlencode_params(params) end raise ArgumentError, "Must provide API key for this API. It does not accept enterprise credentials." end
[ "def", "generate_auth_url", "(", "path", ",", "params", ",", "accepts_client_id", ")", "# Deterministic ordering through sorting by key.", "# Useful for tests, and in the future, any caching.", "if", "params", ".", "kind_of?", "(", "Hash", ")", "params", "=", "params", ".", "sort", "else", "params", "=", "params", ".", "dup", "end", "if", "accepts_client_id", "and", "@client_id", "and", "@client_secret", "params", "<<", "[", "\"client\"", ",", "@client_id", "]", "path", "=", "[", "path", ",", "GoogleMapsService", "::", "Url", ".", "urlencode_params", "(", "params", ")", "]", ".", "join", "(", "\"?\"", ")", "sig", "=", "GoogleMapsService", "::", "Url", ".", "sign_hmac", "(", "@client_secret", ",", "path", ")", "return", "path", "+", "\"&signature=\"", "+", "sig", "end", "if", "@key", "params", "<<", "[", "\"key\"", ",", "@key", "]", "return", "path", "+", "\"?\"", "+", "GoogleMapsService", "::", "Url", ".", "urlencode_params", "(", "params", ")", "end", "raise", "ArgumentError", ",", "\"Must provide API key for this API. It does not accept enterprise credentials.\"", "end" ]
Returns the path and query string portion of the request URL, first adding any necessary parameters. @param [String] path The path portion of the URL. @param [Hash] params URL parameters. @param [Boolean] accepts_client_id Sign the request using API {#keys} instead of {#client_id}. @return [String]
[ "Returns", "the", "path", "and", "query", "string", "portion", "of", "the", "request", "URL", "first", "adding", "any", "necessary", "parameters", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L213-L236
865
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/client.rb
GoogleMapsService.Client.decode_response_body
def decode_response_body(response) check_response_status_code(response) body = MultiJson.load(response.body, :symbolize_keys => true) check_body_error(response, body) body end
ruby
def decode_response_body(response) check_response_status_code(response) body = MultiJson.load(response.body, :symbolize_keys => true) check_body_error(response, body) body end
[ "def", "decode_response_body", "(", "response", ")", "check_response_status_code", "(", "response", ")", "body", "=", "MultiJson", ".", "load", "(", "response", ".", "body", ",", ":symbolize_keys", "=>", "true", ")", "check_body_error", "(", "response", ",", "body", ")", "body", "end" ]
Extract and parse body response as hash. Throw an error if there is something wrong with the response. @param [Hurley::Response] response Web API response. @return [Hash] Response body as hash. The hash key will be symbolized.
[ "Extract", "and", "parse", "body", "response", "as", "hash", ".", "Throw", "an", "error", "if", "there", "is", "something", "wrong", "with", "the", "response", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L243-L248
866
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/client.rb
GoogleMapsService.Client.check_response_status_code
def check_response_status_code(response) case response.status_code when 200..300 # Do-nothing when 301, 302, 303, 307 raise GoogleMapsService::Error::RedirectError.new(response), sprintf('Redirect to %s', response.header[:location]) when 401 raise GoogleMapsService::Error::ClientError.new(response), 'Unauthorized' when 304, 400, 402...500 raise GoogleMapsService::Error::ClientError.new(response), 'Invalid request' when 500..600 raise GoogleMapsService::Error::ServerError.new(response), 'Server error' end end
ruby
def check_response_status_code(response) case response.status_code when 200..300 # Do-nothing when 301, 302, 303, 307 raise GoogleMapsService::Error::RedirectError.new(response), sprintf('Redirect to %s', response.header[:location]) when 401 raise GoogleMapsService::Error::ClientError.new(response), 'Unauthorized' when 304, 400, 402...500 raise GoogleMapsService::Error::ClientError.new(response), 'Invalid request' when 500..600 raise GoogleMapsService::Error::ServerError.new(response), 'Server error' end end
[ "def", "check_response_status_code", "(", "response", ")", "case", "response", ".", "status_code", "when", "200", "..", "300", "# Do-nothing", "when", "301", ",", "302", ",", "303", ",", "307", "raise", "GoogleMapsService", "::", "Error", "::", "RedirectError", ".", "new", "(", "response", ")", ",", "sprintf", "(", "'Redirect to %s'", ",", "response", ".", "header", "[", ":location", "]", ")", "when", "401", "raise", "GoogleMapsService", "::", "Error", "::", "ClientError", ".", "new", "(", "response", ")", ",", "'Unauthorized'", "when", "304", ",", "400", ",", "402", "...", "500", "raise", "GoogleMapsService", "::", "Error", "::", "ClientError", ".", "new", "(", "response", ")", ",", "'Invalid request'", "when", "500", "..", "600", "raise", "GoogleMapsService", "::", "Error", "::", "ServerError", ".", "new", "(", "response", ")", ",", "'Server error'", "end", "end" ]
Check HTTP response status code. Raise error if the status is not 2xx. @param [Hurley::Response] response Web API response.
[ "Check", "HTTP", "response", "status", "code", ".", "Raise", "error", "if", "the", "status", "is", "not", "2xx", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/client.rb#L253-L266
867
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/apis/directions.rb
GoogleMapsService::Apis.Directions.directions
def directions(origin, destination, mode: nil, waypoints: nil, alternatives: false, avoid: nil, language: nil, units: nil, region: nil, departure_time: nil, arrival_time: nil, optimize_waypoints: false, transit_mode: nil, transit_routing_preference: nil) params = { origin: GoogleMapsService::Convert.waypoint(origin), destination: GoogleMapsService::Convert.waypoint(destination) } params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode if waypoints = waypoints waypoints = GoogleMapsService::Convert.as_list(waypoints) waypoints = waypoints.map { |waypoint| GoogleMapsService::Convert.waypoint(waypoint) } waypoints = ['optimize:true'] + waypoints if optimize_waypoints params[:waypoints] = GoogleMapsService::Convert.join_list("|", waypoints) end params[:alternatives] = 'true' if alternatives params[:avoid] = GoogleMapsService::Convert.join_list('|', avoid) if avoid params[:language] = language if language params[:units] = units if units params[:region] = region if region params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time if departure_time and arrival_time raise ArgumentError, 'Should not specify both departure_time and arrival_time.' end params[:transit_mode] = GoogleMapsService::Convert.join_list("|", transit_mode) if transit_mode params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference return get('/maps/api/directions/json', params)[:routes] end
ruby
def directions(origin, destination, mode: nil, waypoints: nil, alternatives: false, avoid: nil, language: nil, units: nil, region: nil, departure_time: nil, arrival_time: nil, optimize_waypoints: false, transit_mode: nil, transit_routing_preference: nil) params = { origin: GoogleMapsService::Convert.waypoint(origin), destination: GoogleMapsService::Convert.waypoint(destination) } params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode if waypoints = waypoints waypoints = GoogleMapsService::Convert.as_list(waypoints) waypoints = waypoints.map { |waypoint| GoogleMapsService::Convert.waypoint(waypoint) } waypoints = ['optimize:true'] + waypoints if optimize_waypoints params[:waypoints] = GoogleMapsService::Convert.join_list("|", waypoints) end params[:alternatives] = 'true' if alternatives params[:avoid] = GoogleMapsService::Convert.join_list('|', avoid) if avoid params[:language] = language if language params[:units] = units if units params[:region] = region if region params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time if departure_time and arrival_time raise ArgumentError, 'Should not specify both departure_time and arrival_time.' end params[:transit_mode] = GoogleMapsService::Convert.join_list("|", transit_mode) if transit_mode params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference return get('/maps/api/directions/json', params)[:routes] end
[ "def", "directions", "(", "origin", ",", "destination", ",", "mode", ":", "nil", ",", "waypoints", ":", "nil", ",", "alternatives", ":", "false", ",", "avoid", ":", "nil", ",", "language", ":", "nil", ",", "units", ":", "nil", ",", "region", ":", "nil", ",", "departure_time", ":", "nil", ",", "arrival_time", ":", "nil", ",", "optimize_waypoints", ":", "false", ",", "transit_mode", ":", "nil", ",", "transit_routing_preference", ":", "nil", ")", "params", "=", "{", "origin", ":", "GoogleMapsService", "::", "Convert", ".", "waypoint", "(", "origin", ")", ",", "destination", ":", "GoogleMapsService", "::", "Convert", ".", "waypoint", "(", "destination", ")", "}", "params", "[", ":mode", "]", "=", "GoogleMapsService", "::", "Validator", ".", "travel_mode", "(", "mode", ")", "if", "mode", "if", "waypoints", "=", "waypoints", "waypoints", "=", "GoogleMapsService", "::", "Convert", ".", "as_list", "(", "waypoints", ")", "waypoints", "=", "waypoints", ".", "map", "{", "|", "waypoint", "|", "GoogleMapsService", "::", "Convert", ".", "waypoint", "(", "waypoint", ")", "}", "waypoints", "=", "[", "'optimize:true'", "]", "+", "waypoints", "if", "optimize_waypoints", "params", "[", ":waypoints", "]", "=", "GoogleMapsService", "::", "Convert", ".", "join_list", "(", "\"|\"", ",", "waypoints", ")", "end", "params", "[", ":alternatives", "]", "=", "'true'", "if", "alternatives", "params", "[", ":avoid", "]", "=", "GoogleMapsService", "::", "Convert", ".", "join_list", "(", "'|'", ",", "avoid", ")", "if", "avoid", "params", "[", ":language", "]", "=", "language", "if", "language", "params", "[", ":units", "]", "=", "units", "if", "units", "params", "[", ":region", "]", "=", "region", "if", "region", "params", "[", ":departure_time", "]", "=", "GoogleMapsService", "::", "Convert", ".", "time", "(", "departure_time", ")", "if", "departure_time", "params", "[", ":arrival_time", "]", "=", "GoogleMapsService", "::", "Convert", ".", "time", "(", "arrival_time", ")", "if", "arrival_time", "if", "departure_time", "and", "arrival_time", "raise", "ArgumentError", ",", "'Should not specify both departure_time and arrival_time.'", "end", "params", "[", ":transit_mode", "]", "=", "GoogleMapsService", "::", "Convert", ".", "join_list", "(", "\"|\"", ",", "transit_mode", ")", "if", "transit_mode", "params", "[", ":transit_routing_preference", "]", "=", "transit_routing_preference", "if", "transit_routing_preference", "return", "get", "(", "'/maps/api/directions/json'", ",", "params", ")", "[", ":routes", "]", "end" ]
Get directions between an origin point and a destination point. @example Simple directions routes = client.directions('Sydney', 'Melbourne') @example Complex bicycling directions routes = client.directions('Sydney', 'Melbourne', mode: 'bicycling', avoid: ['highways', 'tolls', 'ferries'], units: 'metric', region: 'au') @example Public transportation directions an_hour_from_now = Time.now - (1.0/24) routes = client.directions('Sydney Town Hall', 'Parramatta, NSW', mode: 'transit', arrival_time: an_hour_from_now) @example Walking with alternative routes routes = client.directions('Sydney Town Hall', 'Parramatta, NSW', mode: 'walking', alternatives: true) @param [String, Hash, Array] origin The address or latitude/longitude value from which you wish to calculate directions. @param [String, Hash, Array] destination The address or latitude/longitude value from which you wish to calculate directions. @param [String] mode Specifies the mode of transport to use when calculating directions. One of `driving`, `walking`, `bicycling` or `transit`. @param [Array<String>, Array<Hash>, Array<Array>] waypoints Specifies an array of waypoints. Waypoints alter a route by routing it through the specified location(s). @param [Boolean] alternatives If True, more than one route may be returned in the response. @param [Array, String] avoid Indicates that the calculated route(s) should avoid the indicated features. @param [String] language The language in which to return results. @param [String] units Specifies the unit system to use when displaying results. `metric` or `imperial`. @param [String] region The region code, specified as a ccTLD (_top-level domain_) two-character value. @param [Integer, DateTime] departure_time Specifies the desired time of departure. @param [Integer, DateTime] arrival_time Specifies the desired time of arrival for transit directions. Note: you can not specify both `departure_time` and `arrival_time`. @param [Boolean] optimize_waypoints Optimize the provided route by rearranging the waypoints in a more efficient order. @param [String, Array<String>] transit_mode Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the mode is transit. Valid values are `bus`, `subway`, `train`, `tram` or `rail`. `rail` is equivalent to `["train", "tram", "subway"]`. @param [String] transit_routing_preference Specifies preferences for transit requests. Valid values are `less_walking` or `fewer_transfers`. @return [Array] Array of routes.
[ "Get", "directions", "between", "an", "origin", "point", "and", "a", "destination", "point", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/directions.rb#L62-L99
868
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/apis/elevation.rb
GoogleMapsService::Apis.Elevation.elevation_along_path
def elevation_along_path(path, samples) if path.kind_of?(String) path = "enc:%s" % path else path = GoogleMapsService::Convert.waypoints(path) end params = { path: path, samples: samples } return get('/maps/api/elevation/json', params)[:results] end
ruby
def elevation_along_path(path, samples) if path.kind_of?(String) path = "enc:%s" % path else path = GoogleMapsService::Convert.waypoints(path) end params = { path: path, samples: samples } return get('/maps/api/elevation/json', params)[:results] end
[ "def", "elevation_along_path", "(", "path", ",", "samples", ")", "if", "path", ".", "kind_of?", "(", "String", ")", "path", "=", "\"enc:%s\"", "%", "path", "else", "path", "=", "GoogleMapsService", "::", "Convert", ".", "waypoints", "(", "path", ")", "end", "params", "=", "{", "path", ":", "path", ",", "samples", ":", "samples", "}", "return", "get", "(", "'/maps/api/elevation/json'", ",", "params", ")", "[", ":results", "]", "end" ]
Provides elevation data sampled along a path on the surface of the earth. @example Elevation along path locations = [[40.714728, -73.998672], [-34.397, 150.644]] results = client.elevation_along_path(locations, 5) @param [String, Array] path A encoded polyline string, or a list of latitude/longitude pairs from which you wish to calculate elevation data. @param [Integer] samples The number of sample points along a path for which to return elevation data. @return [Array] Array of elevation data responses
[ "Provides", "elevation", "data", "sampled", "along", "a", "path", "on", "the", "surface", "of", "the", "earth", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/elevation.rb#L43-L56
869
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/apis/roads.rb
GoogleMapsService::Apis.Roads.snap_to_roads
def snap_to_roads(path, interpolate: false) path = GoogleMapsService::Convert.waypoints(path) params = { path: path } params[:interpolate] = 'true' if interpolate return get('/v1/snapToRoads', params, base_url: ROADS_BASE_URL, accepts_client_id: false, custom_response_decoder: method(:extract_roads_body))[:snappedPoints] end
ruby
def snap_to_roads(path, interpolate: false) path = GoogleMapsService::Convert.waypoints(path) params = { path: path } params[:interpolate] = 'true' if interpolate return get('/v1/snapToRoads', params, base_url: ROADS_BASE_URL, accepts_client_id: false, custom_response_decoder: method(:extract_roads_body))[:snappedPoints] end
[ "def", "snap_to_roads", "(", "path", ",", "interpolate", ":", "false", ")", "path", "=", "GoogleMapsService", "::", "Convert", ".", "waypoints", "(", "path", ")", "params", "=", "{", "path", ":", "path", "}", "params", "[", ":interpolate", "]", "=", "'true'", "if", "interpolate", "return", "get", "(", "'/v1/snapToRoads'", ",", "params", ",", "base_url", ":", "ROADS_BASE_URL", ",", "accepts_client_id", ":", "false", ",", "custom_response_decoder", ":", "method", "(", ":extract_roads_body", ")", ")", "[", ":snappedPoints", "]", "end" ]
Snaps a path to the most likely roads travelled. Takes up to 100 GPS points collected along a route, and returns a similar set of data with the points snapped to the most likely roads the vehicle was traveling along. @example Single point snap results = client.snap_to_roads([40.714728, -73.998672]) @example Multi points snap path = [ [-33.8671, 151.20714], [-33.86708, 151.20683000000002], [-33.867070000000005, 151.20674000000002], [-33.86703, 151.20625] ] results = client.snap_to_roads(path, interpolate: true) @param [Array] path The path to be snapped. Array of latitude/longitude pairs. @param [Boolean] interpolate Whether to interpolate a path to include all points forming the full road-geometry. When true, additional interpolated points will also be returned, resulting in a path that smoothly follows the geometry of the road, even around corners and through tunnels. Interpolated paths may contain more points than the original path. @return [Array] Array of snapped points.
[ "Snaps", "a", "path", "to", "the", "most", "likely", "roads", "travelled", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L38-L51
870
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/apis/roads.rb
GoogleMapsService::Apis.Roads.nearest_roads
def nearest_roads(points) points = GoogleMapsService::Convert.waypoints(points) params = { points: points } return get('/v1/nearestRoads', params, base_url: ROADS_BASE_URL, accepts_client_id: false, custom_response_decoder: method(:extract_roads_body))[:snappedPoints] end
ruby
def nearest_roads(points) points = GoogleMapsService::Convert.waypoints(points) params = { points: points } return get('/v1/nearestRoads', params, base_url: ROADS_BASE_URL, accepts_client_id: false, custom_response_decoder: method(:extract_roads_body))[:snappedPoints] end
[ "def", "nearest_roads", "(", "points", ")", "points", "=", "GoogleMapsService", "::", "Convert", ".", "waypoints", "(", "points", ")", "params", "=", "{", "points", ":", "points", "}", "return", "get", "(", "'/v1/nearestRoads'", ",", "params", ",", "base_url", ":", "ROADS_BASE_URL", ",", "accepts_client_id", ":", "false", ",", "custom_response_decoder", ":", "method", "(", ":extract_roads_body", ")", ")", "[", ":snappedPoints", "]", "end" ]
Returns the nearest road segments for provided points. The points passed do not need to be part of a continuous path. @example Single point snap results = client.nearest_roads([40.714728, -73.998672]) @example Multi points snap points = [ [-33.8671, 151.20714], [-33.86708, 151.20683000000002], [-33.867070000000005, 151.20674000000002], [-33.86703, 151.20625] ] results = client.nearest_roads(points) @param [Array] points The points to be used for nearest road segment lookup. Array of latitude/longitude pairs which do not need to be a part of continuous part. Takes up to 100 independent coordinates, and returns the closest road segment for each point. @return [Array] Array of snapped points.
[ "Returns", "the", "nearest", "road", "segments", "for", "provided", "points", ".", "The", "points", "passed", "do", "not", "need", "to", "be", "part", "of", "a", "continuous", "path", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L128-L139
871
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/apis/roads.rb
GoogleMapsService::Apis.Roads.extract_roads_body
def extract_roads_body(response) begin body = MultiJson.load(response.body, :symbolize_keys => true) rescue unless response.status_code == 200 check_response_status_code(response) end raise GoogleMapsService::Error::ApiError.new(response), 'Received a malformed response.' end check_roads_body_error(response, body) unless response.status_code == 200 raise GoogleMapsService::Error::ApiError.new(response) end return body end
ruby
def extract_roads_body(response) begin body = MultiJson.load(response.body, :symbolize_keys => true) rescue unless response.status_code == 200 check_response_status_code(response) end raise GoogleMapsService::Error::ApiError.new(response), 'Received a malformed response.' end check_roads_body_error(response, body) unless response.status_code == 200 raise GoogleMapsService::Error::ApiError.new(response) end return body end
[ "def", "extract_roads_body", "(", "response", ")", "begin", "body", "=", "MultiJson", ".", "load", "(", "response", ".", "body", ",", ":symbolize_keys", "=>", "true", ")", "rescue", "unless", "response", ".", "status_code", "==", "200", "check_response_status_code", "(", "response", ")", "end", "raise", "GoogleMapsService", "::", "Error", "::", "ApiError", ".", "new", "(", "response", ")", ",", "'Received a malformed response.'", "end", "check_roads_body_error", "(", "response", ",", "body", ")", "unless", "response", ".", "status_code", "==", "200", "raise", "GoogleMapsService", "::", "Error", "::", "ApiError", ".", "new", "(", "response", ")", "end", "return", "body", "end" ]
Extracts a result from a Roads API HTTP response.
[ "Extracts", "a", "result", "from", "a", "Roads", "API", "HTTP", "response", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/apis/roads.rb#L145-L161
872
edwardsamuel/google-maps-services-ruby
lib/google_maps_service/polyline.rb
GoogleMapsService.Polyline.encode
def encode(points) last_lat = last_lng = 0 result = "" points.each do |point| ll = GoogleMapsService::Convert.normalize_latlng(point) lat = (ll[0] * 1e5).round.to_i lng = (ll[1] * 1e5).round.to_i d_lat = lat - last_lat d_lng = lng - last_lng [d_lat, d_lng].each do |v| v = (v < 0) ? ~(v << 1) : (v << 1) while v >= 0x20 result += ((0x20 | (v & 0x1f)) + 63).chr v >>= 5 end result += (v + 63).chr end last_lat = lat last_lng = lng end result end
ruby
def encode(points) last_lat = last_lng = 0 result = "" points.each do |point| ll = GoogleMapsService::Convert.normalize_latlng(point) lat = (ll[0] * 1e5).round.to_i lng = (ll[1] * 1e5).round.to_i d_lat = lat - last_lat d_lng = lng - last_lng [d_lat, d_lng].each do |v| v = (v < 0) ? ~(v << 1) : (v << 1) while v >= 0x20 result += ((0x20 | (v & 0x1f)) + 63).chr v >>= 5 end result += (v + 63).chr end last_lat = lat last_lng = lng end result end
[ "def", "encode", "(", "points", ")", "last_lat", "=", "last_lng", "=", "0", "result", "=", "\"\"", "points", ".", "each", "do", "|", "point", "|", "ll", "=", "GoogleMapsService", "::", "Convert", ".", "normalize_latlng", "(", "point", ")", "lat", "=", "(", "ll", "[", "0", "]", "*", "1e5", ")", ".", "round", ".", "to_i", "lng", "=", "(", "ll", "[", "1", "]", "*", "1e5", ")", ".", "round", ".", "to_i", "d_lat", "=", "lat", "-", "last_lat", "d_lng", "=", "lng", "-", "last_lng", "[", "d_lat", ",", "d_lng", "]", ".", "each", "do", "|", "v", "|", "v", "=", "(", "v", "<", "0", ")", "?", "~", "(", "v", "<<", "1", ")", ":", "(", "v", "<<", "1", ")", "while", "v", ">=", "0x20", "result", "+=", "(", "(", "0x20", "|", "(", "v", "&", "0x1f", ")", ")", "+", "63", ")", ".", "chr", "v", ">>=", "5", "end", "result", "+=", "(", "v", "+", "63", ")", ".", "chr", "end", "last_lat", "=", "lat", "last_lng", "=", "lng", "end", "result", "end" ]
Encodes a list of points into a polyline string. See the developer docs for a detailed description of this encoding: https://developers.google.com/maps/documentation/utilities/polylinealgorithm @param [Array<Hash>, Array<Array>] points A list of lat/lng pairs. @return [String]
[ "Encodes", "a", "list", "of", "points", "into", "a", "polyline", "string", "." ]
46746fd72e90c75855baa88aee04e41c84ff32c9
https://github.com/edwardsamuel/google-maps-services-ruby/blob/46746fd72e90c75855baa88aee04e41c84ff32c9/lib/google_maps_service/polyline.rb#L63-L88
873
mongoid/mongoid_fulltext
lib/mongoid/full_text_search.rb
Mongoid::FullTextSearch.ClassMethods.map_query_filters
def map_query_filters(filters) Hash[filters.map do |key, value| case value when Hash then if value.key? :any then format_query_filter('$in', key, value[:any]) elsif value.key? :all then format_query_filter('$all', key, value[:all]) else raise UnknownFilterQueryOperator, value.keys.join(','), caller end else format_query_filter('$all', key, value) end end] end
ruby
def map_query_filters(filters) Hash[filters.map do |key, value| case value when Hash then if value.key? :any then format_query_filter('$in', key, value[:any]) elsif value.key? :all then format_query_filter('$all', key, value[:all]) else raise UnknownFilterQueryOperator, value.keys.join(','), caller end else format_query_filter('$all', key, value) end end] end
[ "def", "map_query_filters", "(", "filters", ")", "Hash", "[", "filters", ".", "map", "do", "|", "key", ",", "value", "|", "case", "value", "when", "Hash", "then", "if", "value", ".", "key?", ":any", "then", "format_query_filter", "(", "'$in'", ",", "key", ",", "value", "[", ":any", "]", ")", "elsif", "value", ".", "key?", ":all", "then", "format_query_filter", "(", "'$all'", ",", "key", ",", "value", "[", ":all", "]", ")", "else", "raise", "UnknownFilterQueryOperator", ",", "value", ".", "keys", ".", "join", "(", "','", ")", ",", "caller", "end", "else", "format_query_filter", "(", "'$all'", ",", "key", ",", "value", ")", "end", "end", "]", "end" ]
Take a list of filters to be mapped so they can update the query used upon the fulltext search of the ngrams
[ "Take", "a", "list", "of", "filters", "to", "be", "mapped", "so", "they", "can", "update", "the", "query", "used", "upon", "the", "fulltext", "search", "of", "the", "ngrams" ]
3d212b0eaec2b93b54d9514603bc24b3b2594104
https://github.com/mongoid/mongoid_fulltext/blob/3d212b0eaec2b93b54d9514603bc24b3b2594104/lib/mongoid/full_text_search.rb#L300-L310
874
copiousfreetime/stickler
lib/stickler/spec_lite.rb
Stickler.SpecLite.=~
def =~(other) other = coerce( other ) return (other and self.name == other.name and self.version.to_s == other.version.to_s and self.platform_string == other.platform_string ) end
ruby
def =~(other) other = coerce( other ) return (other and self.name == other.name and self.version.to_s == other.version.to_s and self.platform_string == other.platform_string ) end
[ "def", "=~", "(", "other", ")", "other", "=", "coerce", "(", "other", ")", "return", "(", "other", "and", "self", ".", "name", "==", "other", ".", "name", "and", "self", ".", "version", ".", "to_s", "==", "other", ".", "version", ".", "to_s", "and", "self", ".", "platform_string", "==", "other", ".", "platform_string", ")", "end" ]
Lets be comparable! See if another Spec is the same as this spec
[ "Lets", "be", "comparable!" ]
9c9ef5b2287c0be071da0a233e2b262e98c878e5
https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/spec_lite.rb#L85-L91
875
copiousfreetime/stickler
lib/stickler/repository/remote_mirror.rb
::Stickler::Repository.RemoteMirror.mirror
def mirror( spec, upstream_host ) raise Stickler::Repository::Error, "gem #{spec.full_name} already exists in remote repository" if remote_gem_file_exist?( spec ) resource_request( mirror_resource( spec, upstream_host ) ) end
ruby
def mirror( spec, upstream_host ) raise Stickler::Repository::Error, "gem #{spec.full_name} already exists in remote repository" if remote_gem_file_exist?( spec ) resource_request( mirror_resource( spec, upstream_host ) ) end
[ "def", "mirror", "(", "spec", ",", "upstream_host", ")", "raise", "Stickler", "::", "Repository", "::", "Error", ",", "\"gem #{spec.full_name} already exists in remote repository\"", "if", "remote_gem_file_exist?", "(", "spec", ")", "resource_request", "(", "mirror_resource", "(", "spec", ",", "upstream_host", ")", ")", "end" ]
Tell the remote repoistory to mirror the given gem from an upstream repository
[ "Tell", "the", "remote", "repoistory", "to", "mirror", "the", "given", "gem", "from", "an", "upstream", "repository" ]
9c9ef5b2287c0be071da0a233e2b262e98c878e5
https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/repository/remote_mirror.rb#L14-L17
876
copiousfreetime/stickler
lib/stickler/middleware/index.rb
Stickler::Middleware.Index.marshalled_specs
def marshalled_specs( spec_a ) a = spec_a.collect { |s| s.to_rubygems_a } marshal( optimize_specs( a ) ) end
ruby
def marshalled_specs( spec_a ) a = spec_a.collect { |s| s.to_rubygems_a } marshal( optimize_specs( a ) ) end
[ "def", "marshalled_specs", "(", "spec_a", ")", "a", "=", "spec_a", ".", "collect", "{", "|", "s", "|", "s", ".", "to_rubygems_a", "}", "marshal", "(", "optimize_specs", "(", "a", ")", ")", "end" ]
Convert to the array format used by gem servers everywhere
[ "Convert", "to", "the", "array", "format", "used", "by", "gem", "servers", "everywhere" ]
9c9ef5b2287c0be071da0a233e2b262e98c878e5
https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/middleware/index.rb#L153-L156
877
copiousfreetime/stickler
lib/stickler/client.rb
Stickler.Client.parser
def parser me = self # scoping forces this @parser ||= Trollop::Parser.new do banner me.class.banner opt :server, "The gem or stickler server URL", :type => :string, :default => Client.config.server opt :debug, "Output debug information for the server interaction", :default => false end end
ruby
def parser me = self # scoping forces this @parser ||= Trollop::Parser.new do banner me.class.banner opt :server, "The gem or stickler server URL", :type => :string, :default => Client.config.server opt :debug, "Output debug information for the server interaction", :default => false end end
[ "def", "parser", "me", "=", "self", "# scoping forces this", "@parser", "||=", "Trollop", "::", "Parser", ".", "new", "do", "banner", "me", ".", "class", ".", "banner", "opt", ":server", ",", "\"The gem or stickler server URL\"", ",", ":type", "=>", ":string", ",", ":default", "=>", "Client", ".", "config", ".", "server", "opt", ":debug", ",", "\"Output debug information for the server interaction\"", ",", ":default", "=>", "false", "end", "end" ]
Create a new client Takes an argv like array as a parameter.
[ "Create", "a", "new", "client" ]
9c9ef5b2287c0be071da0a233e2b262e98c878e5
https://github.com/copiousfreetime/stickler/blob/9c9ef5b2287c0be071da0a233e2b262e98c878e5/lib/stickler/client.rb#L21-L28
878
janko/flickr-objects
lib/flickr/attributes.rb
Flickr.Attribute.find_value
def find_value(context) locations.each do |location| begin value = context.instance_exec(&location) next if value.nil? return value rescue end end nil end
ruby
def find_value(context) locations.each do |location| begin value = context.instance_exec(&location) next if value.nil? return value rescue end end nil end
[ "def", "find_value", "(", "context", ")", "locations", ".", "each", "do", "|", "location", "|", "begin", "value", "=", "context", ".", "instance_exec", "(", "location", ")", "next", "if", "value", ".", "nil?", "return", "value", "rescue", "end", "end", "nil", "end" ]
Finds attribute value in the JSON response by looking at the given locations.
[ "Finds", "attribute", "value", "in", "the", "JSON", "response", "by", "looking", "at", "the", "given", "locations", "." ]
dd25554e0002e76f4045542a9abdcdb754a94df6
https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/attributes.rb#L79-L90
879
janko/flickr-objects
lib/flickr/attributes.rb
Flickr.AttributeSet.add_locations
def add_locations(hash) hash.each do |attribute_name, locations| find(attribute_name).add_locations(locations) end end
ruby
def add_locations(hash) hash.each do |attribute_name, locations| find(attribute_name).add_locations(locations) end end
[ "def", "add_locations", "(", "hash", ")", "hash", ".", "each", "do", "|", "attribute_name", ",", "locations", "|", "find", "(", "attribute_name", ")", ".", "add_locations", "(", "locations", ")", "end", "end" ]
Shorthand for adding locations to multiple attributes at once.
[ "Shorthand", "for", "adding", "locations", "to", "multiple", "attributes", "at", "once", "." ]
dd25554e0002e76f4045542a9abdcdb754a94df6
https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/attributes.rb#L187-L191
880
janko/flickr-objects
spec/support/helpers.rb
Helpers.ClassMethods.record_api_methods
def record_api_methods before do stub_const("Flickr::Client::Data", Class.new(Flickr::Client::Data) do def do_request(http_method, flickr_method, params = {}) VCR.use_cassette(flickr_method) { super } end end) stub_const("Flickr::Client::Upload", Class.new(Flickr::Client::Upload) do def do_request(http_method, path, params = {}) if VCR.send(:cassettes).empty? VCR.use_cassette(path) { super } else super end end end) end end
ruby
def record_api_methods before do stub_const("Flickr::Client::Data", Class.new(Flickr::Client::Data) do def do_request(http_method, flickr_method, params = {}) VCR.use_cassette(flickr_method) { super } end end) stub_const("Flickr::Client::Upload", Class.new(Flickr::Client::Upload) do def do_request(http_method, path, params = {}) if VCR.send(:cassettes).empty? VCR.use_cassette(path) { super } else super end end end) end end
[ "def", "record_api_methods", "before", "do", "stub_const", "(", "\"Flickr::Client::Data\"", ",", "Class", ".", "new", "(", "Flickr", "::", "Client", "::", "Data", ")", "do", "def", "do_request", "(", "http_method", ",", "flickr_method", ",", "params", "=", "{", "}", ")", "VCR", ".", "use_cassette", "(", "flickr_method", ")", "{", "super", "}", "end", "end", ")", "stub_const", "(", "\"Flickr::Client::Upload\"", ",", "Class", ".", "new", "(", "Flickr", "::", "Client", "::", "Upload", ")", "do", "def", "do_request", "(", "http_method", ",", "path", ",", "params", "=", "{", "}", ")", "if", "VCR", ".", "send", "(", ":cassettes", ")", ".", "empty?", "VCR", ".", "use_cassette", "(", "path", ")", "{", "super", "}", "else", "super", "end", "end", "end", ")", "end", "end" ]
Wraps a VCR cassette around API calls with the same name as the Flickr method called. For example, the cassette for `Flickr.sets.create` will be called "flickr.photosets.create". Because we repeat the same API calls in different examples, we can just reuse those VCR cassettes rather than recording new ones.
[ "Wraps", "a", "VCR", "cassette", "around", "API", "calls", "with", "the", "same", "name", "as", "the", "Flickr", "method", "called", ".", "For", "example", "the", "cassette", "for", "Flickr", ".", "sets", ".", "create", "will", "be", "called", "flickr", ".", "photosets", ".", "create", ".", "Because", "we", "repeat", "the", "same", "API", "calls", "in", "different", "examples", "we", "can", "just", "reuse", "those", "VCR", "cassettes", "rather", "than", "recording", "new", "ones", "." ]
dd25554e0002e76f4045542a9abdcdb754a94df6
https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/spec/support/helpers.rb#L30-L48
881
janko/flickr-objects
lib/flickr/object.rb
Flickr.Object.inspect
def inspect attribute_values = self.class.attributes .inject({}) { |hash, attribute| hash.update(attribute.name => send(attribute.name)) } .reject { |name, value| value.nil? or (value.respond_to?(:empty?) and value.empty?) } attributes = attribute_values .map { |name, value| "#{name}=#{value.inspect}" } .join(" ") class_name = self.class.name hex_code = "0x#{(object_id >> 1).to_s(16)}" "#<#{class_name}:#{hex_code} #{attributes}>" end
ruby
def inspect attribute_values = self.class.attributes .inject({}) { |hash, attribute| hash.update(attribute.name => send(attribute.name)) } .reject { |name, value| value.nil? or (value.respond_to?(:empty?) and value.empty?) } attributes = attribute_values .map { |name, value| "#{name}=#{value.inspect}" } .join(" ") class_name = self.class.name hex_code = "0x#{(object_id >> 1).to_s(16)}" "#<#{class_name}:#{hex_code} #{attributes}>" end
[ "def", "inspect", "attribute_values", "=", "self", ".", "class", ".", "attributes", ".", "inject", "(", "{", "}", ")", "{", "|", "hash", ",", "attribute", "|", "hash", ".", "update", "(", "attribute", ".", "name", "=>", "send", "(", "attribute", ".", "name", ")", ")", "}", ".", "reject", "{", "|", "name", ",", "value", "|", "value", ".", "nil?", "or", "(", "value", ".", "respond_to?", "(", ":empty?", ")", "and", "value", ".", "empty?", ")", "}", "attributes", "=", "attribute_values", ".", "map", "{", "|", "name", ",", "value", "|", "\"#{name}=#{value.inspect}\"", "}", ".", "join", "(", "\" \"", ")", "class_name", "=", "self", ".", "class", ".", "name", "hex_code", "=", "\"0x#{(object_id >> 1).to_s(16)}\"", "\"#<#{class_name}:#{hex_code} #{attributes}>\"", "end" ]
Displays all the attributes and their values.
[ "Displays", "all", "the", "attributes", "and", "their", "values", "." ]
dd25554e0002e76f4045542a9abdcdb754a94df6
https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/object.rb#L85-L97
882
janko/flickr-objects
lib/flickr/sanitized_file.rb
Flickr.SanitizedFile.sanitize!
def sanitize! if rails_file? @file = @original @content_type = @original.content_type @path = @original.tempfile elsif sinatra_file? @file = @original[:tempfile] @content_type = @original[:type] @path = @original[:tempfile].path elsif io? @file = @original @content_type = @original.content_type if @original.respond_to?(:content_type) @path = @original.path if @original.respond_to?(:path) elsif string? @file = File.open(@original) @content_type = nil @path = @original else raise ArgumentError, "invalid file format" end end
ruby
def sanitize! if rails_file? @file = @original @content_type = @original.content_type @path = @original.tempfile elsif sinatra_file? @file = @original[:tempfile] @content_type = @original[:type] @path = @original[:tempfile].path elsif io? @file = @original @content_type = @original.content_type if @original.respond_to?(:content_type) @path = @original.path if @original.respond_to?(:path) elsif string? @file = File.open(@original) @content_type = nil @path = @original else raise ArgumentError, "invalid file format" end end
[ "def", "sanitize!", "if", "rails_file?", "@file", "=", "@original", "@content_type", "=", "@original", ".", "content_type", "@path", "=", "@original", ".", "tempfile", "elsif", "sinatra_file?", "@file", "=", "@original", "[", ":tempfile", "]", "@content_type", "=", "@original", "[", ":type", "]", "@path", "=", "@original", "[", ":tempfile", "]", ".", "path", "elsif", "io?", "@file", "=", "@original", "@content_type", "=", "@original", ".", "content_type", "if", "@original", ".", "respond_to?", "(", ":content_type", ")", "@path", "=", "@original", ".", "path", "if", "@original", ".", "respond_to?", "(", ":path", ")", "elsif", "string?", "@file", "=", "File", ".", "open", "(", "@original", ")", "@content_type", "=", "nil", "@path", "=", "@original", "else", "raise", "ArgumentError", ",", "\"invalid file format\"", "end", "end" ]
Extracts the tempfile, content type and path.
[ "Extracts", "the", "tempfile", "content", "type", "and", "path", "." ]
dd25554e0002e76f4045542a9abdcdb754a94df6
https://github.com/janko/flickr-objects/blob/dd25554e0002e76f4045542a9abdcdb754a94df6/lib/flickr/sanitized_file.rb#L30-L50
883
dei79/jquery-modal-rails
lib/jquery/modal/helpers/link_helpers.rb
Jquery.Helpers.link_to_modal
def link_to_modal(*args, &block) if block_given? options = args.first || {} html_options = args.second block_result = capture(&block) link_to_modal(block_result, options, html_options) else name = args[0] options = args[1] || {} html_options = args[2] || {} # extend the html_options html_options[:rel] = "modal:open" if (html_options.has_key?(:remote)) if (html_options[:remote] == true) html_options[:rel] = "modal:open:ajaxpost" end # remove the remote tag html_options.delete(:remote) end # check if we have an id html_options[:id] = UUIDTools::UUID.random_create().to_s unless html_options.has_key?(:id) # perform the normal link_to operation html_link = link_to(name, options, html_options) # emit both html_link.html_safe end end
ruby
def link_to_modal(*args, &block) if block_given? options = args.first || {} html_options = args.second block_result = capture(&block) link_to_modal(block_result, options, html_options) else name = args[0] options = args[1] || {} html_options = args[2] || {} # extend the html_options html_options[:rel] = "modal:open" if (html_options.has_key?(:remote)) if (html_options[:remote] == true) html_options[:rel] = "modal:open:ajaxpost" end # remove the remote tag html_options.delete(:remote) end # check if we have an id html_options[:id] = UUIDTools::UUID.random_create().to_s unless html_options.has_key?(:id) # perform the normal link_to operation html_link = link_to(name, options, html_options) # emit both html_link.html_safe end end
[ "def", "link_to_modal", "(", "*", "args", ",", "&", "block", ")", "if", "block_given?", "options", "=", "args", ".", "first", "||", "{", "}", "html_options", "=", "args", ".", "second", "block_result", "=", "capture", "(", "block", ")", "link_to_modal", "(", "block_result", ",", "options", ",", "html_options", ")", "else", "name", "=", "args", "[", "0", "]", "options", "=", "args", "[", "1", "]", "||", "{", "}", "html_options", "=", "args", "[", "2", "]", "||", "{", "}", "# extend the html_options", "html_options", "[", ":rel", "]", "=", "\"modal:open\"", "if", "(", "html_options", ".", "has_key?", "(", ":remote", ")", ")", "if", "(", "html_options", "[", ":remote", "]", "==", "true", ")", "html_options", "[", ":rel", "]", "=", "\"modal:open:ajaxpost\"", "end", "# remove the remote tag", "html_options", ".", "delete", "(", ":remote", ")", "end", "# check if we have an id", "html_options", "[", ":id", "]", "=", "UUIDTools", "::", "UUID", ".", "random_create", "(", ")", ".", "to_s", "unless", "html_options", ".", "has_key?", "(", ":id", ")", "# perform the normal link_to operation", "html_link", "=", "link_to", "(", "name", ",", "options", ",", "html_options", ")", "# emit both", "html_link", ".", "html_safe", "end", "end" ]
Creates a link tag to a given url or path and ensures that the linke will be rendered as jquery modal dialog ==== Signatures link_to(body, url, html_options = {}) link_to(body, url)
[ "Creates", "a", "link", "tag", "to", "a", "given", "url", "or", "path", "and", "ensures", "that", "the", "linke", "will", "be", "rendered", "as", "jquery", "modal", "dialog" ]
9aa5e120131108577cfeb9600dde7343d95a034f
https://github.com/dei79/jquery-modal-rails/blob/9aa5e120131108577cfeb9600dde7343d95a034f/lib/jquery/modal/helpers/link_helpers.rb#L12-L43
884
ashmaroli/jekyll-data
lib/jekyll-data/reader.rb
JekyllData.Reader.read_theme_data
def read_theme_data if @theme.data_path # # show contents of "<theme>/_data/" dir being read while degugging. inspect_theme_data theme_data = ThemeDataReader.new(site).read(site.config["data_dir"]) @site.data = Jekyll::Utils.deep_merge_hashes(theme_data, @site.data) # # show contents of merged site.data hash while debugging with # additional --show-data switch. inspect_merged_hash if site.config["show-data"] && site.config["verbose"] end end
ruby
def read_theme_data if @theme.data_path # # show contents of "<theme>/_data/" dir being read while degugging. inspect_theme_data theme_data = ThemeDataReader.new(site).read(site.config["data_dir"]) @site.data = Jekyll::Utils.deep_merge_hashes(theme_data, @site.data) # # show contents of merged site.data hash while debugging with # additional --show-data switch. inspect_merged_hash if site.config["show-data"] && site.config["verbose"] end end
[ "def", "read_theme_data", "if", "@theme", ".", "data_path", "#", "# show contents of \"<theme>/_data/\" dir being read while degugging.", "inspect_theme_data", "theme_data", "=", "ThemeDataReader", ".", "new", "(", "site", ")", ".", "read", "(", "site", ".", "config", "[", "\"data_dir\"", "]", ")", "@site", ".", "data", "=", "Jekyll", "::", "Utils", ".", "deep_merge_hashes", "(", "theme_data", ",", "@site", ".", "data", ")", "#", "# show contents of merged site.data hash while debugging with", "# additional --show-data switch.", "inspect_merged_hash", "if", "site", ".", "config", "[", "\"show-data\"", "]", "&&", "site", ".", "config", "[", "\"verbose\"", "]", "end", "end" ]
Read data files within a theme gem and add them to internal data Returns a hash appended with new data
[ "Read", "data", "files", "within", "a", "theme", "gem", "and", "add", "them", "to", "internal", "data" ]
7fb2b51db67c864c9e596a759c0df46efc78c86d
https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L25-L37
885
ashmaroli/jekyll-data
lib/jekyll-data/reader.rb
JekyllData.Reader.inspect_inner_hash
def inspect_inner_hash(hash) hash.each do |key, value| if value.is_a? Array print_label key extract_hashes_and_print value elsif value.is_a? Hash print_subkey_and_value key, value else print_hash key, value end end end
ruby
def inspect_inner_hash(hash) hash.each do |key, value| if value.is_a? Array print_label key extract_hashes_and_print value elsif value.is_a? Hash print_subkey_and_value key, value else print_hash key, value end end end
[ "def", "inspect_inner_hash", "(", "hash", ")", "hash", ".", "each", "do", "|", "key", ",", "value", "|", "if", "value", ".", "is_a?", "Array", "print_label", "key", "extract_hashes_and_print", "value", "elsif", "value", ".", "is_a?", "Hash", "print_subkey_and_value", "key", ",", "value", "else", "print_hash", "key", ",", "value", "end", "end", "end" ]
Analyse deeper hashes and extract contents to output
[ "Analyse", "deeper", "hashes", "and", "extract", "contents", "to", "output" ]
7fb2b51db67c864c9e596a759c0df46efc78c86d
https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L98-L109
886
ashmaroli/jekyll-data
lib/jekyll-data/reader.rb
JekyllData.Reader.print_subkey_and_value
def print_subkey_and_value(key, value) print_label key value.each do |subkey, val| if val.is_a? Hash print_inner_subkey subkey inspect_inner_hash val elsif val.is_a? Array print_inner_subkey subkey extract_hashes_and_print val elsif val.is_a? String print_hash subkey, val end end end
ruby
def print_subkey_and_value(key, value) print_label key value.each do |subkey, val| if val.is_a? Hash print_inner_subkey subkey inspect_inner_hash val elsif val.is_a? Array print_inner_subkey subkey extract_hashes_and_print val elsif val.is_a? String print_hash subkey, val end end end
[ "def", "print_subkey_and_value", "(", "key", ",", "value", ")", "print_label", "key", "value", ".", "each", "do", "|", "subkey", ",", "val", "|", "if", "val", ".", "is_a?", "Hash", "print_inner_subkey", "subkey", "inspect_inner_hash", "val", "elsif", "val", ".", "is_a?", "Array", "print_inner_subkey", "subkey", "extract_hashes_and_print", "val", "elsif", "val", ".", "is_a?", "String", "print_hash", "subkey", ",", "val", "end", "end", "end" ]
Prints label, keys and values of mappings
[ "Prints", "label", "keys", "and", "values", "of", "mappings" ]
7fb2b51db67c864c9e596a759c0df46efc78c86d
https://github.com/ashmaroli/jekyll-data/blob/7fb2b51db67c864c9e596a759c0df46efc78c86d/lib/jekyll-data/reader.rb#L176-L189
887
RubyDevInc/paho.mqtt.ruby
lib/paho_mqtt/connection_helper.rb
PahoMqtt.ConnectionHelper.should_send_ping?
def should_send_ping?(now, keep_alive, last_packet_received_at) last_pingreq_sent_at = @sender.last_pingreq_sent_at last_pingresp_received_at = @handler.last_pingresp_received_at if !last_pingreq_sent_at || (last_pingresp_received_at && (last_pingreq_sent_at <= last_pingresp_received_at)) next_pingreq_at = [@sender.last_packet_sent_at, last_packet_received_at].min + (keep_alive * 0.7).ceil return next_pingreq_at <= now end end
ruby
def should_send_ping?(now, keep_alive, last_packet_received_at) last_pingreq_sent_at = @sender.last_pingreq_sent_at last_pingresp_received_at = @handler.last_pingresp_received_at if !last_pingreq_sent_at || (last_pingresp_received_at && (last_pingreq_sent_at <= last_pingresp_received_at)) next_pingreq_at = [@sender.last_packet_sent_at, last_packet_received_at].min + (keep_alive * 0.7).ceil return next_pingreq_at <= now end end
[ "def", "should_send_ping?", "(", "now", ",", "keep_alive", ",", "last_packet_received_at", ")", "last_pingreq_sent_at", "=", "@sender", ".", "last_pingreq_sent_at", "last_pingresp_received_at", "=", "@handler", ".", "last_pingresp_received_at", "if", "!", "last_pingreq_sent_at", "||", "(", "last_pingresp_received_at", "&&", "(", "last_pingreq_sent_at", "<=", "last_pingresp_received_at", ")", ")", "next_pingreq_at", "=", "[", "@sender", ".", "last_packet_sent_at", ",", "last_packet_received_at", "]", ".", "min", "+", "(", "keep_alive", "*", "0.7", ")", ".", "ceil", "return", "next_pingreq_at", "<=", "now", "end", "end" ]
Would return 'true' if ping requset should be sent and 'nil' if not
[ "Would", "return", "true", "if", "ping", "requset", "should", "be", "sent", "and", "nil", "if", "not" ]
1a3a14ac5b646132829fb0f38c794cae503989d2
https://github.com/RubyDevInc/paho.mqtt.ruby/blob/1a3a14ac5b646132829fb0f38c794cae503989d2/lib/paho_mqtt/connection_helper.rb#L147-L154
888
morgoth/picasa
lib/picasa/utils.rb
Picasa.Utils.array_wrap
def array_wrap(object) if object.nil? [] elsif object.respond_to?(:to_ary) object.to_ary || [object] else [object] end end
ruby
def array_wrap(object) if object.nil? [] elsif object.respond_to?(:to_ary) object.to_ary || [object] else [object] end end
[ "def", "array_wrap", "(", "object", ")", "if", "object", ".", "nil?", "[", "]", "elsif", "object", ".", "respond_to?", "(", ":to_ary", ")", "object", ".", "to_ary", "||", "[", "object", "]", "else", "[", "object", "]", "end", "end" ]
Ported from activesupport gem
[ "Ported", "from", "activesupport", "gem" ]
94672fab0baa24eb2db9c6aba5b03920be9f98f2
https://github.com/morgoth/picasa/blob/94672fab0baa24eb2db9c6aba5b03920be9f98f2/lib/picasa/utils.rb#L26-L34
889
coderanger/rspec-command
lib/rspec_command/match_fixture.rb
RSpecCommand.MatchFixture.failure_message
def failure_message matching_files = @fixture.files & @local.files fixture_only_files = @fixture.files - @local.files local_only_files = @local.files - @fixture.files buf = "expected fixture #{@fixture.path} to match files:\n" (@fixture.files | @local.files).sort.each do |file| if matching_files.include?(file) local_file = @local.absolute(file) fixture_file = @fixture.absolute(file) if File.directory?(local_file) && File.directory?(fixture_file) # Do nothing elsif File.directory?(fixture_file) buf << " #{file} should be a directory\n" elsif File.directory?(local_file) buf << " #{file} should not be a directory" else actual = IO.read(local_file) expected = IO.read(fixture_file) if actual != expected # Show a diff buf << " #{file} does not match fixture:" buf << differ.diff(actual, expected).split(/\n/).map {|line| ' '+line }.join("\n") end end elsif fixture_only_files.include?(file) buf << " #{file} is not found\n" elsif local_only_files.include?(file) buf << " #{file} should not exist\n" end end buf end
ruby
def failure_message matching_files = @fixture.files & @local.files fixture_only_files = @fixture.files - @local.files local_only_files = @local.files - @fixture.files buf = "expected fixture #{@fixture.path} to match files:\n" (@fixture.files | @local.files).sort.each do |file| if matching_files.include?(file) local_file = @local.absolute(file) fixture_file = @fixture.absolute(file) if File.directory?(local_file) && File.directory?(fixture_file) # Do nothing elsif File.directory?(fixture_file) buf << " #{file} should be a directory\n" elsif File.directory?(local_file) buf << " #{file} should not be a directory" else actual = IO.read(local_file) expected = IO.read(fixture_file) if actual != expected # Show a diff buf << " #{file} does not match fixture:" buf << differ.diff(actual, expected).split(/\n/).map {|line| ' '+line }.join("\n") end end elsif fixture_only_files.include?(file) buf << " #{file} is not found\n" elsif local_only_files.include?(file) buf << " #{file} should not exist\n" end end buf end
[ "def", "failure_message", "matching_files", "=", "@fixture", ".", "files", "&", "@local", ".", "files", "fixture_only_files", "=", "@fixture", ".", "files", "-", "@local", ".", "files", "local_only_files", "=", "@local", ".", "files", "-", "@fixture", ".", "files", "buf", "=", "\"expected fixture #{@fixture.path} to match files:\\n\"", "(", "@fixture", ".", "files", "|", "@local", ".", "files", ")", ".", "sort", ".", "each", "do", "|", "file", "|", "if", "matching_files", ".", "include?", "(", "file", ")", "local_file", "=", "@local", ".", "absolute", "(", "file", ")", "fixture_file", "=", "@fixture", ".", "absolute", "(", "file", ")", "if", "File", ".", "directory?", "(", "local_file", ")", "&&", "File", ".", "directory?", "(", "fixture_file", ")", "# Do nothing", "elsif", "File", ".", "directory?", "(", "fixture_file", ")", "buf", "<<", "\" #{file} should be a directory\\n\"", "elsif", "File", ".", "directory?", "(", "local_file", ")", "buf", "<<", "\" #{file} should not be a directory\"", "else", "actual", "=", "IO", ".", "read", "(", "local_file", ")", "expected", "=", "IO", ".", "read", "(", "fixture_file", ")", "if", "actual", "!=", "expected", "# Show a diff", "buf", "<<", "\" #{file} does not match fixture:\"", "buf", "<<", "differ", ".", "diff", "(", "actual", ",", "expected", ")", ".", "split", "(", "/", "\\n", "/", ")", ".", "map", "{", "|", "line", "|", "' '", "+", "line", "}", ".", "join", "(", "\"\\n\"", ")", "end", "end", "elsif", "fixture_only_files", ".", "include?", "(", "file", ")", "buf", "<<", "\" #{file} is not found\\n\"", "elsif", "local_only_files", ".", "include?", "(", "file", ")", "buf", "<<", "\" #{file} should not exist\\n\"", "end", "end", "buf", "end" ]
Callback fro RSpec. Returns a human-readable failure message. @return [String]
[ "Callback", "fro", "RSpec", ".", "Returns", "a", "human", "-", "readable", "failure", "message", "." ]
3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9
https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command/match_fixture.rb#L51-L82
890
coderanger/rspec-command
lib/rspec_command/match_fixture.rb
RSpecCommand.MatchFixture.file_content_match?
def file_content_match? @fixture.full_files.zip(@local.full_files).all? do |fixture_file, local_file| if File.directory?(fixture_file) File.directory?(local_file) else !File.directory?(local_file) && IO.read(fixture_file) == IO.read(local_file) end end end
ruby
def file_content_match? @fixture.full_files.zip(@local.full_files).all? do |fixture_file, local_file| if File.directory?(fixture_file) File.directory?(local_file) else !File.directory?(local_file) && IO.read(fixture_file) == IO.read(local_file) end end end
[ "def", "file_content_match?", "@fixture", ".", "full_files", ".", "zip", "(", "@local", ".", "full_files", ")", ".", "all?", "do", "|", "fixture_file", ",", "local_file", "|", "if", "File", ".", "directory?", "(", "fixture_file", ")", "File", ".", "directory?", "(", "local_file", ")", "else", "!", "File", ".", "directory?", "(", "local_file", ")", "&&", "IO", ".", "read", "(", "fixture_file", ")", "==", "IO", ".", "read", "(", "local_file", ")", "end", "end", "end" ]
Do the file contents match? @return [Boolean]
[ "Do", "the", "file", "contents", "match?" ]
3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9
https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command/match_fixture.rb#L96-L104
891
coderanger/rspec-command
lib/rspec_command.rb
RSpecCommand.ClassMethods.file
def file(path, content=nil, &block) raise "file path should be relative the the temporary directory." if path == File.expand_path(path) before do content = instance_eval(&block) if block dest_path = File.join(temp_path, path) FileUtils.mkdir_p(File.dirname(dest_path)) IO.write(dest_path, content) end end
ruby
def file(path, content=nil, &block) raise "file path should be relative the the temporary directory." if path == File.expand_path(path) before do content = instance_eval(&block) if block dest_path = File.join(temp_path, path) FileUtils.mkdir_p(File.dirname(dest_path)) IO.write(dest_path, content) end end
[ "def", "file", "(", "path", ",", "content", "=", "nil", ",", "&", "block", ")", "raise", "\"file path should be relative the the temporary directory.\"", "if", "path", "==", "File", ".", "expand_path", "(", "path", ")", "before", "do", "content", "=", "instance_eval", "(", "block", ")", "if", "block", "dest_path", "=", "File", ".", "join", "(", "temp_path", ",", "path", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "dest_path", ")", ")", "IO", ".", "write", "(", "dest_path", ",", "content", ")", "end", "end" ]
Create a file in the temporary directory for this example. @param path [String] Path within the temporary directory to write to. @param content [String] File data to write. @param block [Proc] Optional block to return file data to write. @example describe 'myapp' do command 'myapp read data.txt' file 'data.txt', <<-EOH a thing EOH its(:exitstatus) { is_expected.to eq 0 } end
[ "Create", "a", "file", "in", "the", "temporary", "directory", "for", "this", "example", "." ]
3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9
https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L298-L306
892
coderanger/rspec-command
lib/rspec_command.rb
RSpecCommand.ClassMethods.fixture_file
def fixture_file(path, dest=nil) raise "file path should be relative the the temporary directory." if path == File.expand_path(path) before do |example| fixture_path = find_fixture(example.file_path, path) dest_path = dest ? File.join(temp_path, dest) : temp_path FileUtils.mkdir_p(dest_path) file_list = MatchFixture::FileList.new(fixture_path) file_list.files.each do |file| abs = file_list.absolute(file) if File.directory?(abs) FileUtils.mkdir_p(File.join(dest_path, file)) else FileUtils.copy(abs , File.join(dest_path, file), preserve: true) end end end end
ruby
def fixture_file(path, dest=nil) raise "file path should be relative the the temporary directory." if path == File.expand_path(path) before do |example| fixture_path = find_fixture(example.file_path, path) dest_path = dest ? File.join(temp_path, dest) : temp_path FileUtils.mkdir_p(dest_path) file_list = MatchFixture::FileList.new(fixture_path) file_list.files.each do |file| abs = file_list.absolute(file) if File.directory?(abs) FileUtils.mkdir_p(File.join(dest_path, file)) else FileUtils.copy(abs , File.join(dest_path, file), preserve: true) end end end end
[ "def", "fixture_file", "(", "path", ",", "dest", "=", "nil", ")", "raise", "\"file path should be relative the the temporary directory.\"", "if", "path", "==", "File", ".", "expand_path", "(", "path", ")", "before", "do", "|", "example", "|", "fixture_path", "=", "find_fixture", "(", "example", ".", "file_path", ",", "path", ")", "dest_path", "=", "dest", "?", "File", ".", "join", "(", "temp_path", ",", "dest", ")", ":", "temp_path", "FileUtils", ".", "mkdir_p", "(", "dest_path", ")", "file_list", "=", "MatchFixture", "::", "FileList", ".", "new", "(", "fixture_path", ")", "file_list", ".", "files", ".", "each", "do", "|", "file", "|", "abs", "=", "file_list", ".", "absolute", "(", "file", ")", "if", "File", ".", "directory?", "(", "abs", ")", "FileUtils", ".", "mkdir_p", "(", "File", ".", "join", "(", "dest_path", ",", "file", ")", ")", "else", "FileUtils", ".", "copy", "(", "abs", ",", "File", ".", "join", "(", "dest_path", ",", "file", ")", ",", "preserve", ":", "true", ")", "end", "end", "end", "end" ]
Copy fixture data from the spec folder to the temporary directory for this example. @param path [String] Path of the fixture to copy. @param dest [String] Optional destination path. By default the destination is the same as path. @example describe 'myapp' do command 'myapp run test/' fixture_file 'test' its(:exitstatus) { is_expected.to eq 0 } end
[ "Copy", "fixture", "data", "from", "the", "spec", "folder", "to", "the", "temporary", "directory", "for", "this", "example", "." ]
3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9
https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L320-L336
893
coderanger/rspec-command
lib/rspec_command.rb
RSpecCommand.ClassMethods.environment
def environment(variables) before do variables.each do |key, value| if value.nil? _environment.delete(key.to_s) else _environment[key.to_s] = value.to_s end end end end
ruby
def environment(variables) before do variables.each do |key, value| if value.nil? _environment.delete(key.to_s) else _environment[key.to_s] = value.to_s end end end end
[ "def", "environment", "(", "variables", ")", "before", "do", "variables", ".", "each", "do", "|", "key", ",", "value", "|", "if", "value", ".", "nil?", "_environment", ".", "delete", "(", "key", ".", "to_s", ")", "else", "_environment", "[", "key", ".", "to_s", "]", "=", "value", ".", "to_s", "end", "end", "end", "end" ]
Set an environment variable for this example. @param variables [Hash] Key/value pairs to set. @example describe 'myapp' do command 'myapp show' environment DEBUG: true its(:stderr) { is_expected.to include('[debug]') } end
[ "Set", "an", "environment", "variable", "for", "this", "example", "." ]
3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9
https://github.com/coderanger/rspec-command/blob/3fbcfbd5a8e8e1acc68da59f47f96471b8ff03e9/lib/rspec_command.rb#L347-L357
894
cheezy/data_magic
lib/data_magic/standard_translation.rb
DataMagic.StandardTranslation.randomize
def randomize(value) case value when Array then value[rand(value.size)] when Range then rand((value.last+1) - value.first) + value.first else value end end
ruby
def randomize(value) case value when Array then value[rand(value.size)] when Range then rand((value.last+1) - value.first) + value.first else value end end
[ "def", "randomize", "(", "value", ")", "case", "value", "when", "Array", "then", "value", "[", "rand", "(", "value", ".", "size", ")", "]", "when", "Range", "then", "rand", "(", "(", "value", ".", "last", "+", "1", ")", "-", "value", ".", "first", ")", "+", "value", ".", "first", "else", "value", "end", "end" ]
return a random value from an array or range
[ "return", "a", "random", "value", "from", "an", "array", "or", "range" ]
ac0dc18b319bf3974f9a79704a7636dbf55059ae
https://github.com/cheezy/data_magic/blob/ac0dc18b319bf3974f9a79704a7636dbf55059ae/lib/data_magic/standard_translation.rb#L236-L242
895
cheezy/data_magic
lib/data_magic/standard_translation.rb
DataMagic.StandardTranslation.sequential
def sequential(value) index = index_variable_for(value) index = (index ? index + 1 : 0) index = 0 if index == value.length set_index_variable(value, index) value[index] end
ruby
def sequential(value) index = index_variable_for(value) index = (index ? index + 1 : 0) index = 0 if index == value.length set_index_variable(value, index) value[index] end
[ "def", "sequential", "(", "value", ")", "index", "=", "index_variable_for", "(", "value", ")", "index", "=", "(", "index", "?", "index", "+", "1", ":", "0", ")", "index", "=", "0", "if", "index", "==", "value", ".", "length", "set_index_variable", "(", "value", ",", "index", ")", "value", "[", "index", "]", "end" ]
return an element from the array. The first request will return the first element, the second request will return the second, and so forth.
[ "return", "an", "element", "from", "the", "array", ".", "The", "first", "request", "will", "return", "the", "first", "element", "the", "second", "request", "will", "return", "the", "second", "and", "so", "forth", "." ]
ac0dc18b319bf3974f9a79704a7636dbf55059ae
https://github.com/cheezy/data_magic/blob/ac0dc18b319bf3974f9a79704a7636dbf55059ae/lib/data_magic/standard_translation.rb#L250-L256
896
matiasgagliano/action_access
lib/action_access/keeper.rb
ActionAccess.Keeper.let
def let(clearance_level, actions, resource, options = {}) clearance_level = clearance_level.to_s.singularize.to_sym actions = Array(actions).map(&:to_sym) controller = get_controller_name(resource, options) @rules[controller] ||= {} @rules[controller][clearance_level] ||= [] @rules[controller][clearance_level] += actions @rules[controller][clearance_level].uniq! return nil end
ruby
def let(clearance_level, actions, resource, options = {}) clearance_level = clearance_level.to_s.singularize.to_sym actions = Array(actions).map(&:to_sym) controller = get_controller_name(resource, options) @rules[controller] ||= {} @rules[controller][clearance_level] ||= [] @rules[controller][clearance_level] += actions @rules[controller][clearance_level].uniq! return nil end
[ "def", "let", "(", "clearance_level", ",", "actions", ",", "resource", ",", "options", "=", "{", "}", ")", "clearance_level", "=", "clearance_level", ".", "to_s", ".", "singularize", ".", "to_sym", "actions", "=", "Array", "(", "actions", ")", ".", "map", "(", ":to_sym", ")", "controller", "=", "get_controller_name", "(", "resource", ",", "options", ")", "@rules", "[", "controller", "]", "||=", "{", "}", "@rules", "[", "controller", "]", "[", "clearance_level", "]", "||=", "[", "]", "@rules", "[", "controller", "]", "[", "clearance_level", "]", "+=", "actions", "@rules", "[", "controller", "]", "[", "clearance_level", "]", ".", "uniq!", "return", "nil", "end" ]
Set clearance to perform actions over a resource. Clearance level and resource can be either plural or singular. == Examples: let :user, :show, :profile let :user, :show, @profile let :user, :show, ProfilesController # Any user can can access 'profiles#show'. let :admins, [:edit, :update], :articles, namespace: :admin let :admins, [:edit, :update], @admin_article let :admins, [:edit, :update], Admin::ArticlesController # Admins can access 'admin/articles#edit' and 'admin/articles#update'.
[ "Set", "clearance", "to", "perform", "actions", "over", "a", "resource", ".", "Clearance", "level", "and", "resource", "can", "be", "either", "plural", "or", "singular", "." ]
aa1db07489943e2d5f281fd76257884f52de9766
https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/keeper.rb#L24-L33
897
matiasgagliano/action_access
lib/action_access/keeper.rb
ActionAccess.Keeper.lets?
def lets?(clearance_level, action, resource, options = {}) clearance_level = clearance_level.to_s.singularize.to_sym action = action.to_sym controller = get_controller_name(resource, options) # Load the controller to ensure its rules are loaded (lazy loading rules). controller.constantize.new rules = @rules[controller] return false unless rules # Check rules Array(rules[:all]).include?(:all) || Array(rules[:all]).include?(action) || Array(rules[clearance_level]).include?(:all) || Array(rules[clearance_level]).include?(action) end
ruby
def lets?(clearance_level, action, resource, options = {}) clearance_level = clearance_level.to_s.singularize.to_sym action = action.to_sym controller = get_controller_name(resource, options) # Load the controller to ensure its rules are loaded (lazy loading rules). controller.constantize.new rules = @rules[controller] return false unless rules # Check rules Array(rules[:all]).include?(:all) || Array(rules[:all]).include?(action) || Array(rules[clearance_level]).include?(:all) || Array(rules[clearance_level]).include?(action) end
[ "def", "lets?", "(", "clearance_level", ",", "action", ",", "resource", ",", "options", "=", "{", "}", ")", "clearance_level", "=", "clearance_level", ".", "to_s", ".", "singularize", ".", "to_sym", "action", "=", "action", ".", "to_sym", "controller", "=", "get_controller_name", "(", "resource", ",", "options", ")", "# Load the controller to ensure its rules are loaded (lazy loading rules).", "controller", ".", "constantize", ".", "new", "rules", "=", "@rules", "[", "controller", "]", "return", "false", "unless", "rules", "# Check rules", "Array", "(", "rules", "[", ":all", "]", ")", ".", "include?", "(", ":all", ")", "||", "Array", "(", "rules", "[", ":all", "]", ")", ".", "include?", "(", "action", ")", "||", "Array", "(", "rules", "[", "clearance_level", "]", ")", ".", "include?", "(", ":all", ")", "||", "Array", "(", "rules", "[", "clearance_level", "]", ")", ".", "include?", "(", "action", ")", "end" ]
Check if a given clearance level allows to perform an action on a resource. Clearance level and resource can be either plural or singular. == Examples: lets? :users, :create, :profiles lets? :users, :create, @profile lets? :users, :create, ProfilesController # True if users are allowed to access 'profiles#create'. lets? :admin, :edit, :article, namespace: :admin lets? :admin, :edit, @admin_article lets? :admin, :edit, Admin::ArticlesController # True if any admin is allowed to access 'admin/articles#edit'.
[ "Check", "if", "a", "given", "clearance", "level", "allows", "to", "perform", "an", "action", "on", "a", "resource", ".", "Clearance", "level", "and", "resource", "can", "be", "either", "plural", "or", "singular", "." ]
aa1db07489943e2d5f281fd76257884f52de9766
https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/keeper.rb#L50-L65
898
matiasgagliano/action_access
lib/action_access/controller_additions.rb
ActionAccess.ControllerAdditions.validate_access!
def validate_access! action = self.action_name clearance_levels = Array(current_clearance_levels) authorized = clearance_levels.any? { |c| keeper.lets? c, action, self.class } not_authorized! unless authorized end
ruby
def validate_access! action = self.action_name clearance_levels = Array(current_clearance_levels) authorized = clearance_levels.any? { |c| keeper.lets? c, action, self.class } not_authorized! unless authorized end
[ "def", "validate_access!", "action", "=", "self", ".", "action_name", "clearance_levels", "=", "Array", "(", "current_clearance_levels", ")", "authorized", "=", "clearance_levels", ".", "any?", "{", "|", "c", "|", "keeper", ".", "lets?", "c", ",", "action", ",", "self", ".", "class", "}", "not_authorized!", "unless", "authorized", "end" ]
Validate access to the current route.
[ "Validate", "access", "to", "the", "current", "route", "." ]
aa1db07489943e2d5f281fd76257884f52de9766
https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/controller_additions.rb#L86-L91
899
matiasgagliano/action_access
lib/action_access/controller_additions.rb
ActionAccess.ControllerAdditions.not_authorized!
def not_authorized!(*args) options = args.extract_options! message = options[:message] || I18n.t('action_access.redirection_message', default: 'Not authorized.') path = options[:path] || unauthorized_access_redirection_path redirect_to path, alert: message end
ruby
def not_authorized!(*args) options = args.extract_options! message = options[:message] || I18n.t('action_access.redirection_message', default: 'Not authorized.') path = options[:path] || unauthorized_access_redirection_path redirect_to path, alert: message end
[ "def", "not_authorized!", "(", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "message", "=", "options", "[", ":message", "]", "||", "I18n", ".", "t", "(", "'action_access.redirection_message'", ",", "default", ":", "'Not authorized.'", ")", "path", "=", "options", "[", ":path", "]", "||", "unauthorized_access_redirection_path", "redirect_to", "path", ",", "alert", ":", "message", "end" ]
Redirect if not authorized. May be used inside action methods for finer control.
[ "Redirect", "if", "not", "authorized", ".", "May", "be", "used", "inside", "action", "methods", "for", "finer", "control", "." ]
aa1db07489943e2d5f281fd76257884f52de9766
https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/controller_additions.rb#L95-L101