id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
20,100
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.gem_signature
def gem_signature(gem_full_name) require 'digest' Digest::SHA256.new.hexdigest(@gems[gem_full_name].to_yaml).to_s end
ruby
def gem_signature(gem_full_name) require 'digest' Digest::SHA256.new.hexdigest(@gems[gem_full_name].to_yaml).to_s end
[ "def", "gem_signature", "(", "gem_full_name", ")", "require", "'digest'", "Digest", "::", "SHA256", ".", "new", ".", "hexdigest", "(", "@gems", "[", "gem_full_name", "]", ".", "to_yaml", ")", ".", "to_s", "end" ]
The signature for the given gem specification.
[ "The", "signature", "for", "the", "given", "gem", "specification", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L237-L241
20,101
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.find_name
def find_name(gem_name, version_requirement = Gem::Requirement.default) dep = Gem::Dependency.new gem_name, version_requirement search dep end
ruby
def find_name(gem_name, version_requirement = Gem::Requirement.default) dep = Gem::Dependency.new gem_name, version_requirement search dep end
[ "def", "find_name", "(", "gem_name", ",", "version_requirement", "=", "Gem", "::", "Requirement", ".", "default", ")", "dep", "=", "Gem", "::", "Dependency", ".", "new", "gem_name", ",", "version_requirement", "search", "dep", "end" ]
Find a gem by an exact match on the short name.
[ "Find", "a", "gem", "by", "an", "exact", "match", "on", "the", "short", "name", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L251-L254
20,102
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.update
def update(source_uri, all) source_uri = URI.parse source_uri unless URI::Generic === source_uri source_uri.path += '/' unless source_uri.path =~ /\/$/ use_incremental = false begin gem_names = fetch_quick_index source_uri, all remove_extra gem_names missing_gems = find_missing gem_names return false if missing_gems.size.zero? say "Missing metadata for #{missing_gems.size} gems" if missing_gems.size > 0 and Gem.configuration.really_verbose use_incremental = missing_gems.size <= Gem.configuration.bulk_threshold rescue Gem::OperationNotSupportedError => ex alert_error "Falling back to bulk fetch: #{ex.message}" if Gem.configuration.really_verbose use_incremental = false end if use_incremental then update_with_missing(source_uri, missing_gems) else new_index = fetch_bulk_index(source_uri) @gems.replace(new_index.gems) end true end
ruby
def update(source_uri, all) source_uri = URI.parse source_uri unless URI::Generic === source_uri source_uri.path += '/' unless source_uri.path =~ /\/$/ use_incremental = false begin gem_names = fetch_quick_index source_uri, all remove_extra gem_names missing_gems = find_missing gem_names return false if missing_gems.size.zero? say "Missing metadata for #{missing_gems.size} gems" if missing_gems.size > 0 and Gem.configuration.really_verbose use_incremental = missing_gems.size <= Gem.configuration.bulk_threshold rescue Gem::OperationNotSupportedError => ex alert_error "Falling back to bulk fetch: #{ex.message}" if Gem.configuration.really_verbose use_incremental = false end if use_incremental then update_with_missing(source_uri, missing_gems) else new_index = fetch_bulk_index(source_uri) @gems.replace(new_index.gems) end true end
[ "def", "update", "(", "source_uri", ",", "all", ")", "source_uri", "=", "URI", ".", "parse", "source_uri", "unless", "URI", "::", "Generic", "===", "source_uri", "source_uri", ".", "path", "+=", "'/'", "unless", "source_uri", ".", "path", "=~", "/", "\\/", "/", "use_incremental", "=", "false", "begin", "gem_names", "=", "fetch_quick_index", "source_uri", ",", "all", "remove_extra", "gem_names", "missing_gems", "=", "find_missing", "gem_names", "return", "false", "if", "missing_gems", ".", "size", ".", "zero?", "say", "\"Missing metadata for #{missing_gems.size} gems\"", "if", "missing_gems", ".", "size", ">", "0", "and", "Gem", ".", "configuration", ".", "really_verbose", "use_incremental", "=", "missing_gems", ".", "size", "<=", "Gem", ".", "configuration", ".", "bulk_threshold", "rescue", "Gem", "::", "OperationNotSupportedError", "=>", "ex", "alert_error", "\"Falling back to bulk fetch: #{ex.message}\"", "if", "Gem", ".", "configuration", ".", "really_verbose", "use_incremental", "=", "false", "end", "if", "use_incremental", "then", "update_with_missing", "(", "source_uri", ",", "missing_gems", ")", "else", "new_index", "=", "fetch_bulk_index", "(", "source_uri", ")", "@gems", ".", "replace", "(", "new_index", ".", "gems", ")", "end", "true", "end" ]
Updates this SourceIndex from +source_uri+. If +all+ is false, only the latest gems are fetched.
[ "Updates", "this", "SourceIndex", "from", "+", "source_uri", "+", ".", "If", "+", "all", "+", "is", "false", "only", "the", "latest", "gems", "are", "fetched", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L356-L387
20,103
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.fetch_quick_index
def fetch_quick_index(source_uri, all) index = all ? 'index' : 'latest_index' zipped_index = fetcher.fetch_path source_uri + "quick/#{index}.rz" unzip(zipped_index).split("\n") rescue ::Exception => e unless all then say "Latest index not found, using quick index" if Gem.configuration.really_verbose fetch_quick_index source_uri, true else raise Gem::OperationNotSupportedError, "No quick index found: #{e.message}" end end
ruby
def fetch_quick_index(source_uri, all) index = all ? 'index' : 'latest_index' zipped_index = fetcher.fetch_path source_uri + "quick/#{index}.rz" unzip(zipped_index).split("\n") rescue ::Exception => e unless all then say "Latest index not found, using quick index" if Gem.configuration.really_verbose fetch_quick_index source_uri, true else raise Gem::OperationNotSupportedError, "No quick index found: #{e.message}" end end
[ "def", "fetch_quick_index", "(", "source_uri", ",", "all", ")", "index", "=", "all", "?", "'index'", ":", "'latest_index'", "zipped_index", "=", "fetcher", ".", "fetch_path", "source_uri", "+", "\"quick/#{index}.rz\"", "unzip", "(", "zipped_index", ")", ".", "split", "(", "\"\\n\"", ")", "rescue", "::", "Exception", "=>", "e", "unless", "all", "then", "say", "\"Latest index not found, using quick index\"", "if", "Gem", ".", "configuration", ".", "really_verbose", "fetch_quick_index", "source_uri", ",", "true", "else", "raise", "Gem", "::", "OperationNotSupportedError", ",", "\"No quick index found: #{e.message}\"", "end", "end" ]
Get the quick index needed for incremental updates.
[ "Get", "the", "quick", "index", "needed", "for", "incremental", "updates", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L455-L471
20,104
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.find_missing
def find_missing(spec_names) unless defined? @originals then @originals = {} each do |full_name, spec| @originals[spec.original_name] = spec end end spec_names.find_all { |full_name| @originals[full_name].nil? } end
ruby
def find_missing(spec_names) unless defined? @originals then @originals = {} each do |full_name, spec| @originals[spec.original_name] = spec end end spec_names.find_all { |full_name| @originals[full_name].nil? } end
[ "def", "find_missing", "(", "spec_names", ")", "unless", "defined?", "@originals", "then", "@originals", "=", "{", "}", "each", "do", "|", "full_name", ",", "spec", "|", "@originals", "[", "spec", ".", "original_name", "]", "=", "spec", "end", "end", "spec_names", ".", "find_all", "{", "|", "full_name", "|", "@originals", "[", "full_name", "]", ".", "nil?", "}", "end" ]
Make a list of full names for all the missing gemspecs.
[ "Make", "a", "list", "of", "full", "names", "for", "all", "the", "missing", "gemspecs", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L476-L487
20,105
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.fetch_single_spec
def fetch_single_spec(source_uri, spec_name) @fetch_error = nil begin marshal_uri = source_uri + "quick/Marshal.#{Gem.marshal_version}/#{spec_name}.gemspec.rz" zipped = fetcher.fetch_path marshal_uri return Marshal.load(unzip(zipped)) rescue => ex @fetch_error = ex if Gem.configuration.really_verbose then say "unable to fetch marshal gemspec #{marshal_uri}: #{ex.class} - #{ex}" end end begin yaml_uri = source_uri + "quick/#{spec_name}.gemspec.rz" zipped = fetcher.fetch_path yaml_uri return YAML.load(unzip(zipped)) rescue => ex @fetch_error = ex if Gem.configuration.really_verbose then say "unable to fetch YAML gemspec #{yaml_uri}: #{ex.class} - #{ex}" end end nil end
ruby
def fetch_single_spec(source_uri, spec_name) @fetch_error = nil begin marshal_uri = source_uri + "quick/Marshal.#{Gem.marshal_version}/#{spec_name}.gemspec.rz" zipped = fetcher.fetch_path marshal_uri return Marshal.load(unzip(zipped)) rescue => ex @fetch_error = ex if Gem.configuration.really_verbose then say "unable to fetch marshal gemspec #{marshal_uri}: #{ex.class} - #{ex}" end end begin yaml_uri = source_uri + "quick/#{spec_name}.gemspec.rz" zipped = fetcher.fetch_path yaml_uri return YAML.load(unzip(zipped)) rescue => ex @fetch_error = ex if Gem.configuration.really_verbose then say "unable to fetch YAML gemspec #{yaml_uri}: #{ex.class} - #{ex}" end end nil end
[ "def", "fetch_single_spec", "(", "source_uri", ",", "spec_name", ")", "@fetch_error", "=", "nil", "begin", "marshal_uri", "=", "source_uri", "+", "\"quick/Marshal.#{Gem.marshal_version}/#{spec_name}.gemspec.rz\"", "zipped", "=", "fetcher", ".", "fetch_path", "marshal_uri", "return", "Marshal", ".", "load", "(", "unzip", "(", "zipped", ")", ")", "rescue", "=>", "ex", "@fetch_error", "=", "ex", "if", "Gem", ".", "configuration", ".", "really_verbose", "then", "say", "\"unable to fetch marshal gemspec #{marshal_uri}: #{ex.class} - #{ex}\"", "end", "end", "begin", "yaml_uri", "=", "source_uri", "+", "\"quick/#{spec_name}.gemspec.rz\"", "zipped", "=", "fetcher", ".", "fetch_path", "yaml_uri", "return", "YAML", ".", "load", "(", "unzip", "(", "zipped", ")", ")", "rescue", "=>", "ex", "@fetch_error", "=", "ex", "if", "Gem", ".", "configuration", ".", "really_verbose", "then", "say", "\"unable to fetch YAML gemspec #{yaml_uri}: #{ex.class} - #{ex}\"", "end", "end", "nil", "end" ]
Tries to fetch Marshal representation first, then YAML
[ "Tries", "to", "fetch", "Marshal", "representation", "first", "then", "YAML" ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L507-L534
20,106
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.update_with_missing
def update_with_missing(source_uri, missing_names) progress = ui.progress_reporter(missing_names.size, "Updating metadata for #{missing_names.size} gems from #{source_uri}") missing_names.each do |spec_name| gemspec = fetch_single_spec(source_uri, spec_name) if gemspec.nil? then ui.say "Failed to download spec #{spec_name} from #{source_uri}:\n" \ "\t#{@fetch_error.message}" else add_spec gemspec progress.updated spec_name end @fetch_error = nil end progress.done progress.count end
ruby
def update_with_missing(source_uri, missing_names) progress = ui.progress_reporter(missing_names.size, "Updating metadata for #{missing_names.size} gems from #{source_uri}") missing_names.each do |spec_name| gemspec = fetch_single_spec(source_uri, spec_name) if gemspec.nil? then ui.say "Failed to download spec #{spec_name} from #{source_uri}:\n" \ "\t#{@fetch_error.message}" else add_spec gemspec progress.updated spec_name end @fetch_error = nil end progress.done progress.count end
[ "def", "update_with_missing", "(", "source_uri", ",", "missing_names", ")", "progress", "=", "ui", ".", "progress_reporter", "(", "missing_names", ".", "size", ",", "\"Updating metadata for #{missing_names.size} gems from #{source_uri}\"", ")", "missing_names", ".", "each", "do", "|", "spec_name", "|", "gemspec", "=", "fetch_single_spec", "(", "source_uri", ",", "spec_name", ")", "if", "gemspec", ".", "nil?", "then", "ui", ".", "say", "\"Failed to download spec #{spec_name} from #{source_uri}:\\n\"", "\"\\t#{@fetch_error.message}\"", "else", "add_spec", "gemspec", "progress", ".", "updated", "spec_name", "end", "@fetch_error", "=", "nil", "end", "progress", ".", "done", "progress", ".", "count", "end" ]
Update the cached source index with the missing names.
[ "Update", "the", "cached", "source", "index", "with", "the", "missing", "names", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L539-L555
20,107
puppetlabs/beaker-rspec
lib/beaker-rspec/helpers/serverspec.rb
Specinfra::Backend.BeakerBase.ssh_exec!
def ssh_exec!(node, command) r = on node, command, { :acceptable_exit_codes => (0..127) } { :exit_status => r.exit_code, :stdout => r.stdout, :stderr => r.stderr } end
ruby
def ssh_exec!(node, command) r = on node, command, { :acceptable_exit_codes => (0..127) } { :exit_status => r.exit_code, :stdout => r.stdout, :stderr => r.stderr } end
[ "def", "ssh_exec!", "(", "node", ",", "command", ")", "r", "=", "on", "node", ",", "command", ",", "{", ":acceptable_exit_codes", "=>", "(", "0", "..", "127", ")", "}", "{", ":exit_status", "=>", "r", ".", "exit_code", ",", ":stdout", "=>", "r", ".", "stdout", ",", ":stderr", "=>", "r", ".", "stderr", "}", "end" ]
Execute the provided ssh command @param [String] command The command to be executed @return [Hash] Returns a hash containing :exit_status, :stdout and :stderr
[ "Execute", "the", "provided", "ssh", "command" ]
6f45849544a10889c14b7bff6bb8171956ec2b56
https://github.com/puppetlabs/beaker-rspec/blob/6f45849544a10889c14b7bff6bb8171956ec2b56/lib/beaker-rspec/helpers/serverspec.rb#L187-L194
20,108
puppetlabs/beaker-rspec
lib/beaker-rspec/helpers/serverspec.rb
Specinfra::Backend.BeakerCygwin.run_command
def run_command(cmd, opt = {}) node = get_working_node script = create_script(cmd) #when node is not cygwin rm -rf will fail so lets use native del instead #There should be a better way to do this, but for now , this works if node.is_cygwin? delete_command = "rm -rf" redirection = "< /dev/null" else delete_command = "del" redirection = "< NUL" end on node, "#{delete_command} script.ps1" create_remote_file(node, 'script.ps1', script) #When using cmd on a pswindows node redirection should be set to < NUl #when using a cygwing one, /dev/null should be fine ret = ssh_exec!(node, "powershell.exe -File script.ps1 #{redirection}") if @example @example.metadata[:command] = script @example.metadata[:stdout] = ret[:stdout] end CommandResult.new ret end
ruby
def run_command(cmd, opt = {}) node = get_working_node script = create_script(cmd) #when node is not cygwin rm -rf will fail so lets use native del instead #There should be a better way to do this, but for now , this works if node.is_cygwin? delete_command = "rm -rf" redirection = "< /dev/null" else delete_command = "del" redirection = "< NUL" end on node, "#{delete_command} script.ps1" create_remote_file(node, 'script.ps1', script) #When using cmd on a pswindows node redirection should be set to < NUl #when using a cygwing one, /dev/null should be fine ret = ssh_exec!(node, "powershell.exe -File script.ps1 #{redirection}") if @example @example.metadata[:command] = script @example.metadata[:stdout] = ret[:stdout] end CommandResult.new ret end
[ "def", "run_command", "(", "cmd", ",", "opt", "=", "{", "}", ")", "node", "=", "get_working_node", "script", "=", "create_script", "(", "cmd", ")", "#when node is not cygwin rm -rf will fail so lets use native del instead", "#There should be a better way to do this, but for now , this works", "if", "node", ".", "is_cygwin?", "delete_command", "=", "\"rm -rf\"", "redirection", "=", "\"< /dev/null\"", "else", "delete_command", "=", "\"del\"", "redirection", "=", "\"< NUL\"", "end", "on", "node", ",", "\"#{delete_command} script.ps1\"", "create_remote_file", "(", "node", ",", "'script.ps1'", ",", "script", ")", "#When using cmd on a pswindows node redirection should be set to < NUl", "#when using a cygwing one, /dev/null should be fine", "ret", "=", "ssh_exec!", "(", "node", ",", "\"powershell.exe -File script.ps1 #{redirection}\"", ")", "if", "@example", "@example", ".", "metadata", "[", ":command", "]", "=", "script", "@example", ".", "metadata", "[", ":stdout", "]", "=", "ret", "[", ":stdout", "]", "end", "CommandResult", ".", "new", "ret", "end" ]
Run a windows style command using serverspec. Defaults to running on the 'default_node' test node, otherwise uses the node specified in @example.metadata[:node] @param [String] cmd The serverspec command to executed @param [Hash] opt No currently supported options @return [Hash] Returns a hash containing :exit_status, :stdout and :stderr
[ "Run", "a", "windows", "style", "command", "using", "serverspec", ".", "Defaults", "to", "running", "on", "the", "default_node", "test", "node", "otherwise", "uses", "the", "node", "specified", "in" ]
6f45849544a10889c14b7bff6bb8171956ec2b56
https://github.com/puppetlabs/beaker-rspec/blob/6f45849544a10889c14b7bff6bb8171956ec2b56/lib/beaker-rspec/helpers/serverspec.rb#L235-L259
20,109
puppetlabs/beaker-rspec
lib/beaker-rspec/helpers/serverspec.rb
Specinfra::Backend.BeakerExec.run_command
def run_command(cmd, opt = {}) node = get_working_node cmd = build_command(cmd) cmd = add_pre_command(cmd) ret = ssh_exec!(node, cmd) if @example @example.metadata[:command] = cmd @example.metadata[:stdout] = ret[:stdout] end CommandResult.new ret end
ruby
def run_command(cmd, opt = {}) node = get_working_node cmd = build_command(cmd) cmd = add_pre_command(cmd) ret = ssh_exec!(node, cmd) if @example @example.metadata[:command] = cmd @example.metadata[:stdout] = ret[:stdout] end CommandResult.new ret end
[ "def", "run_command", "(", "cmd", ",", "opt", "=", "{", "}", ")", "node", "=", "get_working_node", "cmd", "=", "build_command", "(", "cmd", ")", "cmd", "=", "add_pre_command", "(", "cmd", ")", "ret", "=", "ssh_exec!", "(", "node", ",", "cmd", ")", "if", "@example", "@example", ".", "metadata", "[", ":command", "]", "=", "cmd", "@example", ".", "metadata", "[", ":stdout", "]", "=", "ret", "[", ":stdout", "]", "end", "CommandResult", ".", "new", "ret", "end" ]
Run a unix style command using serverspec. Defaults to running on the 'default_node' test node, otherwise uses the node specified in @example.metadata[:node] @param [String] cmd The serverspec command to executed @param [Hash] opt No currently supported options @return [Hash] Returns a hash containing :exit_status, :stdout and :stderr
[ "Run", "a", "unix", "style", "command", "using", "serverspec", ".", "Defaults", "to", "running", "on", "the", "default_node", "test", "node", "otherwise", "uses", "the", "node", "specified", "in" ]
6f45849544a10889c14b7bff6bb8171956ec2b56
https://github.com/puppetlabs/beaker-rspec/blob/6f45849544a10889c14b7bff6bb8171956ec2b56/lib/beaker-rspec/helpers/serverspec.rb#L272-L284
20,110
puppetlabs/beaker-rspec
lib/beaker-rspec/beaker_shim.rb
BeakerRSpec.BeakerShim.setup
def setup(args = []) options_parser = Beaker::Options::Parser.new options = options_parser.parse_args(args) options[:debug] = true RSpec.configuration.logger = Beaker::Logger.new(options) options[:logger] = logger RSpec.configuration.hosts = [] RSpec.configuration.options = options end
ruby
def setup(args = []) options_parser = Beaker::Options::Parser.new options = options_parser.parse_args(args) options[:debug] = true RSpec.configuration.logger = Beaker::Logger.new(options) options[:logger] = logger RSpec.configuration.hosts = [] RSpec.configuration.options = options end
[ "def", "setup", "(", "args", "=", "[", "]", ")", "options_parser", "=", "Beaker", "::", "Options", "::", "Parser", ".", "new", "options", "=", "options_parser", ".", "parse_args", "(", "args", ")", "options", "[", ":debug", "]", "=", "true", "RSpec", ".", "configuration", ".", "logger", "=", "Beaker", "::", "Logger", ".", "new", "(", "options", ")", "options", "[", ":logger", "]", "=", "logger", "RSpec", ".", "configuration", ".", "hosts", "=", "[", "]", "RSpec", ".", "configuration", ".", "options", "=", "options", "end" ]
Setup the testing environment @param [Array<String>] args The argument array of options for configuring Beaker See 'beaker --help' for full list of supported command line options
[ "Setup", "the", "testing", "environment" ]
6f45849544a10889c14b7bff6bb8171956ec2b56
https://github.com/puppetlabs/beaker-rspec/blob/6f45849544a10889c14b7bff6bb8171956ec2b56/lib/beaker-rspec/beaker_shim.rb#L56-L64
20,111
qrush/m
lib/m/executor.rb
M.Executor.suites
def suites # Since we're not using `ruby -Itest -Ilib` to run the tests, we need to add this directory to the `LOAD_PATH` $:.unshift "./test", "./spec", "./lib" begin # Fire up this Ruby file. Let's hope it actually has tests. require "./#{testable.file}" rescue LoadError => e # Fail with a happier error message instead of spitting out a backtrace from this gem STDERR.puts "Failed loading test file:\n#{e.message}" return [] end suites = runner.suites # Use some janky internal APIs to group test methods by test suite. suites.each_with_object({}) do |suite_class, test_suites| # End up with a hash of suite class name to an array of test methods, so we can later find them and ignore empty test suites if runner.test_methods(suite_class).any? test_suites[suite_class] = runner.test_methods(suite_class) end end end
ruby
def suites # Since we're not using `ruby -Itest -Ilib` to run the tests, we need to add this directory to the `LOAD_PATH` $:.unshift "./test", "./spec", "./lib" begin # Fire up this Ruby file. Let's hope it actually has tests. require "./#{testable.file}" rescue LoadError => e # Fail with a happier error message instead of spitting out a backtrace from this gem STDERR.puts "Failed loading test file:\n#{e.message}" return [] end suites = runner.suites # Use some janky internal APIs to group test methods by test suite. suites.each_with_object({}) do |suite_class, test_suites| # End up with a hash of suite class name to an array of test methods, so we can later find them and ignore empty test suites if runner.test_methods(suite_class).any? test_suites[suite_class] = runner.test_methods(suite_class) end end end
[ "def", "suites", "# Since we're not using `ruby -Itest -Ilib` to run the tests, we need to add this directory to the `LOAD_PATH`", "$:", ".", "unshift", "\"./test\"", ",", "\"./spec\"", ",", "\"./lib\"", "begin", "# Fire up this Ruby file. Let's hope it actually has tests.", "require", "\"./#{testable.file}\"", "rescue", "LoadError", "=>", "e", "# Fail with a happier error message instead of spitting out a backtrace from this gem", "STDERR", ".", "puts", "\"Failed loading test file:\\n#{e.message}\"", "return", "[", "]", "end", "suites", "=", "runner", ".", "suites", "# Use some janky internal APIs to group test methods by test suite.", "suites", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "suite_class", ",", "test_suites", "|", "# End up with a hash of suite class name to an array of test methods, so we can later find them and ignore empty test suites", "if", "runner", ".", "test_methods", "(", "suite_class", ")", ".", "any?", "test_suites", "[", "suite_class", "]", "=", "runner", ".", "test_methods", "(", "suite_class", ")", "end", "end", "end" ]
Finds all test suites in this test file, with test methods included.
[ "Finds", "all", "test", "suites", "in", "this", "test", "file", "with", "test", "methods", "included", "." ]
9bcbf6120588bd8702046cb44c2f7d78aa2047db
https://github.com/qrush/m/blob/9bcbf6120588bd8702046cb44c2f7d78aa2047db/lib/m/executor.rb#L72-L94
20,112
tc/paypal_adaptive
lib/paypal_adaptive/response.rb
PaypalAdaptive.Response.approve_paypal_payment_url
def approve_paypal_payment_url(opts = {}) if opts.is_a?(Symbol) || opts.is_a?(String) warn "[DEPRECATION] use approve_paypal_payment_url(:type => #{opts})" opts = {:type => opts} end return nil if self['payKey'].nil? if ['mini', 'light'].include?(opts[:type].to_s) "#{@paypal_base_url}/webapps/adaptivepayment/flow/pay?expType=#{opts[:type]}&paykey=#{self['payKey']}" else base = @paypal_base_url base = base + "/#{opts[:country]}" if opts[:country] "#{base}/webscr?cmd=_ap-payment&paykey=#{self['payKey']}" end end
ruby
def approve_paypal_payment_url(opts = {}) if opts.is_a?(Symbol) || opts.is_a?(String) warn "[DEPRECATION] use approve_paypal_payment_url(:type => #{opts})" opts = {:type => opts} end return nil if self['payKey'].nil? if ['mini', 'light'].include?(opts[:type].to_s) "#{@paypal_base_url}/webapps/adaptivepayment/flow/pay?expType=#{opts[:type]}&paykey=#{self['payKey']}" else base = @paypal_base_url base = base + "/#{opts[:country]}" if opts[:country] "#{base}/webscr?cmd=_ap-payment&paykey=#{self['payKey']}" end end
[ "def", "approve_paypal_payment_url", "(", "opts", "=", "{", "}", ")", "if", "opts", ".", "is_a?", "(", "Symbol", ")", "||", "opts", ".", "is_a?", "(", "String", ")", "warn", "\"[DEPRECATION] use approve_paypal_payment_url(:type => #{opts})\"", "opts", "=", "{", ":type", "=>", "opts", "}", "end", "return", "nil", "if", "self", "[", "'payKey'", "]", ".", "nil?", "if", "[", "'mini'", ",", "'light'", "]", ".", "include?", "(", "opts", "[", ":type", "]", ".", "to_s", ")", "\"#{@paypal_base_url}/webapps/adaptivepayment/flow/pay?expType=#{opts[:type]}&paykey=#{self['payKey']}\"", "else", "base", "=", "@paypal_base_url", "base", "=", "base", "+", "\"/#{opts[:country]}\"", "if", "opts", "[", ":country", "]", "\"#{base}/webscr?cmd=_ap-payment&paykey=#{self['payKey']}\"", "end", "end" ]
URL to redirect to in order for the user to approve the payment options: * country: default country code for the user * type: mini / light
[ "URL", "to", "redirect", "to", "in", "order", "for", "the", "user", "to", "approve", "the", "payment" ]
cfd2c651057c407d844c470aa28d02b2bdec7579
https://github.com/tc/paypal_adaptive/blob/cfd2c651057c407d844c470aa28d02b2bdec7579/lib/paypal_adaptive/response.rb#L34-L48
20,113
assaf/scrapi
lib/scraper/base.rb
Scraper.Base.scrape
def scrape() # Call prepare with the document, but before doing anything else. prepare document # Retrieve the document. This may raise HTTPError or HTMLParseError. case document when Array stack = @document.reverse # see below when HTML::Node # If a root element is specified, start selecting from there. # The stack is empty if we can't find any root element (makes # sense). However, the node we're going to process may be # a tag, or an HTML::Document.root which is the equivalent of # a document fragment. root_element = option(:root_element) root = root_element ? @document.find(:tag=>root_element) : @document stack = root ? (root.tag? ? [root] : root.children.reverse) : [] else return end # @skip stores all the elements we want to skip (see #skip). # rules stores all the rules we want to process with this # scraper, based on the class definition. @skip = [] @stop = false rules = self.class.rules.clone begin # Process the document one node at a time. We process elements # from the end of the stack, so each time we visit child elements, # we add them to the end of the stack in reverse order. while node = stack.pop break if @stop skip_this = false # Only match nodes that are elements, ignore text nodes. # Also ignore any element that's on the skip list, and if # found one, remove it from the list (since we never visit # the same element twice). But an element may be added twice # to the skip list. # Note: equal? is faster than == for nodes. next unless node.tag? @skip.delete_if { |s| skip_this = true if s.equal?(node) } next if skip_this # Run through all the rules until we process the element or # run out of rules. If skip_this=true then we processed the # element and we can break out of the loop. However, we might # process (and skip) descedants so also watch the skip list. rules.delete_if do |selector, extractor, rule_name, first_only| break if skip_this # The result of calling match (selected) is nil, element # or array of elements. We turn it into an array to # process one element at a time. We process all elements # that are not on the skip list (we haven't visited # them yet). if selected = selector.match(node, first_only) selected = [selected] unless selected.is_a?(Array) selected = [selected.first] if first_only selected.each do |element| # Do not process elements we already skipped # (see above). However, this time we may visit # an element twice, since selected elements may # be descendants of the current element on the # stack. In rare cases two elements on the stack # may pick the same descendants. next if @skip.find { |s| s.equal?(element) } # Call the extractor method with this element. # If it returns true, skip the element and if # the current element, don't process any more # rules. Again, pay attention to descendants. if extractor.bind(self).call(element) @extracted = true end if @skip.delete(true) if element.equal?(node) skip_this = true else @skip << element end end end first_only if !selected.empty? end end # If we did not skip the element, we're going to process its # children. Reverse order since we're popping from the stack. if !skip_this && children = node.children stack.concat children.reverse end end ensure @skip = nil end collect return result end
ruby
def scrape() # Call prepare with the document, but before doing anything else. prepare document # Retrieve the document. This may raise HTTPError or HTMLParseError. case document when Array stack = @document.reverse # see below when HTML::Node # If a root element is specified, start selecting from there. # The stack is empty if we can't find any root element (makes # sense). However, the node we're going to process may be # a tag, or an HTML::Document.root which is the equivalent of # a document fragment. root_element = option(:root_element) root = root_element ? @document.find(:tag=>root_element) : @document stack = root ? (root.tag? ? [root] : root.children.reverse) : [] else return end # @skip stores all the elements we want to skip (see #skip). # rules stores all the rules we want to process with this # scraper, based on the class definition. @skip = [] @stop = false rules = self.class.rules.clone begin # Process the document one node at a time. We process elements # from the end of the stack, so each time we visit child elements, # we add them to the end of the stack in reverse order. while node = stack.pop break if @stop skip_this = false # Only match nodes that are elements, ignore text nodes. # Also ignore any element that's on the skip list, and if # found one, remove it from the list (since we never visit # the same element twice). But an element may be added twice # to the skip list. # Note: equal? is faster than == for nodes. next unless node.tag? @skip.delete_if { |s| skip_this = true if s.equal?(node) } next if skip_this # Run through all the rules until we process the element or # run out of rules. If skip_this=true then we processed the # element and we can break out of the loop. However, we might # process (and skip) descedants so also watch the skip list. rules.delete_if do |selector, extractor, rule_name, first_only| break if skip_this # The result of calling match (selected) is nil, element # or array of elements. We turn it into an array to # process one element at a time. We process all elements # that are not on the skip list (we haven't visited # them yet). if selected = selector.match(node, first_only) selected = [selected] unless selected.is_a?(Array) selected = [selected.first] if first_only selected.each do |element| # Do not process elements we already skipped # (see above). However, this time we may visit # an element twice, since selected elements may # be descendants of the current element on the # stack. In rare cases two elements on the stack # may pick the same descendants. next if @skip.find { |s| s.equal?(element) } # Call the extractor method with this element. # If it returns true, skip the element and if # the current element, don't process any more # rules. Again, pay attention to descendants. if extractor.bind(self).call(element) @extracted = true end if @skip.delete(true) if element.equal?(node) skip_this = true else @skip << element end end end first_only if !selected.empty? end end # If we did not skip the element, we're going to process its # children. Reverse order since we're popping from the stack. if !skip_this && children = node.children stack.concat children.reverse end end ensure @skip = nil end collect return result end
[ "def", "scrape", "(", ")", "# Call prepare with the document, but before doing anything else.", "prepare", "document", "# Retrieve the document. This may raise HTTPError or HTMLParseError.", "case", "document", "when", "Array", "stack", "=", "@document", ".", "reverse", "# see below", "when", "HTML", "::", "Node", "# If a root element is specified, start selecting from there.", "# The stack is empty if we can't find any root element (makes", "# sense). However, the node we're going to process may be", "# a tag, or an HTML::Document.root which is the equivalent of", "# a document fragment.", "root_element", "=", "option", "(", ":root_element", ")", "root", "=", "root_element", "?", "@document", ".", "find", "(", ":tag", "=>", "root_element", ")", ":", "@document", "stack", "=", "root", "?", "(", "root", ".", "tag?", "?", "[", "root", "]", ":", "root", ".", "children", ".", "reverse", ")", ":", "[", "]", "else", "return", "end", "# @skip stores all the elements we want to skip (see #skip).", "# rules stores all the rules we want to process with this", "# scraper, based on the class definition.", "@skip", "=", "[", "]", "@stop", "=", "false", "rules", "=", "self", ".", "class", ".", "rules", ".", "clone", "begin", "# Process the document one node at a time. We process elements", "# from the end of the stack, so each time we visit child elements,", "# we add them to the end of the stack in reverse order.", "while", "node", "=", "stack", ".", "pop", "break", "if", "@stop", "skip_this", "=", "false", "# Only match nodes that are elements, ignore text nodes.", "# Also ignore any element that's on the skip list, and if", "# found one, remove it from the list (since we never visit", "# the same element twice). But an element may be added twice", "# to the skip list.", "# Note: equal? is faster than == for nodes.", "next", "unless", "node", ".", "tag?", "@skip", ".", "delete_if", "{", "|", "s", "|", "skip_this", "=", "true", "if", "s", ".", "equal?", "(", "node", ")", "}", "next", "if", "skip_this", "# Run through all the rules until we process the element or", "# run out of rules. If skip_this=true then we processed the", "# element and we can break out of the loop. However, we might", "# process (and skip) descedants so also watch the skip list.", "rules", ".", "delete_if", "do", "|", "selector", ",", "extractor", ",", "rule_name", ",", "first_only", "|", "break", "if", "skip_this", "# The result of calling match (selected) is nil, element", "# or array of elements. We turn it into an array to", "# process one element at a time. We process all elements", "# that are not on the skip list (we haven't visited", "# them yet).", "if", "selected", "=", "selector", ".", "match", "(", "node", ",", "first_only", ")", "selected", "=", "[", "selected", "]", "unless", "selected", ".", "is_a?", "(", "Array", ")", "selected", "=", "[", "selected", ".", "first", "]", "if", "first_only", "selected", ".", "each", "do", "|", "element", "|", "# Do not process elements we already skipped", "# (see above). However, this time we may visit", "# an element twice, since selected elements may", "# be descendants of the current element on the", "# stack. In rare cases two elements on the stack", "# may pick the same descendants.", "next", "if", "@skip", ".", "find", "{", "|", "s", "|", "s", ".", "equal?", "(", "element", ")", "}", "# Call the extractor method with this element.", "# If it returns true, skip the element and if", "# the current element, don't process any more", "# rules. Again, pay attention to descendants.", "if", "extractor", ".", "bind", "(", "self", ")", ".", "call", "(", "element", ")", "@extracted", "=", "true", "end", "if", "@skip", ".", "delete", "(", "true", ")", "if", "element", ".", "equal?", "(", "node", ")", "skip_this", "=", "true", "else", "@skip", "<<", "element", "end", "end", "end", "first_only", "if", "!", "selected", ".", "empty?", "end", "end", "# If we did not skip the element, we're going to process its", "# children. Reverse order since we're popping from the stack.", "if", "!", "skip_this", "&&", "children", "=", "node", ".", "children", "stack", ".", "concat", "children", ".", "reverse", "end", "end", "ensure", "@skip", "=", "nil", "end", "collect", "return", "result", "end" ]
Create a new scraper instance. The argument +source+ is a URL, string containing HTML, or HTML::Node. The optional argument +options+ are options passed to the scraper. See Base#scrape for more details. For example: # The page we want to scrape url = URI.parse("http://example.com") # Skip the header scraper = MyScraper.new(url, :root_element=>"body") result = scraper.scrape Scrapes the document and returns the result. If the scraper was created with a URL, retrieve the page and parse it. If the scraper was created with a string, parse the page. The result is returned by calling the #result method. The default implementation returns +self+ if any extractor returned true, +nil+ otherwise. The method may raise any number of exceptions. HTTPError indicates it failed to retrieve the HTML page, and HTMLParseError that it failed to parse the page. Other exceptions come from extractors and the #result method. See also Base#scrape.
[ "Create", "a", "new", "scraper", "instance", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/scraper/base.rb#L747-L841
20,114
assaf/scrapi
lib/scraper/base.rb
Scraper.Base.document
def document if @document.is_a?(URI) # Attempt to read page. May raise HTTPError. options = {} READER_OPTIONS.each { |key| options[key] = option(key) } request(@document, options) end if @document.is_a?(String) # Parse the page. May raise HTMLParseError. parsed = Reader.parse_page(@document, @page_info.encoding, option(:parser_options), option(:parser)) @document = parsed.document @page_info.encoding = parsed.encoding end return @document if @document.is_a?(HTML::Node) raise RuntimeError, "No document to process" end
ruby
def document if @document.is_a?(URI) # Attempt to read page. May raise HTTPError. options = {} READER_OPTIONS.each { |key| options[key] = option(key) } request(@document, options) end if @document.is_a?(String) # Parse the page. May raise HTMLParseError. parsed = Reader.parse_page(@document, @page_info.encoding, option(:parser_options), option(:parser)) @document = parsed.document @page_info.encoding = parsed.encoding end return @document if @document.is_a?(HTML::Node) raise RuntimeError, "No document to process" end
[ "def", "document", "if", "@document", ".", "is_a?", "(", "URI", ")", "# Attempt to read page. May raise HTTPError.", "options", "=", "{", "}", "READER_OPTIONS", ".", "each", "{", "|", "key", "|", "options", "[", "key", "]", "=", "option", "(", "key", ")", "}", "request", "(", "@document", ",", "options", ")", "end", "if", "@document", ".", "is_a?", "(", "String", ")", "# Parse the page. May raise HTMLParseError.", "parsed", "=", "Reader", ".", "parse_page", "(", "@document", ",", "@page_info", ".", "encoding", ",", "option", "(", ":parser_options", ")", ",", "option", "(", ":parser", ")", ")", "@document", "=", "parsed", ".", "document", "@page_info", ".", "encoding", "=", "parsed", ".", "encoding", "end", "return", "@document", "if", "@document", ".", "is_a?", "(", "HTML", "::", "Node", ")", "raise", "RuntimeError", ",", "\"No document to process\"", "end" ]
Returns the document being processed. If the scraper was created with a URL, this method will attempt to retrieve the page and parse it. If the scraper was created with a string, this method will attempt to parse the page. Be advised that calling this method may raise an exception (HTTPError or HTMLParseError). The document is parsed only the first time this method is called.
[ "Returns", "the", "document", "being", "processed", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/scraper/base.rb#L856-L872
20,115
assaf/scrapi
lib/html/node_ext.rb
HTML.Node.next_sibling
def next_sibling() if siblings = parent.children siblings.each_with_index do |node, i| return siblings[i + 1] if node.equal?(self) end end nil end
ruby
def next_sibling() if siblings = parent.children siblings.each_with_index do |node, i| return siblings[i + 1] if node.equal?(self) end end nil end
[ "def", "next_sibling", "(", ")", "if", "siblings", "=", "parent", ".", "children", "siblings", ".", "each_with_index", "do", "|", "node", ",", "i", "|", "return", "siblings", "[", "i", "+", "1", "]", "if", "node", ".", "equal?", "(", "self", ")", "end", "end", "nil", "end" ]
Returns the next sibling node.
[ "Returns", "the", "next", "sibling", "node", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/node_ext.rb#L6-L13
20,116
assaf/scrapi
lib/html/node_ext.rb
HTML.Node.previous_sibling
def previous_sibling() if siblings = parent.children siblings.each_with_index do |node, i| return siblings[i - 1] if node.equal?(self) end end nil end
ruby
def previous_sibling() if siblings = parent.children siblings.each_with_index do |node, i| return siblings[i - 1] if node.equal?(self) end end nil end
[ "def", "previous_sibling", "(", ")", "if", "siblings", "=", "parent", ".", "children", "siblings", ".", "each_with_index", "do", "|", "node", ",", "i", "|", "return", "siblings", "[", "i", "-", "1", "]", "if", "node", ".", "equal?", "(", "self", ")", "end", "end", "nil", "end" ]
Returns the previous sibling node.
[ "Returns", "the", "previous", "sibling", "node", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/node_ext.rb#L17-L24
20,117
assaf/scrapi
lib/html/node_ext.rb
HTML.Node.previous_element
def previous_element(name = nil) if siblings = parent.children found = nil siblings.each do |node| return found if node.equal?(self) found = node if node.tag? && (name.nil? || node.name == name) end end nil end
ruby
def previous_element(name = nil) if siblings = parent.children found = nil siblings.each do |node| return found if node.equal?(self) found = node if node.tag? && (name.nil? || node.name == name) end end nil end
[ "def", "previous_element", "(", "name", "=", "nil", ")", "if", "siblings", "=", "parent", ".", "children", "found", "=", "nil", "siblings", ".", "each", "do", "|", "node", "|", "return", "found", "if", "node", ".", "equal?", "(", "self", ")", "found", "=", "node", "if", "node", ".", "tag?", "&&", "(", "name", ".", "nil?", "||", "node", ".", "name", "==", "name", ")", "end", "end", "nil", "end" ]
Return the previous element before this one. Skips sibling text nodes. Using the +name+ argument, returns the previous element with that name, skipping other sibling elements.
[ "Return", "the", "previous", "element", "before", "this", "one", ".", "Skips", "sibling", "text", "nodes", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/node_ext.rb#L51-L60
20,118
assaf/scrapi
lib/html/node_ext.rb
HTML.Node.each
def each(value = nil, &block) yield self, value if @children @children.each do |child| child.each value, &block end end value end
ruby
def each(value = nil, &block) yield self, value if @children @children.each do |child| child.each value, &block end end value end
[ "def", "each", "(", "value", "=", "nil", ",", "&", "block", ")", "yield", "self", ",", "value", "if", "@children", "@children", ".", "each", "do", "|", "child", "|", "child", ".", "each", "value", ",", "block", "end", "end", "value", "end" ]
Process each node beginning with the current node.
[ "Process", "each", "node", "beginning", "with", "the", "current", "node", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/node_ext.rb#L74-L82
20,119
assaf/scrapi
lib/html/tokenizer.rb
HTML.Tokenizer.scan_tag
def scan_tag tag = @scanner.getch if @scanner.scan(/!--/) # comment tag << @scanner.matched tag << (@scanner.scan_until(/--\s*>/) || @scanner.scan_until(/\Z/)) elsif @scanner.scan(/!\[CDATA\[/) tag << @scanner.matched tag << @scanner.scan_until(/\]\]>/) elsif @scanner.scan(/!/) # doctype tag << @scanner.matched tag << consume_quoted_regions else tag << consume_quoted_regions end tag end
ruby
def scan_tag tag = @scanner.getch if @scanner.scan(/!--/) # comment tag << @scanner.matched tag << (@scanner.scan_until(/--\s*>/) || @scanner.scan_until(/\Z/)) elsif @scanner.scan(/!\[CDATA\[/) tag << @scanner.matched tag << @scanner.scan_until(/\]\]>/) elsif @scanner.scan(/!/) # doctype tag << @scanner.matched tag << consume_quoted_regions else tag << consume_quoted_regions end tag end
[ "def", "scan_tag", "tag", "=", "@scanner", ".", "getch", "if", "@scanner", ".", "scan", "(", "/", "/", ")", "# comment", "tag", "<<", "@scanner", ".", "matched", "tag", "<<", "(", "@scanner", ".", "scan_until", "(", "/", "\\s", "/", ")", "||", "@scanner", ".", "scan_until", "(", "/", "\\Z", "/", ")", ")", "elsif", "@scanner", ".", "scan", "(", "/", "\\[", "\\[", "/", ")", "tag", "<<", "@scanner", ".", "matched", "tag", "<<", "@scanner", ".", "scan_until", "(", "/", "\\]", "\\]", "/", ")", "elsif", "@scanner", ".", "scan", "(", "/", "/", ")", "# doctype", "tag", "<<", "@scanner", ".", "matched", "tag", "<<", "consume_quoted_regions", "else", "tag", "<<", "consume_quoted_regions", "end", "tag", "end" ]
Treat the text at the current position as a tag, and scan it. Supports comments, doctype tags, and regular tags, and ignores less-than and greater-than characters within quoted strings.
[ "Treat", "the", "text", "at", "the", "current", "position", "as", "a", "tag", "and", "scan", "it", ".", "Supports", "comments", "doctype", "tags", "and", "regular", "tags", "and", "ignores", "less", "-", "than", "and", "greater", "-", "than", "characters", "within", "quoted", "strings", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/tokenizer.rb#L50-L65
20,120
assaf/scrapi
lib/html/selector.rb
HTML.Selector.next_element
def next_element(element, name = nil) if siblings = element.parent.children found = false siblings.each do |node| if node.equal?(element) found = true elsif found && node.tag? return node if (name.nil? || node.name == name) end end end nil end
ruby
def next_element(element, name = nil) if siblings = element.parent.children found = false siblings.each do |node| if node.equal?(element) found = true elsif found && node.tag? return node if (name.nil? || node.name == name) end end end nil end
[ "def", "next_element", "(", "element", ",", "name", "=", "nil", ")", "if", "siblings", "=", "element", ".", "parent", ".", "children", "found", "=", "false", "siblings", ".", "each", "do", "|", "node", "|", "if", "node", ".", "equal?", "(", "element", ")", "found", "=", "true", "elsif", "found", "&&", "node", ".", "tag?", "return", "node", "if", "(", "name", ".", "nil?", "||", "node", ".", "name", "==", "name", ")", "end", "end", "end", "nil", "end" ]
Return the next element after this one. Skips sibling text nodes. With the +name+ argument, returns the next element with that name, skipping other sibling elements.
[ "Return", "the", "next", "element", "after", "this", "one", ".", "Skips", "sibling", "text", "nodes", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/selector.rb#L490-L502
20,121
assaf/scrapi
lib/html/selector.rb
HTML.Selector.only_child
def only_child(of_type) lambda do |element| # Element must be inside parent element. return false unless element.parent and element.parent.tag? name = of_type ? element.name : nil other = false for child in element.parent.children # Skip text nodes/comments. if child.tag? and (name == nil or child.name == name) unless child.equal?(element) other = true break end end end !other end end
ruby
def only_child(of_type) lambda do |element| # Element must be inside parent element. return false unless element.parent and element.parent.tag? name = of_type ? element.name : nil other = false for child in element.parent.children # Skip text nodes/comments. if child.tag? and (name == nil or child.name == name) unless child.equal?(element) other = true break end end end !other end end
[ "def", "only_child", "(", "of_type", ")", "lambda", "do", "|", "element", "|", "# Element must be inside parent element.", "return", "false", "unless", "element", ".", "parent", "and", "element", ".", "parent", ".", "tag?", "name", "=", "of_type", "?", "element", ".", "name", ":", "nil", "other", "=", "false", "for", "child", "in", "element", ".", "parent", ".", "children", "# Skip text nodes/comments.", "if", "child", ".", "tag?", "and", "(", "name", "==", "nil", "or", "child", ".", "name", "==", "name", ")", "unless", "child", ".", "equal?", "(", "element", ")", "other", "=", "true", "break", "end", "end", "end", "!", "other", "end", "end" ]
Creates a only child lambda. Pass +of-type+ to only look at elements of its type.
[ "Creates", "a", "only", "child", "lambda", ".", "Pass", "+", "of", "-", "type", "+", "to", "only", "look", "at", "elements", "of", "its", "type", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/selector.rb#L769-L786
20,122
assaf/scrapi
lib/html/node.rb
HTML.Node.find_all
def find_all(conditions) conditions = validate_conditions(conditions) matches = [] matches << self if match(conditions) @children.each do |child| matches.concat child.find_all(conditions) end matches end
ruby
def find_all(conditions) conditions = validate_conditions(conditions) matches = [] matches << self if match(conditions) @children.each do |child| matches.concat child.find_all(conditions) end matches end
[ "def", "find_all", "(", "conditions", ")", "conditions", "=", "validate_conditions", "(", "conditions", ")", "matches", "=", "[", "]", "matches", "<<", "self", "if", "match", "(", "conditions", ")", "@children", ".", "each", "do", "|", "child", "|", "matches", ".", "concat", "child", ".", "find_all", "(", "conditions", ")", "end", "matches", "end" ]
Search for all nodes that match the given conditions, and return them as an array.
[ "Search", "for", "all", "nodes", "that", "match", "the", "given", "conditions", "and", "return", "them", "as", "an", "array", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/node.rb#L105-L114
20,123
assaf/scrapi
lib/html/node.rb
HTML.Tag.to_s
def to_s if @closing == :close "</#{@name}>" else s = "<#{@name}" @attributes.each do |k,v| s << " #{k}" s << "='#{v.gsub(/'/,"\\\\'")}'" if String === v end s << " /" if @closing == :self s << ">" @children.each { |child| s << child.to_s } s << "</#{@name}>" if @closing != :self && !@children.empty? s end end
ruby
def to_s if @closing == :close "</#{@name}>" else s = "<#{@name}" @attributes.each do |k,v| s << " #{k}" s << "='#{v.gsub(/'/,"\\\\'")}'" if String === v end s << " /" if @closing == :self s << ">" @children.each { |child| s << child.to_s } s << "</#{@name}>" if @closing != :self && !@children.empty? s end end
[ "def", "to_s", "if", "@closing", "==", ":close", "\"</#{@name}>\"", "else", "s", "=", "\"<#{@name}\"", "@attributes", ".", "each", "do", "|", "k", ",", "v", "|", "s", "<<", "\" #{k}\"", "s", "<<", "\"='#{v.gsub(/'/,\"\\\\\\\\'\")}'\"", "if", "String", "===", "v", "end", "s", "<<", "\" /\"", "if", "@closing", "==", ":self", "s", "<<", "\">\"", "@children", ".", "each", "{", "|", "child", "|", "s", "<<", "child", ".", "to_s", "}", "s", "<<", "\"</#{@name}>\"", "if", "@closing", "!=", ":self", "&&", "!", "@children", ".", "empty?", "s", "end", "end" ]
Returns a textual representation of the node
[ "Returns", "a", "textual", "representation", "of", "the", "node" ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/node.rb#L312-L327
20,124
assaf/scrapi
lib/html/node.rb
HTML.Tag.match_condition
def match_condition(value, condition) case condition when String value && value == condition when Regexp value && value.match(condition) when Numeric value == condition.to_s when true !value.nil? when false, nil value.nil? else false end end
ruby
def match_condition(value, condition) case condition when String value && value == condition when Regexp value && value.match(condition) when Numeric value == condition.to_s when true !value.nil? when false, nil value.nil? else false end end
[ "def", "match_condition", "(", "value", ",", "condition", ")", "case", "condition", "when", "String", "value", "&&", "value", "==", "condition", "when", "Regexp", "value", "&&", "value", ".", "match", "(", "condition", ")", "when", "Numeric", "value", "==", "condition", ".", "to_s", "when", "true", "!", "value", ".", "nil?", "when", "false", ",", "nil", "value", ".", "nil?", "else", "false", "end", "end" ]
Match the given value to the given condition.
[ "Match", "the", "given", "value", "to", "the", "given", "condition", "." ]
08f207ed740660bdf65730dd6bd3cb4df64e6d4b
https://github.com/assaf/scrapi/blob/08f207ed740660bdf65730dd6bd3cb4df64e6d4b/lib/html/node.rb#L517-L532
20,125
LoyaltyNZ/hoodoo
lib/hoodoo/client/client.rb
Hoodoo.Client.resource
def resource( resource, version = 1, options = {} ) endpoint_options = { :discoverer => @discoverer, :session_id => @session_id, :locale => options[ :locale ] || @locale } Hoodoo::Client::Headers::HEADER_TO_PROPERTY.each do | rack_header, description | property = description[ :property ] endpoint_options[ property ] = options[ property ] if options.has_key?( property ) end endpoint = Hoodoo::Client::Endpoint.endpoint_for( resource, version, endpoint_options ) unless @auto_session_endpoint.nil? remote_discovery_result = Hoodoo::Services::Discovery::ForRemote.new( :resource => resource, :version => version, :wrapped_endpoint => endpoint ) endpoint = Hoodoo::Client::Endpoint::AutoSession.new( resource, version, :caller_id => @caller_id, :caller_secret => @caller_secret, :session_endpoint => @auto_session_endpoint, :discovery_result => remote_discovery_result ) end return endpoint end
ruby
def resource( resource, version = 1, options = {} ) endpoint_options = { :discoverer => @discoverer, :session_id => @session_id, :locale => options[ :locale ] || @locale } Hoodoo::Client::Headers::HEADER_TO_PROPERTY.each do | rack_header, description | property = description[ :property ] endpoint_options[ property ] = options[ property ] if options.has_key?( property ) end endpoint = Hoodoo::Client::Endpoint.endpoint_for( resource, version, endpoint_options ) unless @auto_session_endpoint.nil? remote_discovery_result = Hoodoo::Services::Discovery::ForRemote.new( :resource => resource, :version => version, :wrapped_endpoint => endpoint ) endpoint = Hoodoo::Client::Endpoint::AutoSession.new( resource, version, :caller_id => @caller_id, :caller_secret => @caller_secret, :session_endpoint => @auto_session_endpoint, :discovery_result => remote_discovery_result ) end return endpoint end
[ "def", "resource", "(", "resource", ",", "version", "=", "1", ",", "options", "=", "{", "}", ")", "endpoint_options", "=", "{", ":discoverer", "=>", "@discoverer", ",", ":session_id", "=>", "@session_id", ",", ":locale", "=>", "options", "[", ":locale", "]", "||", "@locale", "}", "Hoodoo", "::", "Client", "::", "Headers", "::", "HEADER_TO_PROPERTY", ".", "each", "do", "|", "rack_header", ",", "description", "|", "property", "=", "description", "[", ":property", "]", "endpoint_options", "[", "property", "]", "=", "options", "[", "property", "]", "if", "options", ".", "has_key?", "(", "property", ")", "end", "endpoint", "=", "Hoodoo", "::", "Client", "::", "Endpoint", ".", "endpoint_for", "(", "resource", ",", "version", ",", "endpoint_options", ")", "unless", "@auto_session_endpoint", ".", "nil?", "remote_discovery_result", "=", "Hoodoo", "::", "Services", "::", "Discovery", "::", "ForRemote", ".", "new", "(", ":resource", "=>", "resource", ",", ":version", "=>", "version", ",", ":wrapped_endpoint", "=>", "endpoint", ")", "endpoint", "=", "Hoodoo", "::", "Client", "::", "Endpoint", "::", "AutoSession", ".", "new", "(", "resource", ",", "version", ",", ":caller_id", "=>", "@caller_id", ",", ":caller_secret", "=>", "@caller_secret", ",", ":session_endpoint", "=>", "@auto_session_endpoint", ",", ":discovery_result", "=>", "remote_discovery_result", ")", "end", "return", "endpoint", "end" ]
Create a client instance. This is used as a factory for endpoint instances which communicate with Resource implementations. == Overview Suppose you have Resources with only +public_actions+ so that no sessions are needed, with resource implementations running at host "test.com" on paths which follow downcase/pluralisation conventions. In this case, creating a Client instance can be as simple as: client = Hoodoo::Client.new( base_uri: 'http://test.com/', auto_session: false ) Ask this client for an endpoint of Resource "Member" implementing version 2 of its interface: members = client.resource( :Member, 2 ) Perform operations on the endpoints according to the methods in the base class - see these for details: * Hoodoo::Client::Endpoint#list * Hoodoo::Client::Endpoint#show * Hoodoo::Client::Endpoint#create * Hoodoo::Client::Endpoint#update * Hoodoo::Client::Endpoint#delete The above reference describes the basic approach for each call, with common parameters such as the query hash or body hash data described in the base class constructor, Hoodoo::Client::Endpoint#new. As an example, we could list records 50-79 inclusive of "Member" sorted by +created_at+ ascending, embedding an "account" for each, where field 'surname' matches 'Smith' - assuming there's an implementation of such a Resource interface available! - as follows: results = members.list( offset: 50, limit: 25, sort: 'created_at', direction: 'asc', search: { 'surname' => 'Smith' }, _embed: 'account' ) This will return a Hoodoo::Client::AugmentedArray. This is an Array subclass which will contain the (up to) 25 results from the above call and supports Hoodoo::Client::AugmentedArray#dataset_size which (if the called Resource endpoint implementation provides the information) gives the total size of the data set at the time of calling. Hoodoo::Client::AugmentedArray#estimated_dataset_size likewise gives access to the estimated count, if available. The other 4 methods return a Hoodoo::Client::AugmentedHash. This is a Hash subclass. Both the Array and Hash subclasses provide a common standard way to handle errors. See the documentation of these classes for details; in brief, you _must_ _always_ check for errors before examining the Hash or Array data with a pattern such as this: if results.platform_errors.has_errors? # Examine results.platform_errors, which is a # Hoodoo::Errors instance, and deal with the contents. else # Treat 'results' as a Hash containing the Resource # data (String keys) or Array of Hashes of such data. end == Session management By default, the Hoodoo::Client constructor assumes you want automatic session management. If you want to use automatic sessions, a Resource endpoint which implements the Session Resource interface is required. This must accept a POST (+create+) action with a payload of two JSON fields: +caller_id+ and +authentication_secret+. It must return a Resource with an "id" value that contains the session ID to quote in future requests via the X-Session-ID HTTP header; or it should return an error if the Caller ID and/or authentication secret are incorrect. The Resource is assumed to live at the same base URI and/or be discovered by the same mechanism (e.g. by convention) as everything else you'll use the client instance for. For more about discovery related paramters, see later. You will need to provide the +caller_id+ and +authentication_secret+ (as named parameter +caller_secret+) to the constructor. If the name of the Resource implementing the Session interface is not 'Session', or not at version 1, then you can also provide alternatives. For example, suppose we want to use automatic session management for Caller ID "0123" and secret "ABCD" via version 2 of "CustomSession": client = Hoodoo::Client.new( base_uri: 'http://test.com/', auto_session_resource: 'CustomSession', auto_session_version: 2, caller_id: '0123', caller_secret: 'ABCD' ) Finally, you can manually supply a session ID externally for the X-Session-ID header through the +session_id+ parameter. This may be used in conjunction with auto-session management; in that case, the given session is used until it expires (a "platform.invalid_session" error is encountered), after which a new one will be obtained. == Discovery parameters The Client instance needs to be able to find the place where the requested Resource implementations are located, which it does using the Hoodoo::Services::Discovery framework. You should read the description of this framework to get a feel for how that works first. One of the following *named* parameters must be supplied in order to choose a discovery engine for finding Resource endpoints: +discoverer+:: The Client needs a *Discoverer* to map from resource names and versions to locations on the Internet of the actual resource endpoint implementation. Via the +discoverer+ parameter, you can explicitly pass a Hoodoo::Services::Discovery subclass instance customised to your own requirements. There are also convenience parameters available - see below - that create discoverer instances for you, covering common use cases. If provided, the +discoverer+ parameter takes precedence over any other parameters below. +base_uri+:: When given, Resource discovery is done by Hoodoo::Services::Discovery::ByConvention. The path that the by-convention discoverer creates is appended to the base URI to build the full URI at which a server implementing each requested Resource endpoint must be listening (else a 404 / 'platform.not_found' response arises). Specify as a String. If provided, the +base_uri+ parameter takes precedence over any other parameters below. +drb_uri+:: When given, Resource discovery is done by Hoodoo::Services::Discovery::ByDRb. A DRb service providing discovery data must be running at the given URI. Specify as a String. See Hoodoo::Services::Discovery::ByDRb::DRbServer and file +drb_server_start.rb+ for more. +drb_port+:: Instead of +drb_uri+, you can provide the port number of a DRb server on localhost. See Hoodoo::Services::Discovery::ByDRb for which of +drb_uri+ or +drb_port+ take precedence, if both are provided. As an example of using a custom Discoverer, consider a simple HTTP case with the +base_uri+ parameter. The default "by convention" discoverer pluralises all paths, but let's say you have exceptions for Version and Health singleton resources which you've elected to place on singular, not plural, paths. You will need to construct a custom discoverer with these exceptions. See the documentation for Hoodoo::Services::Discovery::ByConvention to understand the options passed in for the custom routing information. base_uri = 'https://api.test.com/' discoverer = Hoodoo::Services::Discovery::ByConvention.new( :base_uri => base_uri, :routing => { :Version => { 1 => '/v1/version' }, :Health => { 1 => '/v1/health' } } ) client = Hoodoo::Client.new( :discoverer => discoverer, # ...other options... ) == Other parameters The following additional *named* parameters are all optional: +locale+:: The String given in Content-Language _and_ Accept-Language HTTP headers for requests; default is "en-nz". +session_id+:: An optional session ID to be used for the initial X-Session-ID request header value. +auto_session+:: If +false+, automatic session management is disabled. Default is +true+. +auto_session_resource+:: Name of the Resource to use for automatic session management as a String or Symbol. Default is +"Session"+. +auto_session_version+:: Version of the Resource to use for automatic session management as an Integer. Default is 1. +caller_id+:: If using automatic session management, a Caller UUID must be provided. It is used as the +caller_id+ field's value in the POST (+create+) call to the session Resource endpoint. +caller_secret+:: If using automatic session management, a Caller authentication secret must be provide. It is used as the +authentication_secret+ field's value in the POST (+create+) call to the session Resource endpoint. If curious about the implementation details of automatic session management, see the Hoodoo::Client::Endpoints::AutoSession class's code. Get an endpoint instance which you can use for talking to a Resource. See the constructor for full information. You'll always get an endpoint instance back from this call. If an implementation of the given version of the given Resource cannot be contacted, you will only get a 404 ('platform.not_found') or 408 ('platform.timeout') response when you try to make a call to it. +resource+:: Resource name as a Symbol or String (e.g. +:Purchase+). +version+:: Endpoint version as an Integer; optional; default is 1. +options+:: Optional options Hash (see below). The options Hash key/values are as follows: +locale+:: Locale string for request/response, e.g. "en-gb". Optional. If omitted, defaults to the locale set in this Client instance's constructor. OTHERS:: See Hoodoo::Client::Headers' +HEADER_TO_PROPERTY+. All such option keys _MUST_ be Symbols.
[ "Create", "a", "client", "instance", ".", "This", "is", "used", "as", "a", "factory", "for", "endpoint", "instances", "which", "communicate", "with", "Resource", "implementations", "." ]
905940121917ecbb66364bca3455b94b1636470f
https://github.com/LoyaltyNZ/hoodoo/blob/905940121917ecbb66364bca3455b94b1636470f/lib/hoodoo/client/client.rb#L319-L356
20,126
LoyaltyNZ/hoodoo
lib/hoodoo/logger/logger.rb
Hoodoo.Logger.remove
def remove( *writer_instances ) writer_instances.each do | writer_instance | communicator = @writers[ writer_instance ] @pool.remove( communicator ) unless communicator.nil? @writers.delete( writer_instance ) end end
ruby
def remove( *writer_instances ) writer_instances.each do | writer_instance | communicator = @writers[ writer_instance ] @pool.remove( communicator ) unless communicator.nil? @writers.delete( writer_instance ) end end
[ "def", "remove", "(", "*", "writer_instances", ")", "writer_instances", ".", "each", "do", "|", "writer_instance", "|", "communicator", "=", "@writers", "[", "writer_instance", "]", "@pool", ".", "remove", "(", "communicator", ")", "unless", "communicator", ".", "nil?", "@writers", ".", "delete", "(", "writer_instance", ")", "end", "end" ]
Remove a writer instance from this logger. If the instance has not been previously added, no error is raised. Slow writers may take a while to finish processing and shut down in the background. As a result, this method might take a while to return. Internal default timeouts may even mean that the writer is still running (possibly entirely hung). +writer_instances+:: One or more _instances_ of a subclass of Hoodoo::Logger::FastWriter or Hoodoo::Logger::SlowWriter, passed as one or more comma-separated parameters.
[ "Remove", "a", "writer", "instance", "from", "this", "logger", ".", "If", "the", "instance", "has", "not", "been", "previously", "added", "no", "error", "is", "raised", "." ]
905940121917ecbb66364bca3455b94b1636470f
https://github.com/LoyaltyNZ/hoodoo/blob/905940121917ecbb66364bca3455b94b1636470f/lib/hoodoo/logger/logger.rb#L111-L117
20,127
LoyaltyNZ/hoodoo
lib/hoodoo/logger/logger.rb
Hoodoo.Logger.include_class?
def include_class?( writer_class ) @writers.keys.each do | writer_instance | return true if writer_instance.is_a?( writer_class ) end return false end
ruby
def include_class?( writer_class ) @writers.keys.each do | writer_instance | return true if writer_instance.is_a?( writer_class ) end return false end
[ "def", "include_class?", "(", "writer_class", ")", "@writers", ".", "keys", ".", "each", "do", "|", "writer_instance", "|", "return", "true", "if", "writer_instance", ".", "is_a?", "(", "writer_class", ")", "end", "return", "false", "end" ]
Does this log instance's collection of writers include any writer instances which are of the given writer _class_? Returns +true+ if so, else +false+. This is slower than #include? so try to work with writer instance queries rather than writer class queries if you can. +writer_class+:: A _subclass_ (class reference, not instance) of Hoodoo::Logger::FastWriter or Hoodoo::Logger::SlowWriter.
[ "Does", "this", "log", "instance", "s", "collection", "of", "writers", "include", "any", "writer", "instances", "which", "are", "of", "the", "given", "writer", "_class_?", "Returns", "+", "true", "+", "if", "so", "else", "+", "false", "+", "." ]
905940121917ecbb66364bca3455b94b1636470f
https://github.com/LoyaltyNZ/hoodoo/blob/905940121917ecbb66364bca3455b94b1636470f/lib/hoodoo/logger/logger.rb#L155-L161
20,128
LoyaltyNZ/hoodoo
lib/hoodoo/errors/errors.rb
Hoodoo.Errors.add_error
def add_error( code, options = nil ) options = Hoodoo::Utilities.stringify( options || {} ) reference = options[ 'reference' ] || {} message = options[ 'message' ] # Make sure nobody uses an undeclared error code. raise UnknownCode, "In \#add_error: Unknown error code '#{code}'" unless @descriptions.recognised?( code ) # If the error description specifies a list of required reference keys, # make sure all are present and complain if not. description = @descriptions.describe( code ) required_keys = description[ 'reference' ] || [] actual_keys = reference.keys missing_keys = required_keys - actual_keys unless missing_keys.empty? raise MissingReferenceData, "In \#add_error: Reference hash missing required keys: '#{ missing_keys.join( ', ' ) }'" end # All good! @http_status_code = ( description[ 'status' ] || 200 ).to_i if @errors.empty? # Use first in collection for overall HTTP status code error = { 'code' => code, 'message' => message || description[ 'message' ] || code } ordered_keys = required_keys + ( actual_keys - required_keys ) ordered_values = ordered_keys.map { | key | escape_commas( reference[ key ].to_s ) } # See #unjoin_and_unescape_commas to undo the join below. error[ 'reference' ] = ordered_values.join( ',' ) unless ordered_values.empty? @errors << error end
ruby
def add_error( code, options = nil ) options = Hoodoo::Utilities.stringify( options || {} ) reference = options[ 'reference' ] || {} message = options[ 'message' ] # Make sure nobody uses an undeclared error code. raise UnknownCode, "In \#add_error: Unknown error code '#{code}'" unless @descriptions.recognised?( code ) # If the error description specifies a list of required reference keys, # make sure all are present and complain if not. description = @descriptions.describe( code ) required_keys = description[ 'reference' ] || [] actual_keys = reference.keys missing_keys = required_keys - actual_keys unless missing_keys.empty? raise MissingReferenceData, "In \#add_error: Reference hash missing required keys: '#{ missing_keys.join( ', ' ) }'" end # All good! @http_status_code = ( description[ 'status' ] || 200 ).to_i if @errors.empty? # Use first in collection for overall HTTP status code error = { 'code' => code, 'message' => message || description[ 'message' ] || code } ordered_keys = required_keys + ( actual_keys - required_keys ) ordered_values = ordered_keys.map { | key | escape_commas( reference[ key ].to_s ) } # See #unjoin_and_unescape_commas to undo the join below. error[ 'reference' ] = ordered_values.join( ',' ) unless ordered_values.empty? @errors << error end
[ "def", "add_error", "(", "code", ",", "options", "=", "nil", ")", "options", "=", "Hoodoo", "::", "Utilities", ".", "stringify", "(", "options", "||", "{", "}", ")", "reference", "=", "options", "[", "'reference'", "]", "||", "{", "}", "message", "=", "options", "[", "'message'", "]", "# Make sure nobody uses an undeclared error code.", "raise", "UnknownCode", ",", "\"In \\#add_error: Unknown error code '#{code}'\"", "unless", "@descriptions", ".", "recognised?", "(", "code", ")", "# If the error description specifies a list of required reference keys,", "# make sure all are present and complain if not.", "description", "=", "@descriptions", ".", "describe", "(", "code", ")", "required_keys", "=", "description", "[", "'reference'", "]", "||", "[", "]", "actual_keys", "=", "reference", ".", "keys", "missing_keys", "=", "required_keys", "-", "actual_keys", "unless", "missing_keys", ".", "empty?", "raise", "MissingReferenceData", ",", "\"In \\#add_error: Reference hash missing required keys: '#{ missing_keys.join( ', ' ) }'\"", "end", "# All good!", "@http_status_code", "=", "(", "description", "[", "'status'", "]", "||", "200", ")", ".", "to_i", "if", "@errors", ".", "empty?", "# Use first in collection for overall HTTP status code", "error", "=", "{", "'code'", "=>", "code", ",", "'message'", "=>", "message", "||", "description", "[", "'message'", "]", "||", "code", "}", "ordered_keys", "=", "required_keys", "+", "(", "actual_keys", "-", "required_keys", ")", "ordered_values", "=", "ordered_keys", ".", "map", "{", "|", "key", "|", "escape_commas", "(", "reference", "[", "key", "]", ".", "to_s", ")", "}", "# See #unjoin_and_unescape_commas to undo the join below.", "error", "[", "'reference'", "]", "=", "ordered_values", ".", "join", "(", "','", ")", "unless", "ordered_values", ".", "empty?", "@errors", "<<", "error", "end" ]
Create an instance. +descriptions+:: (Optional) Hoodoo::ErrorDescriptions instance with service-domain-specific error descriptions added, or omit for a default instance describing +platform+ and +generic+ error domains only. Add an error instance to this collection. +code+:: Error code in full, e.g. +generic.invalid_state'. +options+:: An options Hash, optional. The options hash contains symbol keys named as follows, with values as described: +reference+:: Reference data Hash, optionality depending upon the error code and the reference data its error description mandates. Provide key/value pairs where (symbol) keys are names from the array of description requirements and values are strings. All values are concatenated into a single string, comma-separated. Commas within values are escaped with a backslash; backslash is itself escaped with a backslash. You must provide that data at a minimum, but can provide additional keys too if you so wish. Required keys are always included first, in order of appearance in the requirements array of the error declaration, followed by any extra values in undefined order. See also Hoodoo::ErrorDescriptions::DomainDescriptions#error +message+:: Optional human-readable for-developer message, +en-nz+ locale. Default messages are provided for all errors, but if you think you can provide something more informative, you can do so through this parameter. Example: errors.add_error( 'platform.not_found', :message => 'Optional custom message', :reference => { :entity_name => 'mandatory reference data' } ) In the above example, the mandatory reference data +entity_name+ comes from the description for the 'platform.not_found' message - see the Hoodoo::ErrorDescriptions#initialize _implementation_ and Platform API.
[ "Create", "an", "instance", "." ]
905940121917ecbb66364bca3455b94b1636470f
https://github.com/LoyaltyNZ/hoodoo/blob/905940121917ecbb66364bca3455b94b1636470f/lib/hoodoo/errors/errors.rb#L121-L161
20,129
LoyaltyNZ/hoodoo
lib/hoodoo/errors/errors.rb
Hoodoo.Errors.add_precompiled_error
def add_precompiled_error( code, message, reference, http_status = 500 ) @http_status_code = http_status.to_i if @errors.empty? error = { 'code' => code, 'message' => message } error[ 'reference' ] = reference unless reference.nil? || reference.empty? @errors << error end
ruby
def add_precompiled_error( code, message, reference, http_status = 500 ) @http_status_code = http_status.to_i if @errors.empty? error = { 'code' => code, 'message' => message } error[ 'reference' ] = reference unless reference.nil? || reference.empty? @errors << error end
[ "def", "add_precompiled_error", "(", "code", ",", "message", ",", "reference", ",", "http_status", "=", "500", ")", "@http_status_code", "=", "http_status", ".", "to_i", "if", "@errors", ".", "empty?", "error", "=", "{", "'code'", "=>", "code", ",", "'message'", "=>", "message", "}", "error", "[", "'reference'", "]", "=", "reference", "unless", "reference", ".", "nil?", "||", "reference", ".", "empty?", "@errors", "<<", "error", "end" ]
Add a precompiled error to the error collection. Pass error code, error message and reference data directly. In most cases you should be calling #add_error instead, *NOT* here. *No* *validation* is performed. You should only really call here if storing an error / errors from another, trusted source with assumed validity (e.g. another service called remotely with errors in the JSON response). It's possible to store invalid error data using this call, which means counter-to-documentation results could be returned to API clients. That is Very Bad. Pass optionally the HTTP status code to use if this happens to be the first stored error. If this is omitted, 500 is kept as the default.
[ "Add", "a", "precompiled", "error", "to", "the", "error", "collection", ".", "Pass", "error", "code", "error", "message", "and", "reference", "data", "directly", "." ]
905940121917ecbb66364bca3455b94b1636470f
https://github.com/LoyaltyNZ/hoodoo/blob/905940121917ecbb66364bca3455b94b1636470f/lib/hoodoo/errors/errors.rb#L178-L189
20,130
LoyaltyNZ/hoodoo
lib/hoodoo/generator.rb
Hoodoo.Generator.run!
def run! git = nil path = nil return show_usage() if ARGV.length < 1 name = ARGV.shift() if ARGV.first[ 0 ] != '-' opts = GetoptLong.new( [ '--help', '-h', GetoptLong::NO_ARGUMENT ], [ '--version', '-v', '-V', GetoptLong::NO_ARGUMENT ], [ '--path', '-p', GetoptLong::REQUIRED_ARGUMENT ], [ '--from', '-f', GetoptLong::REQUIRED_ARGUMENT ], [ '--git', '-g', GetoptLong::REQUIRED_ARGUMENT ], ) silence_stream( $stderr ) do begin opts.each do | opt, arg | case opt when '--help' return show_usage() when '--version' return show_version() when '--path' path = arg when '--from', '--git' git = arg end end rescue GetoptLong::InvalidOption, GetoptLong::MissingArgument => e return usage_and_warning( e.message ) end end unless path.nil? || git.nil? return usage_and_warning( 'Use the --path OR --from arguments, but not both' ) end git ||= 'git@github.com:LoyaltyNZ/service_shell.git' name = ARGV.shift() if name.nil? return show_usage() if name.nil? return usage_and_warning( "Unexpected extra arguments were given" ) if ARGV.count > 0 return usage_and_warning( "SERVICE_NAME must match #{ NAME_REGEX.inspect }" ) if naughty_name?( name ) return usage_and_warning( "'#{ name }' already exists" ) if File.exist?( "./#{ name }" ) return create_service( name, git, path ) end
ruby
def run! git = nil path = nil return show_usage() if ARGV.length < 1 name = ARGV.shift() if ARGV.first[ 0 ] != '-' opts = GetoptLong.new( [ '--help', '-h', GetoptLong::NO_ARGUMENT ], [ '--version', '-v', '-V', GetoptLong::NO_ARGUMENT ], [ '--path', '-p', GetoptLong::REQUIRED_ARGUMENT ], [ '--from', '-f', GetoptLong::REQUIRED_ARGUMENT ], [ '--git', '-g', GetoptLong::REQUIRED_ARGUMENT ], ) silence_stream( $stderr ) do begin opts.each do | opt, arg | case opt when '--help' return show_usage() when '--version' return show_version() when '--path' path = arg when '--from', '--git' git = arg end end rescue GetoptLong::InvalidOption, GetoptLong::MissingArgument => e return usage_and_warning( e.message ) end end unless path.nil? || git.nil? return usage_and_warning( 'Use the --path OR --from arguments, but not both' ) end git ||= 'git@github.com:LoyaltyNZ/service_shell.git' name = ARGV.shift() if name.nil? return show_usage() if name.nil? return usage_and_warning( "Unexpected extra arguments were given" ) if ARGV.count > 0 return usage_and_warning( "SERVICE_NAME must match #{ NAME_REGEX.inspect }" ) if naughty_name?( name ) return usage_and_warning( "'#{ name }' already exists" ) if File.exist?( "./#{ name }" ) return create_service( name, git, path ) end
[ "def", "run!", "git", "=", "nil", "path", "=", "nil", "return", "show_usage", "(", ")", "if", "ARGV", ".", "length", "<", "1", "name", "=", "ARGV", ".", "shift", "(", ")", "if", "ARGV", ".", "first", "[", "0", "]", "!=", "'-'", "opts", "=", "GetoptLong", ".", "new", "(", "[", "'--help'", ",", "'-h'", ",", "GetoptLong", "::", "NO_ARGUMENT", "]", ",", "[", "'--version'", ",", "'-v'", ",", "'-V'", ",", "GetoptLong", "::", "NO_ARGUMENT", "]", ",", "[", "'--path'", ",", "'-p'", ",", "GetoptLong", "::", "REQUIRED_ARGUMENT", "]", ",", "[", "'--from'", ",", "'-f'", ",", "GetoptLong", "::", "REQUIRED_ARGUMENT", "]", ",", "[", "'--git'", ",", "'-g'", ",", "GetoptLong", "::", "REQUIRED_ARGUMENT", "]", ",", ")", "silence_stream", "(", "$stderr", ")", "do", "begin", "opts", ".", "each", "do", "|", "opt", ",", "arg", "|", "case", "opt", "when", "'--help'", "return", "show_usage", "(", ")", "when", "'--version'", "return", "show_version", "(", ")", "when", "'--path'", "path", "=", "arg", "when", "'--from'", ",", "'--git'", "git", "=", "arg", "end", "end", "rescue", "GetoptLong", "::", "InvalidOption", ",", "GetoptLong", "::", "MissingArgument", "=>", "e", "return", "usage_and_warning", "(", "e", ".", "message", ")", "end", "end", "unless", "path", ".", "nil?", "||", "git", ".", "nil?", "return", "usage_and_warning", "(", "'Use the --path OR --from arguments, but not both'", ")", "end", "git", "||=", "'git@github.com:LoyaltyNZ/service_shell.git'", "name", "=", "ARGV", ".", "shift", "(", ")", "if", "name", ".", "nil?", "return", "show_usage", "(", ")", "if", "name", ".", "nil?", "return", "usage_and_warning", "(", "\"Unexpected extra arguments were given\"", ")", "if", "ARGV", ".", "count", ">", "0", "return", "usage_and_warning", "(", "\"SERVICE_NAME must match #{ NAME_REGEX.inspect }\"", ")", "if", "naughty_name?", "(", "name", ")", "return", "usage_and_warning", "(", "\"'#{ name }' already exists\"", ")", "if", "File", ".", "exist?", "(", "\"./#{ name }\"", ")", "return", "create_service", "(", "name", ",", "git", ",", "path", ")", "end" ]
Run the +hoodoo+ command implementation. Command line options are taken from the Ruby ARGV constant.
[ "Run", "the", "+", "hoodoo", "+", "command", "implementation", ".", "Command", "line", "options", "are", "taken", "from", "the", "Ruby", "ARGV", "constant", "." ]
905940121917ecbb66364bca3455b94b1636470f
https://github.com/LoyaltyNZ/hoodoo/blob/905940121917ecbb66364bca3455b94b1636470f/lib/hoodoo/generator.rb#L43-L93
20,131
LoyaltyNZ/hoodoo
lib/hoodoo/transient_store/transient_store.rb
Hoodoo.TransientStore.set
def set( key:, payload:, maximum_lifespan: nil ) key = normalise_key( key, 'set' ) if payload.nil? raise "Hoodoo::TransientStore\#set: Payloads of 'nil' are prohibited" end maximum_lifespan ||= @default_maximum_lifespan begin result = @storage_engine_instance.set( key: key, payload: payload, maximum_lifespan: maximum_lifespan ) if result != true && result != false raise "Hoodoo::TransientStore\#set: Engine '#{ @storage_engine }' returned an invalid response" end rescue => e result = e end return result end
ruby
def set( key:, payload:, maximum_lifespan: nil ) key = normalise_key( key, 'set' ) if payload.nil? raise "Hoodoo::TransientStore\#set: Payloads of 'nil' are prohibited" end maximum_lifespan ||= @default_maximum_lifespan begin result = @storage_engine_instance.set( key: key, payload: payload, maximum_lifespan: maximum_lifespan ) if result != true && result != false raise "Hoodoo::TransientStore\#set: Engine '#{ @storage_engine }' returned an invalid response" end rescue => e result = e end return result end
[ "def", "set", "(", "key", ":", ",", "payload", ":", ",", "maximum_lifespan", ":", "nil", ")", "key", "=", "normalise_key", "(", "key", ",", "'set'", ")", "if", "payload", ".", "nil?", "raise", "\"Hoodoo::TransientStore\\#set: Payloads of 'nil' are prohibited\"", "end", "maximum_lifespan", "||=", "@default_maximum_lifespan", "begin", "result", "=", "@storage_engine_instance", ".", "set", "(", "key", ":", "key", ",", "payload", ":", "payload", ",", "maximum_lifespan", ":", "maximum_lifespan", ")", "if", "result", "!=", "true", "&&", "result", "!=", "false", "raise", "\"Hoodoo::TransientStore\\#set: Engine '#{ @storage_engine }' returned an invalid response\"", "end", "rescue", "=>", "e", "result", "=", "e", "end", "return", "result", "end" ]
Instantiate a new Transient storage object through which temporary data can be stored or retrieved. The TransientStore abstraction is a high level and simple abstraction over heterogenous data storage engines. It does not expose the many subtle configuration settings usually available in such. If you need to take advantage of those at an item storage level, you'll need to use a lower level interface and thus lock your code to the engine of choice. Engine plug-ins are recommended to attempt to gain and test a connection to the storage engine when this object is constructed, so if building a TransientStore instance, ensure your chosen storage engine is running first. Exceptions may be raised by storage engines, so you will probably want to catch those with more civilised error handling code. _Named_ parameters are: +storage_engine+:: An entry from ::supported_storage_engines. +storage_host_uri+:: The engine-dependent connection URI. Consult documentation for your chosen engine to find out its connection URI requirements, along with the documentation for the constructor method of the plug-in in use, since in some cases requirements may be unusual (e.g. in Hoodoo::TransientStore::MemcachedRedisMirror). +default_maximum_lifespan+:: The default time-to-live for data items, in, seconds; can be overridden per item; default is 604800 seconds or 7 days. +default_namespace+:: Storage engine keys are namespaced with +nz_co_loyalty_hoodoo_transient_store_+ by default, though this can be overridden here. Pass a String or Symbol. Set (write) a given payload into the storage engine with the given payload and maximum lifespan. Payloads must only contain simple types such as Hash, Array, String and Integer. Complex types like Symbol, Date, Float, BigDecimal or custom objects are unlikely to serialise properly but since this depends upon the storage engine in use, errors may or may not be raised for misuse. Storage engines usually have a maximum payload size limit; consult your engine administrator for information. For example, the default - but reconfigurable - maximum payload size for Memcached is 1MB. For maximum possible compatibility: * Use only Hash payloads with String key/value paids and no nesting. You may choose to marshal the data into a String manually for unusual data requirements, manually converting back when reading stored data. * Keep the payload size as small as possible - large objects belong in bulk storage engines such as Amazon S3. These are only guidelines though - heterogenous storage engine support and the ability of system administrators to arbitrarily configure those storage engines makes it impossible to be more precise. Returns: * +true+ if storage was successful * +false+ if storage failed but the reason is unknown * An +Exception+ instance if storage failed and the storage engine raised an exception describing the problem. _Named_ parameters are: +key+:: Storage key to use in the engine, which is then used in subsequent calls to #get and possibly eventually to #delete. Only non-empty Strings or Symbols are permitted, else an exception will be raised. +payload+:: Payload data to store under the given +key+. A flat Hash is recommended rather than simple types such as String (unless marshalling a complex type into such) in order to make potential additions to stored data easier to implement. Note that +nil+ is prohibited. +maximum_lifespan+:: Optional maximum lifespan, seconds. Storage engines may chooset to evict payloads sooner than this; it is a maximum time, not a guarantee. Omit to use this TransientStore instance's default value - see ::new. If you know you no longer need a piece of data at a particular point in the execution flow of your code, explicitly delete it via #delete rather than leaving it to expire. This maximises the storage engine's pool free space and so minimises the chance of early item eviction.
[ "Instantiate", "a", "new", "Transient", "storage", "object", "through", "which", "temporary", "data", "can", "be", "stored", "or", "retrieved", "." ]
905940121917ecbb66364bca3455b94b1636470f
https://github.com/LoyaltyNZ/hoodoo/blob/905940121917ecbb66364bca3455b94b1636470f/lib/hoodoo/transient_store/transient_store.rb#L227-L253
20,132
LoyaltyNZ/hoodoo
lib/hoodoo/transient_store/transient_store.rb
Hoodoo.TransientStore.normalise_key
def normalise_key( key, calling_method_name ) unless key.is_a?( String ) || key.is_a?( Symbol ) raise "Hoodoo::TransientStore\##{ calling_method_name }: Keys must be of String or Symbol class; you provided '#{ key.class }'" end key = key.to_s if key.empty? raise "Hoodoo::TransientStore\##{ calling_method_name }: Empty String or Symbol keys are prohibited" end return key end
ruby
def normalise_key( key, calling_method_name ) unless key.is_a?( String ) || key.is_a?( Symbol ) raise "Hoodoo::TransientStore\##{ calling_method_name }: Keys must be of String or Symbol class; you provided '#{ key.class }'" end key = key.to_s if key.empty? raise "Hoodoo::TransientStore\##{ calling_method_name }: Empty String or Symbol keys are prohibited" end return key end
[ "def", "normalise_key", "(", "key", ",", "calling_method_name", ")", "unless", "key", ".", "is_a?", "(", "String", ")", "||", "key", ".", "is_a?", "(", "Symbol", ")", "raise", "\"Hoodoo::TransientStore\\##{ calling_method_name }: Keys must be of String or Symbol class; you provided '#{ key.class }'\"", "end", "key", "=", "key", ".", "to_s", "if", "key", ".", "empty?", "raise", "\"Hoodoo::TransientStore\\##{ calling_method_name }: Empty String or Symbol keys are prohibited\"", "end", "return", "key", "end" ]
Given a storage key, make sure it's a String or Symbol, coerce to a String and ensure it isn't empty. Returns the non-empty String version. Raises exceptions for bad input classes or empty keys. +key+:: Key to normalise. +calling_method_name+:: Name of calling method to declare in exception messages, to aid callers in debugging.
[ "Given", "a", "storage", "key", "make", "sure", "it", "s", "a", "String", "or", "Symbol", "coerce", "to", "a", "String", "and", "ensure", "it", "isn", "t", "empty", ".", "Returns", "the", "non", "-", "empty", "String", "version", ".", "Raises", "exceptions", "for", "bad", "input", "classes", "or", "empty", "keys", "." ]
905940121917ecbb66364bca3455b94b1636470f
https://github.com/LoyaltyNZ/hoodoo/blob/905940121917ecbb66364bca3455b94b1636470f/lib/hoodoo/transient_store/transient_store.rb#L338-L350
20,133
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.push_gem
def push_gem(file, options = {}) ensure_ready!(:authorization) push_api = connection(:url => self.pushpoint) response = push_api.post('uploads', options.merge(:file => file)) checked_response_body(response) end
ruby
def push_gem(file, options = {}) ensure_ready!(:authorization) push_api = connection(:url => self.pushpoint) response = push_api.post('uploads', options.merge(:file => file)) checked_response_body(response) end
[ "def", "push_gem", "(", "file", ",", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "push_api", "=", "connection", "(", ":url", "=>", "self", ".", "pushpoint", ")", "response", "=", "push_api", ".", "post", "(", "'uploads'", ",", "options", ".", "merge", "(", ":file", "=>", "file", ")", ")", "checked_response_body", "(", "response", ")", "end" ]
Uploading a gem file
[ "Uploading", "a", "gem", "file" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L29-L34
20,134
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.versions
def versions(name, options = {}) ensure_ready!(:authorization) url = "gems/#{escape(name)}/versions" response = connection.get(url, options) checked_response_body(response) end
ruby
def versions(name, options = {}) ensure_ready!(:authorization) url = "gems/#{escape(name)}/versions" response = connection.get(url, options) checked_response_body(response) end
[ "def", "versions", "(", "name", ",", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "url", "=", "\"gems/#{escape(name)}/versions\"", "response", "=", "connection", ".", "get", "(", "url", ",", "options", ")", "checked_response_body", "(", "response", ")", "end" ]
List versions for a gem
[ "List", "versions", "for", "a", "gem" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L44-L49
20,135
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.yank_version
def yank_version(name, version, options = {}) ensure_ready!(:authorization) url = "gems/#{escape(name)}/versions/#{escape(version)}" response = connection.delete(url, options) checked_response_body(response) end
ruby
def yank_version(name, version, options = {}) ensure_ready!(:authorization) url = "gems/#{escape(name)}/versions/#{escape(version)}" response = connection.delete(url, options) checked_response_body(response) end
[ "def", "yank_version", "(", "name", ",", "version", ",", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "url", "=", "\"gems/#{escape(name)}/versions/#{escape(version)}\"", "response", "=", "connection", ".", "delete", "(", "url", ",", "options", ")", "checked_response_body", "(", "response", ")", "end" ]
Delete a gem version
[ "Delete", "a", "gem", "version" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L52-L57
20,136
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.add_collaborator
def add_collaborator(login, options = {}) ensure_ready!(:authorization) url = "collaborators/#{escape(login)}" response = connection.put(url, options) checked_response_body(response) end
ruby
def add_collaborator(login, options = {}) ensure_ready!(:authorization) url = "collaborators/#{escape(login)}" response = connection.put(url, options) checked_response_body(response) end
[ "def", "add_collaborator", "(", "login", ",", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "url", "=", "\"collaborators/#{escape(login)}\"", "response", "=", "connection", ".", "put", "(", "url", ",", "options", ")", "checked_response_body", "(", "response", ")", "end" ]
Add a collaborator to the account
[ "Add", "a", "collaborator", "to", "the", "account" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L86-L91
20,137
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.remove_collaborator
def remove_collaborator(login, options = {}) ensure_ready!(:authorization) url = "collaborators/#{escape(login)}" response = connection.delete(url, options) checked_response_body(response) end
ruby
def remove_collaborator(login, options = {}) ensure_ready!(:authorization) url = "collaborators/#{escape(login)}" response = connection.delete(url, options) checked_response_body(response) end
[ "def", "remove_collaborator", "(", "login", ",", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "url", "=", "\"collaborators/#{escape(login)}\"", "response", "=", "connection", ".", "delete", "(", "url", ",", "options", ")", "checked_response_body", "(", "response", ")", "end" ]
Remove a collaborator to the account
[ "Remove", "a", "collaborator", "to", "the", "account" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L94-L99
20,138
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.git_repos
def git_repos(options = {}) ensure_ready!(:authorization) response = connection.get(git_repo_path, options) checked_response_body(response) end
ruby
def git_repos(options = {}) ensure_ready!(:authorization) response = connection.get(git_repo_path, options) checked_response_body(response) end
[ "def", "git_repos", "(", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "response", "=", "connection", ".", "get", "(", "git_repo_path", ",", "options", ")", "checked_response_body", "(", "response", ")", "end" ]
List Git repos for this account
[ "List", "Git", "repos", "for", "this", "account" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L102-L106
20,139
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.git_update
def git_update(repo, options = {}) ensure_ready!(:authorization) response = connection.patch(git_repo_path(repo), options) checked_response_body(response) end
ruby
def git_update(repo, options = {}) ensure_ready!(:authorization) response = connection.patch(git_repo_path(repo), options) checked_response_body(response) end
[ "def", "git_update", "(", "repo", ",", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "response", "=", "connection", ".", "patch", "(", "git_repo_path", "(", "repo", ")", ",", "options", ")", "checked_response_body", "(", "response", ")", "end" ]
Update repository name and settings
[ "Update", "repository", "name", "and", "settings" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L109-L113
20,140
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.git_reset
def git_reset(repo, options = {}) ensure_ready!(:authorization) response = connection.delete(git_repo_path(repo), options) checked_response_body(response) end
ruby
def git_reset(repo, options = {}) ensure_ready!(:authorization) response = connection.delete(git_repo_path(repo), options) checked_response_body(response) end
[ "def", "git_reset", "(", "repo", ",", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "response", "=", "connection", ".", "delete", "(", "git_repo_path", "(", "repo", ")", ",", "options", ")", "checked_response_body", "(", "response", ")", "end" ]
Reset repository to initial state
[ "Reset", "repository", "to", "initial", "state" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L116-L120
20,141
gemfury/gemfury
lib/gemfury/client.rb
Gemfury.Client.git_rebuild
def git_rebuild(repo, options = {}) ensure_ready!(:authorization) url = "#{git_repo_path(repo)}/builds" api = connection(:api_format => :text) checked_response_body(api.post(url, options)) end
ruby
def git_rebuild(repo, options = {}) ensure_ready!(:authorization) url = "#{git_repo_path(repo)}/builds" api = connection(:api_format => :text) checked_response_body(api.post(url, options)) end
[ "def", "git_rebuild", "(", "repo", ",", "options", "=", "{", "}", ")", "ensure_ready!", "(", ":authorization", ")", "url", "=", "\"#{git_repo_path(repo)}/builds\"", "api", "=", "connection", "(", ":api_format", "=>", ":text", ")", "checked_response_body", "(", "api", ".", "post", "(", "url", ",", "options", ")", ")", "end" ]
Rebuild Git repository package
[ "Rebuild", "Git", "repository", "package" ]
edcdf816a9925abf6fbe89fe7896a563e1902582
https://github.com/gemfury/gemfury/blob/edcdf816a9925abf6fbe89fe7896a563e1902582/lib/gemfury/client.rb#L123-L128
20,142
celluloid/reel
lib/reel/response.rb
Reel.Response.status=
def status=(status, reason=nil) case status when Integer @status = status @reason ||= STATUS_CODES[status] when Symbol if code = SYMBOL_TO_STATUS_CODE[status] self.status = code else raise ArgumentError, "unrecognized status symbol: #{status}" end else raise TypeError, "invalid status type: #{status.inspect}" end end
ruby
def status=(status, reason=nil) case status when Integer @status = status @reason ||= STATUS_CODES[status] when Symbol if code = SYMBOL_TO_STATUS_CODE[status] self.status = code else raise ArgumentError, "unrecognized status symbol: #{status}" end else raise TypeError, "invalid status type: #{status.inspect}" end end
[ "def", "status", "=", "(", "status", ",", "reason", "=", "nil", ")", "case", "status", "when", "Integer", "@status", "=", "status", "@reason", "||=", "STATUS_CODES", "[", "status", "]", "when", "Symbol", "if", "code", "=", "SYMBOL_TO_STATUS_CODE", "[", "status", "]", "self", ".", "status", "=", "code", "else", "raise", "ArgumentError", ",", "\"unrecognized status symbol: #{status}\"", "end", "else", "raise", "TypeError", ",", "\"invalid status type: #{status.inspect}\"", "end", "end" ]
Set the status
[ "Set", "the", "status" ]
f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3
https://github.com/celluloid/reel/blob/f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3/lib/reel/response.rb#L48-L62
20,143
celluloid/reel
lib/reel/connection.rb
Reel.Connection.request
def request raise StateError, "already processing a request" if current_request req = @parser.current_request @request_fsm.transition :headers @keepalive = false if req[CONNECTION] == CLOSE || req.version == HTTP_VERSION_1_0 @current_request = req req rescue IOError, Errno::ECONNRESET, Errno::EPIPE @request_fsm.transition :closed @keepalive = false nil end
ruby
def request raise StateError, "already processing a request" if current_request req = @parser.current_request @request_fsm.transition :headers @keepalive = false if req[CONNECTION] == CLOSE || req.version == HTTP_VERSION_1_0 @current_request = req req rescue IOError, Errno::ECONNRESET, Errno::EPIPE @request_fsm.transition :closed @keepalive = false nil end
[ "def", "request", "raise", "StateError", ",", "\"already processing a request\"", "if", "current_request", "req", "=", "@parser", ".", "current_request", "@request_fsm", ".", "transition", ":headers", "@keepalive", "=", "false", "if", "req", "[", "CONNECTION", "]", "==", "CLOSE", "||", "req", ".", "version", "==", "HTTP_VERSION_1_0", "@current_request", "=", "req", "req", "rescue", "IOError", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "EPIPE", "@request_fsm", ".", "transition", ":closed", "@keepalive", "=", "false", "nil", "end" ]
Read a request object from the connection
[ "Read", "a", "request", "object", "from", "the", "connection" ]
f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3
https://github.com/celluloid/reel/blob/f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3/lib/reel/connection.rb#L54-L67
20,144
celluloid/reel
lib/reel/spy.rb
Reel.Spy.readpartial
def readpartial(maxlen, outbuf = "") data = @socket.readpartial(maxlen, outbuf) log :read, data data end
ruby
def readpartial(maxlen, outbuf = "") data = @socket.readpartial(maxlen, outbuf) log :read, data data end
[ "def", "readpartial", "(", "maxlen", ",", "outbuf", "=", "\"\"", ")", "data", "=", "@socket", ".", "readpartial", "(", "maxlen", ",", "outbuf", ")", "log", ":read", ",", "data", "data", "end" ]
Read from the client
[ "Read", "from", "the", "client" ]
f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3
https://github.com/celluloid/reel/blob/f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3/lib/reel/spy.rb#L23-L27
20,145
celluloid/reel
lib/reel/spy.rb
Reel.Spy.log
def log(type, str) case type when :connect @logger << Colors.green(str) when :close @logger << Colors.red(str) when :read @logger << Colors.gold(str) when :write @logger << Colors.white(str) else raise "unknown event type: #{type.inspect}" end end
ruby
def log(type, str) case type when :connect @logger << Colors.green(str) when :close @logger << Colors.red(str) when :read @logger << Colors.gold(str) when :write @logger << Colors.white(str) else raise "unknown event type: #{type.inspect}" end end
[ "def", "log", "(", "type", ",", "str", ")", "case", "type", "when", ":connect", "@logger", "<<", "Colors", ".", "green", "(", "str", ")", "when", ":close", "@logger", "<<", "Colors", ".", "red", "(", "str", ")", "when", ":read", "@logger", "<<", "Colors", ".", "gold", "(", "str", ")", "when", ":write", "@logger", "<<", "Colors", ".", "white", "(", "str", ")", "else", "raise", "\"unknown event type: #{type.inspect}\"", "end", "end" ]
Log the given event
[ "Log", "the", "given", "event" ]
f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3
https://github.com/celluloid/reel/blob/f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3/lib/reel/spy.rb#L43-L56
20,146
celluloid/reel
lib/reel/request.rb
Reel.Request.read
def read(length = nil, buffer = nil) raise ArgumentError, "negative length #{length} given" if length && length < 0 return '' if length == 0 res = buffer.nil? ? '' : buffer.clear chunk_size = length.nil? ? @connection.buffer_size : length begin while chunk_size > 0 chunk = readpartial(chunk_size) break unless chunk res << chunk chunk_size = length - res.length unless length.nil? end rescue EOFError end return length && res.length == 0 ? nil : res end
ruby
def read(length = nil, buffer = nil) raise ArgumentError, "negative length #{length} given" if length && length < 0 return '' if length == 0 res = buffer.nil? ? '' : buffer.clear chunk_size = length.nil? ? @connection.buffer_size : length begin while chunk_size > 0 chunk = readpartial(chunk_size) break unless chunk res << chunk chunk_size = length - res.length unless length.nil? end rescue EOFError end return length && res.length == 0 ? nil : res end
[ "def", "read", "(", "length", "=", "nil", ",", "buffer", "=", "nil", ")", "raise", "ArgumentError", ",", "\"negative length #{length} given\"", "if", "length", "&&", "length", "<", "0", "return", "''", "if", "length", "==", "0", "res", "=", "buffer", ".", "nil?", "?", "''", ":", "buffer", ".", "clear", "chunk_size", "=", "length", ".", "nil?", "?", "@connection", ".", "buffer_size", ":", "length", "begin", "while", "chunk_size", ">", "0", "chunk", "=", "readpartial", "(", "chunk_size", ")", "break", "unless", "chunk", "res", "<<", "chunk", "chunk_size", "=", "length", "-", "res", ".", "length", "unless", "length", ".", "nil?", "end", "rescue", "EOFError", "end", "return", "length", "&&", "res", ".", "length", "==", "0", "?", "nil", ":", "res", "end" ]
Read a number of bytes, looping until they are available or until readpartial returns nil, indicating there are no more bytes to read
[ "Read", "a", "number", "of", "bytes", "looping", "until", "they", "are", "available", "or", "until", "readpartial", "returns", "nil", "indicating", "there", "are", "no", "more", "bytes", "to", "read" ]
f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3
https://github.com/celluloid/reel/blob/f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3/lib/reel/request.rb#L50-L67
20,147
celluloid/reel
lib/reel/request.rb
Reel.Request.readpartial
def readpartial(length = nil) if length.nil? && @buffer.length > 0 slice = @buffer @buffer = "" else unless finished_reading? || (length && length <= @buffer.length) @connection.readpartial(length ? length - @buffer.length : @connection.buffer_size) end if length slice = @buffer.slice!(0, length) else slice = @buffer @buffer = "" end end slice && slice.length == 0 ? nil : slice end
ruby
def readpartial(length = nil) if length.nil? && @buffer.length > 0 slice = @buffer @buffer = "" else unless finished_reading? || (length && length <= @buffer.length) @connection.readpartial(length ? length - @buffer.length : @connection.buffer_size) end if length slice = @buffer.slice!(0, length) else slice = @buffer @buffer = "" end end slice && slice.length == 0 ? nil : slice end
[ "def", "readpartial", "(", "length", "=", "nil", ")", "if", "length", ".", "nil?", "&&", "@buffer", ".", "length", ">", "0", "slice", "=", "@buffer", "@buffer", "=", "\"\"", "else", "unless", "finished_reading?", "||", "(", "length", "&&", "length", "<=", "@buffer", ".", "length", ")", "@connection", ".", "readpartial", "(", "length", "?", "length", "-", "@buffer", ".", "length", ":", "@connection", ".", "buffer_size", ")", "end", "if", "length", "slice", "=", "@buffer", ".", "slice!", "(", "0", ",", "length", ")", "else", "slice", "=", "@buffer", "@buffer", "=", "\"\"", "end", "end", "slice", "&&", "slice", ".", "length", "==", "0", "?", "nil", ":", "slice", "end" ]
Read a string up to the given number of bytes, blocking until some data is available but returning immediately if some data is available
[ "Read", "a", "string", "up", "to", "the", "given", "number", "of", "bytes", "blocking", "until", "some", "data", "is", "available", "but", "returning", "immediately", "if", "some", "data", "is", "available" ]
f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3
https://github.com/celluloid/reel/blob/f6dd9922ce0e17dbd1a763d1831ac9d7648bc1d3/lib/reel/request.rb#L71-L89
20,148
ianwhite/pickle
lib/pickle/session.rb
Pickle.Session.created_model
def created_model(name) factory, name_or_index = *parse_model(name) if name_or_index.blank? models_by_index(factory).last elsif name_or_index.is_a?(Integer) models_by_index(factory)[name_or_index] else models_by_name(factory)[name_or_index] or raise ModelNotKnownError, name end end
ruby
def created_model(name) factory, name_or_index = *parse_model(name) if name_or_index.blank? models_by_index(factory).last elsif name_or_index.is_a?(Integer) models_by_index(factory)[name_or_index] else models_by_name(factory)[name_or_index] or raise ModelNotKnownError, name end end
[ "def", "created_model", "(", "name", ")", "factory", ",", "name_or_index", "=", "parse_model", "(", "name", ")", "if", "name_or_index", ".", "blank?", "models_by_index", "(", "factory", ")", ".", "last", "elsif", "name_or_index", ".", "is_a?", "(", "Integer", ")", "models_by_index", "(", "factory", ")", "[", "name_or_index", "]", "else", "models_by_name", "(", "factory", ")", "[", "name_or_index", "]", "or", "raise", "ModelNotKnownError", ",", "name", "end", "end" ]
return the original model stored by create_model or find_model
[ "return", "the", "original", "model", "stored", "by", "create_model", "or", "find_model" ]
3970158227375dc62dc8ae7b79305c013b783c7d
https://github.com/ianwhite/pickle/blob/3970158227375dc62dc8ae7b79305c013b783c7d/lib/pickle/session.rb#L114-L124
20,149
ianwhite/pickle
lib/pickle/session.rb
Pickle.Session.model
def model(name) model = created_model(name) return nil unless model Pickle::Adapter.get_model(model.class, model.id) end
ruby
def model(name) model = created_model(name) return nil unless model Pickle::Adapter.get_model(model.class, model.id) end
[ "def", "model", "(", "name", ")", "model", "=", "created_model", "(", "name", ")", "return", "nil", "unless", "model", "Pickle", "::", "Adapter", ".", "get_model", "(", "model", ".", "class", ",", "model", ".", "id", ")", "end" ]
return a newly selected model
[ "return", "a", "newly", "selected", "model" ]
3970158227375dc62dc8ae7b79305c013b783c7d
https://github.com/ianwhite/pickle/blob/3970158227375dc62dc8ae7b79305c013b783c7d/lib/pickle/session.rb#L132-L136
20,150
ianwhite/pickle
lib/pickle/session.rb
Pickle.Session.store_model
def store_model(factory, name, record) store_record(record.class.name, name, record) unless pickle_parser.canonical(factory) == pickle_parser.canonical(record.class.name) store_record(factory, name, record) end
ruby
def store_model(factory, name, record) store_record(record.class.name, name, record) unless pickle_parser.canonical(factory) == pickle_parser.canonical(record.class.name) store_record(factory, name, record) end
[ "def", "store_model", "(", "factory", ",", "name", ",", "record", ")", "store_record", "(", "record", ".", "class", ".", "name", ",", "name", ",", "record", ")", "unless", "pickle_parser", ".", "canonical", "(", "factory", ")", "==", "pickle_parser", ".", "canonical", "(", "record", ".", "class", ".", "name", ")", "store_record", "(", "factory", ",", "name", ",", "record", ")", "end" ]
if the factory name != the model name, store under both names
[ "if", "the", "factory", "name", "!", "=", "the", "model", "name", "store", "under", "both", "names" ]
3970158227375dc62dc8ae7b79305c013b783c7d
https://github.com/ianwhite/pickle/blob/3970158227375dc62dc8ae7b79305c013b783c7d/lib/pickle/session.rb#L231-L234
20,151
ianwhite/pickle
lib/pickle/path.rb
Pickle.Path.path_to_pickle
def path_to_pickle(*pickle_names) options = pickle_names.extract_options! resources = pickle_names.map{|n| model(n) || n.to_sym} if options[:extra] parts = options[:extra].underscore.gsub(' ','_').split("_") find_pickle_path_using_action_segment_combinations(resources, parts) else pickle_path_for_resources_action_segment(resources, options[:action], options[:segment]) end or raise "Could not figure out a path for #{pickle_names.inspect} #{options.inspect}" end
ruby
def path_to_pickle(*pickle_names) options = pickle_names.extract_options! resources = pickle_names.map{|n| model(n) || n.to_sym} if options[:extra] parts = options[:extra].underscore.gsub(' ','_').split("_") find_pickle_path_using_action_segment_combinations(resources, parts) else pickle_path_for_resources_action_segment(resources, options[:action], options[:segment]) end or raise "Could not figure out a path for #{pickle_names.inspect} #{options.inspect}" end
[ "def", "path_to_pickle", "(", "*", "pickle_names", ")", "options", "=", "pickle_names", ".", "extract_options!", "resources", "=", "pickle_names", ".", "map", "{", "|", "n", "|", "model", "(", "n", ")", "||", "n", ".", "to_sym", "}", "if", "options", "[", ":extra", "]", "parts", "=", "options", "[", ":extra", "]", ".", "underscore", ".", "gsub", "(", "' '", ",", "'_'", ")", ".", "split", "(", "\"_\"", ")", "find_pickle_path_using_action_segment_combinations", "(", "resources", ",", "parts", ")", "else", "pickle_path_for_resources_action_segment", "(", "resources", ",", "options", "[", ":action", "]", ",", "options", "[", ":segment", "]", ")", "end", "or", "raise", "\"Could not figure out a path for #{pickle_names.inspect} #{options.inspect}\"", "end" ]
given args of pickle model name, and an optional extra action, or segment, will attempt to find a matching named route path_to_pickle 'the user', :action => 'edit' # => /users/3/edit path_to_pickle 'the user', 'the comment' # => /users/3/comments/1 path_to_pickle 'the user', :segment => 'comments' # => /users/3/comments If you don;t know if the 'extra' part of the path is an action or a segment, then just pass it as 'extra' and this method will run through the possibilities path_to_pickle 'the user', :extra => 'new comment' # => /users/3/comments/new
[ "given", "args", "of", "pickle", "model", "name", "and", "an", "optional", "extra", "action", "or", "segment", "will", "attempt", "to", "find", "a", "matching", "named", "route" ]
3970158227375dc62dc8ae7b79305c013b783c7d
https://github.com/ianwhite/pickle/blob/3970158227375dc62dc8ae7b79305c013b783c7d/lib/pickle/path.rb#L14-L23
20,152
ianwhite/pickle
lib/pickle/email.rb
Pickle.Email.emails
def emails(fields = nil) @emails = ActionMailer::Base.deliveries.select {|m| email_has_fields?(m, fields)} end
ruby
def emails(fields = nil) @emails = ActionMailer::Base.deliveries.select {|m| email_has_fields?(m, fields)} end
[ "def", "emails", "(", "fields", "=", "nil", ")", "@emails", "=", "ActionMailer", "::", "Base", ".", "deliveries", ".", "select", "{", "|", "m", "|", "email_has_fields?", "(", "m", ",", "fields", ")", "}", "end" ]
return the deliveries array, optionally selected by the passed fields
[ "return", "the", "deliveries", "array", "optionally", "selected", "by", "the", "passed", "fields" ]
3970158227375dc62dc8ae7b79305c013b783c7d
https://github.com/ianwhite/pickle/blob/3970158227375dc62dc8ae7b79305c013b783c7d/lib/pickle/email.rb#L4-L6
20,153
rightscale/right_http_connection
lib/right_http_connection.rb
Rightscale.HttpConnection.error_add
def error_add(error) message = error message = "#{error.class.name}: #{error.message}" if error.is_a?(Exception) @state[@server] = { :count => error_count+1, :time => Time.now, :message => message } end
ruby
def error_add(error) message = error message = "#{error.class.name}: #{error.message}" if error.is_a?(Exception) @state[@server] = { :count => error_count+1, :time => Time.now, :message => message } end
[ "def", "error_add", "(", "error", ")", "message", "=", "error", "message", "=", "\"#{error.class.name}: #{error.message}\"", "if", "error", ".", "is_a?", "(", "Exception", ")", "@state", "[", "@server", "]", "=", "{", ":count", "=>", "error_count", "+", "1", ",", ":time", "=>", "Time", ".", "now", ",", ":message", "=>", "message", "}", "end" ]
add an error for a server
[ "add", "an", "error", "for", "a", "server" ]
9c8450bb6b8ae37a8a662f0e0415700f36ac6f89
https://github.com/rightscale/right_http_connection/blob/9c8450bb6b8ae37a8a662f0e0415700f36ac6f89/lib/right_http_connection.rb#L231-L235
20,154
rightscale/right_http_connection
lib/right_http_connection.rb
Rightscale.HttpConnection.setup_streaming
def setup_streaming(request) if(request.body && request.body.respond_to?(:read)) body = request.body request.content_length = body.respond_to?(:lstat) ? body.lstat.size : body.size request.body_stream = request.body true end end
ruby
def setup_streaming(request) if(request.body && request.body.respond_to?(:read)) body = request.body request.content_length = body.respond_to?(:lstat) ? body.lstat.size : body.size request.body_stream = request.body true end end
[ "def", "setup_streaming", "(", "request", ")", "if", "(", "request", ".", "body", "&&", "request", ".", "body", ".", "respond_to?", "(", ":read", ")", ")", "body", "=", "request", ".", "body", "request", ".", "content_length", "=", "body", ".", "respond_to?", "(", ":lstat", ")", "?", "body", ".", "lstat", ".", "size", ":", "body", ".", "size", "request", ".", "body_stream", "=", "request", ".", "body", "true", "end", "end" ]
Detects if an object is 'streamable' - can we read from it, and can we know the size?
[ "Detects", "if", "an", "object", "is", "streamable", "-", "can", "we", "read", "from", "it", "and", "can", "we", "know", "the", "size?" ]
9c8450bb6b8ae37a8a662f0e0415700f36ac6f89
https://github.com/rightscale/right_http_connection/blob/9c8450bb6b8ae37a8a662f0e0415700f36ac6f89/lib/right_http_connection.rb#L277-L284
20,155
rightscale/right_http_connection
lib/right_http_connection.rb
Rightscale.HttpConnection.start
def start(request_params) # close the previous if exists finish # create new connection @server = request_params[:server] @port = request_params[:port] @protocol = request_params[:protocol] @proxy_host = request_params[:proxy_host] @proxy_port = request_params[:proxy_port] @proxy_username = request_params[:proxy_username] @proxy_password = request_params[:proxy_password] SECURITY_PARAMS.each do |param_name| @params[param_name] = request_params[param_name] end @logger.info("Opening new #{@protocol.upcase} connection to #@server:#@port") @logger.info("Connecting to proxy #{@proxy_host}:#{@proxy_port} with username" + " #{@proxy_username.inspect}") unless @proxy_host.nil? @http = Net::HTTP.new(@server, @port, @proxy_host, @proxy_port, @proxy_username, @proxy_password) @http.open_timeout = get_param(:http_connection_open_timeout, request_params) @http.read_timeout = get_param(:http_connection_read_timeout, request_params) if @protocol == 'https' verifyCallbackProc = Proc.new{ |ok, x509_store_ctx| # List of error codes: http://www.openssl.org/docs/apps/verify.html code = x509_store_ctx.error msg = x509_store_ctx.error_string if request_params[:fail_if_ca_mismatch] && code != 0 false else true end } @http.use_ssl = true ca_file = get_param(:ca_file) if ca_file && File.exists?(ca_file) # Documentation for 'http.rb': # : verify_mode, verify_mode=((|mode|)) # Sets the flags for server the certification verification at # beginning of SSL/TLS session. # OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable. # # KHRVI: looks like the constant VERIFY_FAIL_IF_NO_PEER_CERT is not acceptable @http.verify_callback = verifyCallbackProc @http.ca_file= ca_file @http.verify_mode = get_param(:use_server_auth) ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE # The depth count is 'level 0:peer certificate', 'level 1: CA certificate', 'level 2: higher level CA certificate', and so on. # Setting the maximum depth to 2 allows the levels 0, 1, and 2. The default depth limit is 9, allowing for the peer certificate and additional 9 CA certificates. @http.verify_depth = 9 else @http.verify_mode = OpenSSL::SSL::VERIFY_NONE end # CERT cert_file = get_param(:cert_file, request_params) cert = File.read(cert_file) if cert_file && File.exists?(cert_file) cert ||= get_param(:cert, request_params) # KEY key_file = get_param(:key_file, request_params) key = File.read(key_file) if key_file && File.exists?(key_file) key ||= get_param(:key, request_params) if cert && key begin @http.verify_callback = verifyCallbackProc @http.cert = OpenSSL::X509::Certificate.new(cert) @http.key = OpenSSL::PKey::RSA.new(key) rescue OpenSSL::PKey::RSAError, OpenSSL::X509::CertificateError => e @logger.error "##### Error loading SSL client cert or key: #{e.message} :: backtrace #{e.backtrace}" raise e end end end # open connection @http.start end
ruby
def start(request_params) # close the previous if exists finish # create new connection @server = request_params[:server] @port = request_params[:port] @protocol = request_params[:protocol] @proxy_host = request_params[:proxy_host] @proxy_port = request_params[:proxy_port] @proxy_username = request_params[:proxy_username] @proxy_password = request_params[:proxy_password] SECURITY_PARAMS.each do |param_name| @params[param_name] = request_params[param_name] end @logger.info("Opening new #{@protocol.upcase} connection to #@server:#@port") @logger.info("Connecting to proxy #{@proxy_host}:#{@proxy_port} with username" + " #{@proxy_username.inspect}") unless @proxy_host.nil? @http = Net::HTTP.new(@server, @port, @proxy_host, @proxy_port, @proxy_username, @proxy_password) @http.open_timeout = get_param(:http_connection_open_timeout, request_params) @http.read_timeout = get_param(:http_connection_read_timeout, request_params) if @protocol == 'https' verifyCallbackProc = Proc.new{ |ok, x509_store_ctx| # List of error codes: http://www.openssl.org/docs/apps/verify.html code = x509_store_ctx.error msg = x509_store_ctx.error_string if request_params[:fail_if_ca_mismatch] && code != 0 false else true end } @http.use_ssl = true ca_file = get_param(:ca_file) if ca_file && File.exists?(ca_file) # Documentation for 'http.rb': # : verify_mode, verify_mode=((|mode|)) # Sets the flags for server the certification verification at # beginning of SSL/TLS session. # OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable. # # KHRVI: looks like the constant VERIFY_FAIL_IF_NO_PEER_CERT is not acceptable @http.verify_callback = verifyCallbackProc @http.ca_file= ca_file @http.verify_mode = get_param(:use_server_auth) ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE # The depth count is 'level 0:peer certificate', 'level 1: CA certificate', 'level 2: higher level CA certificate', and so on. # Setting the maximum depth to 2 allows the levels 0, 1, and 2. The default depth limit is 9, allowing for the peer certificate and additional 9 CA certificates. @http.verify_depth = 9 else @http.verify_mode = OpenSSL::SSL::VERIFY_NONE end # CERT cert_file = get_param(:cert_file, request_params) cert = File.read(cert_file) if cert_file && File.exists?(cert_file) cert ||= get_param(:cert, request_params) # KEY key_file = get_param(:key_file, request_params) key = File.read(key_file) if key_file && File.exists?(key_file) key ||= get_param(:key, request_params) if cert && key begin @http.verify_callback = verifyCallbackProc @http.cert = OpenSSL::X509::Certificate.new(cert) @http.key = OpenSSL::PKey::RSA.new(key) rescue OpenSSL::PKey::RSAError, OpenSSL::X509::CertificateError => e @logger.error "##### Error loading SSL client cert or key: #{e.message} :: backtrace #{e.backtrace}" raise e end end end # open connection @http.start end
[ "def", "start", "(", "request_params", ")", "# close the previous if exists", "finish", "# create new connection", "@server", "=", "request_params", "[", ":server", "]", "@port", "=", "request_params", "[", ":port", "]", "@protocol", "=", "request_params", "[", ":protocol", "]", "@proxy_host", "=", "request_params", "[", ":proxy_host", "]", "@proxy_port", "=", "request_params", "[", ":proxy_port", "]", "@proxy_username", "=", "request_params", "[", ":proxy_username", "]", "@proxy_password", "=", "request_params", "[", ":proxy_password", "]", "SECURITY_PARAMS", ".", "each", "do", "|", "param_name", "|", "@params", "[", "param_name", "]", "=", "request_params", "[", "param_name", "]", "end", "@logger", ".", "info", "(", "\"Opening new #{@protocol.upcase} connection to #@server:#@port\"", ")", "@logger", ".", "info", "(", "\"Connecting to proxy #{@proxy_host}:#{@proxy_port} with username\"", "+", "\" #{@proxy_username.inspect}\"", ")", "unless", "@proxy_host", ".", "nil?", "@http", "=", "Net", "::", "HTTP", ".", "new", "(", "@server", ",", "@port", ",", "@proxy_host", ",", "@proxy_port", ",", "@proxy_username", ",", "@proxy_password", ")", "@http", ".", "open_timeout", "=", "get_param", "(", ":http_connection_open_timeout", ",", "request_params", ")", "@http", ".", "read_timeout", "=", "get_param", "(", ":http_connection_read_timeout", ",", "request_params", ")", "if", "@protocol", "==", "'https'", "verifyCallbackProc", "=", "Proc", ".", "new", "{", "|", "ok", ",", "x509_store_ctx", "|", "# List of error codes: http://www.openssl.org/docs/apps/verify.html", "code", "=", "x509_store_ctx", ".", "error", "msg", "=", "x509_store_ctx", ".", "error_string", "if", "request_params", "[", ":fail_if_ca_mismatch", "]", "&&", "code", "!=", "0", "false", "else", "true", "end", "}", "@http", ".", "use_ssl", "=", "true", "ca_file", "=", "get_param", "(", ":ca_file", ")", "if", "ca_file", "&&", "File", ".", "exists?", "(", "ca_file", ")", "# Documentation for 'http.rb':", "# : verify_mode, verify_mode=((|mode|))", "# Sets the flags for server the certification verification at", "# beginning of SSL/TLS session.", "# OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable.", "#", "# KHRVI: looks like the constant VERIFY_FAIL_IF_NO_PEER_CERT is not acceptable", "@http", ".", "verify_callback", "=", "verifyCallbackProc", "@http", ".", "ca_file", "=", "ca_file", "@http", ".", "verify_mode", "=", "get_param", "(", ":use_server_auth", ")", "?", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", ":", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "# The depth count is 'level 0:peer certificate', 'level 1: CA certificate', 'level 2: higher level CA certificate', and so on.", "# Setting the maximum depth to 2 allows the levels 0, 1, and 2. The default depth limit is 9, allowing for the peer certificate and additional 9 CA certificates.", "@http", ".", "verify_depth", "=", "9", "else", "@http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "# CERT", "cert_file", "=", "get_param", "(", ":cert_file", ",", "request_params", ")", "cert", "=", "File", ".", "read", "(", "cert_file", ")", "if", "cert_file", "&&", "File", ".", "exists?", "(", "cert_file", ")", "cert", "||=", "get_param", "(", ":cert", ",", "request_params", ")", "# KEY", "key_file", "=", "get_param", "(", ":key_file", ",", "request_params", ")", "key", "=", "File", ".", "read", "(", "key_file", ")", "if", "key_file", "&&", "File", ".", "exists?", "(", "key_file", ")", "key", "||=", "get_param", "(", ":key", ",", "request_params", ")", "if", "cert", "&&", "key", "begin", "@http", ".", "verify_callback", "=", "verifyCallbackProc", "@http", ".", "cert", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "(", "cert", ")", "@http", ".", "key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "key", ")", "rescue", "OpenSSL", "::", "PKey", "::", "RSAError", ",", "OpenSSL", "::", "X509", "::", "CertificateError", "=>", "e", "@logger", ".", "error", "\"##### Error loading SSL client cert or key: #{e.message} :: backtrace #{e.backtrace}\"", "raise", "e", "end", "end", "end", "# open connection", "@http", ".", "start", "end" ]
Start a fresh connection. The object closes any existing connection and opens a new one.
[ "Start", "a", "fresh", "connection", ".", "The", "object", "closes", "any", "existing", "connection", "and", "opens", "a", "new", "one", "." ]
9c8450bb6b8ae37a8a662f0e0415700f36ac6f89
https://github.com/rightscale/right_http_connection/blob/9c8450bb6b8ae37a8a662f0e0415700f36ac6f89/lib/right_http_connection.rb#L310-L389
20,156
rightscale/right_http_connection
lib/right_http_connection.rb
Rightscale.HttpConnection.request
def request(request_params, &block) current_params = @params.merge(request_params) exception = get_param(:exception, current_params) || RuntimeError # Re-establish the connection if any of auth params has changed same_auth_params_as_before = SECURITY_PARAMS.select do |param| request_params[param] != get_param(param) end.empty? # We save the offset here so that if we need to retry, we can return the file pointer to its initial position mypos = get_fileptr_offset(current_params) loop do current_params[:protocol] ||= (current_params[:port] == 443 ? 'https' : 'http') # (re)open connection to server if none exists or params has changed same_server_as_before = @server == current_params[:server] && @port == current_params[:port] && @protocol == current_params[:protocol] && same_auth_params_as_before # if we are inside a delay between retries: no requests this time! # (skip this step if the endpoint has changed) if error_count > current_params[:http_connection_retry_count] && error_time + current_params[:http_connection_retry_delay] > Time.now && same_server_as_before # store the message (otherwise it will be lost after error_reset and # we will raise an exception with an empty text) banana_message_text = banana_message @logger.warn("#{err_header} re-raising same error: #{banana_message_text} " + "-- error count: #{error_count}, error age: #{Time.now.to_i - error_time.to_i}") raise exception.new(banana_message_text) end # try to connect server(if connection does not exist) and get response data begin request = current_params[:request] request['User-Agent'] = get_param(:user_agent, current_params) || '' unless @http && @http.started? && same_server_as_before same_auth_params_as_before = true start(current_params) end # Detect if the body is a streamable object like a file or socket. If so, stream that # bad boy. setup_streaming(request) # update READ_TIMEOUT value (it can be passed with request_params hash) @http.read_timeout = get_param(:http_connection_read_timeout, current_params) response = @http.request(request, &block) error_reset eof_reset return response # We treat EOF errors and the timeout/network errors differently. Both # are tracked in different statistics blocks. Note below that EOF # errors will sleep for a certain (exponentially increasing) period. # Other errors don't sleep because there is already an inherent delay # in them; connect and read timeouts (for example) have already # 'slept'. It is still not clear which way we should treat errors # like RST and resolution failures. For now, there is no additional # delay for these errors although this may change in the future. # EOFError means the server closed the connection on us. rescue EOFError => e finish(e.message) @logger.debug("#{err_header} server #{@server} closed connection") # if we have waited long enough - raise an exception... if raise_on_eof_exception? @logger.warn("#{err_header} raising #{exception} due to permanent EOF being received from #{@server}, error age: #{Time.now.to_i - eof_time.to_i}") raise exception.new("Permanent EOF is being received from #{@server}.") else # ... else just sleep a bit before new retry sleep(add_eof) # We will be retrying the request, so reset the file pointer reset_fileptr_offset(request, mypos) end rescue ArgumentError => e finish(e.message) if e.message.include?('wrong number of arguments (5 for 4)') # seems our net_fix patch was overriden... raise exception.new('incompatible Net::HTTP monkey-patch') else raise e end rescue Timeout::Error, SocketError, SystemCallError, Interrupt => e # See comment at bottom for the list of errors seen... finish(e.message) if e.is_a?(Errno::ETIMEDOUT) || e.is_a?(Timeout::Error) # Omit retries if it was explicitly requested # #6481: # ... When creating a resource in EC2 (instance, volume, snapshot, etc) it is undetermined what happened if the call times out. # The resource may or may not have been created in EC2. Retrying the call may cause multiple resources to be created... raise exception.new("#{e.class.name}: #{e.message}") if current_params[:raise_on_timeout] elsif e.is_a?(Interrupt) # if ctrl+c is pressed - we have to reraise exception to terminate proggy @logger.debug( "#{err_header} request to server #{@server} interrupted by ctrl-c") raise e end # oops - we got a banana: log it error_add(e) @logger.warn("#{err_header} request failure count: #{error_count}, exception: #{e.inspect}") # We will be retrying the request, so reset the file pointer reset_fileptr_offset(request, mypos) end end end
ruby
def request(request_params, &block) current_params = @params.merge(request_params) exception = get_param(:exception, current_params) || RuntimeError # Re-establish the connection if any of auth params has changed same_auth_params_as_before = SECURITY_PARAMS.select do |param| request_params[param] != get_param(param) end.empty? # We save the offset here so that if we need to retry, we can return the file pointer to its initial position mypos = get_fileptr_offset(current_params) loop do current_params[:protocol] ||= (current_params[:port] == 443 ? 'https' : 'http') # (re)open connection to server if none exists or params has changed same_server_as_before = @server == current_params[:server] && @port == current_params[:port] && @protocol == current_params[:protocol] && same_auth_params_as_before # if we are inside a delay between retries: no requests this time! # (skip this step if the endpoint has changed) if error_count > current_params[:http_connection_retry_count] && error_time + current_params[:http_connection_retry_delay] > Time.now && same_server_as_before # store the message (otherwise it will be lost after error_reset and # we will raise an exception with an empty text) banana_message_text = banana_message @logger.warn("#{err_header} re-raising same error: #{banana_message_text} " + "-- error count: #{error_count}, error age: #{Time.now.to_i - error_time.to_i}") raise exception.new(banana_message_text) end # try to connect server(if connection does not exist) and get response data begin request = current_params[:request] request['User-Agent'] = get_param(:user_agent, current_params) || '' unless @http && @http.started? && same_server_as_before same_auth_params_as_before = true start(current_params) end # Detect if the body is a streamable object like a file or socket. If so, stream that # bad boy. setup_streaming(request) # update READ_TIMEOUT value (it can be passed with request_params hash) @http.read_timeout = get_param(:http_connection_read_timeout, current_params) response = @http.request(request, &block) error_reset eof_reset return response # We treat EOF errors and the timeout/network errors differently. Both # are tracked in different statistics blocks. Note below that EOF # errors will sleep for a certain (exponentially increasing) period. # Other errors don't sleep because there is already an inherent delay # in them; connect and read timeouts (for example) have already # 'slept'. It is still not clear which way we should treat errors # like RST and resolution failures. For now, there is no additional # delay for these errors although this may change in the future. # EOFError means the server closed the connection on us. rescue EOFError => e finish(e.message) @logger.debug("#{err_header} server #{@server} closed connection") # if we have waited long enough - raise an exception... if raise_on_eof_exception? @logger.warn("#{err_header} raising #{exception} due to permanent EOF being received from #{@server}, error age: #{Time.now.to_i - eof_time.to_i}") raise exception.new("Permanent EOF is being received from #{@server}.") else # ... else just sleep a bit before new retry sleep(add_eof) # We will be retrying the request, so reset the file pointer reset_fileptr_offset(request, mypos) end rescue ArgumentError => e finish(e.message) if e.message.include?('wrong number of arguments (5 for 4)') # seems our net_fix patch was overriden... raise exception.new('incompatible Net::HTTP monkey-patch') else raise e end rescue Timeout::Error, SocketError, SystemCallError, Interrupt => e # See comment at bottom for the list of errors seen... finish(e.message) if e.is_a?(Errno::ETIMEDOUT) || e.is_a?(Timeout::Error) # Omit retries if it was explicitly requested # #6481: # ... When creating a resource in EC2 (instance, volume, snapshot, etc) it is undetermined what happened if the call times out. # The resource may or may not have been created in EC2. Retrying the call may cause multiple resources to be created... raise exception.new("#{e.class.name}: #{e.message}") if current_params[:raise_on_timeout] elsif e.is_a?(Interrupt) # if ctrl+c is pressed - we have to reraise exception to terminate proggy @logger.debug( "#{err_header} request to server #{@server} interrupted by ctrl-c") raise e end # oops - we got a banana: log it error_add(e) @logger.warn("#{err_header} request failure count: #{error_count}, exception: #{e.inspect}") # We will be retrying the request, so reset the file pointer reset_fileptr_offset(request, mypos) end end end
[ "def", "request", "(", "request_params", ",", "&", "block", ")", "current_params", "=", "@params", ".", "merge", "(", "request_params", ")", "exception", "=", "get_param", "(", ":exception", ",", "current_params", ")", "||", "RuntimeError", "# Re-establish the connection if any of auth params has changed", "same_auth_params_as_before", "=", "SECURITY_PARAMS", ".", "select", "do", "|", "param", "|", "request_params", "[", "param", "]", "!=", "get_param", "(", "param", ")", "end", ".", "empty?", "# We save the offset here so that if we need to retry, we can return the file pointer to its initial position", "mypos", "=", "get_fileptr_offset", "(", "current_params", ")", "loop", "do", "current_params", "[", ":protocol", "]", "||=", "(", "current_params", "[", ":port", "]", "==", "443", "?", "'https'", ":", "'http'", ")", "# (re)open connection to server if none exists or params has changed", "same_server_as_before", "=", "@server", "==", "current_params", "[", ":server", "]", "&&", "@port", "==", "current_params", "[", ":port", "]", "&&", "@protocol", "==", "current_params", "[", ":protocol", "]", "&&", "same_auth_params_as_before", "# if we are inside a delay between retries: no requests this time!", "# (skip this step if the endpoint has changed)", "if", "error_count", ">", "current_params", "[", ":http_connection_retry_count", "]", "&&", "error_time", "+", "current_params", "[", ":http_connection_retry_delay", "]", ">", "Time", ".", "now", "&&", "same_server_as_before", "# store the message (otherwise it will be lost after error_reset and", "# we will raise an exception with an empty text)", "banana_message_text", "=", "banana_message", "@logger", ".", "warn", "(", "\"#{err_header} re-raising same error: #{banana_message_text} \"", "+", "\"-- error count: #{error_count}, error age: #{Time.now.to_i - error_time.to_i}\"", ")", "raise", "exception", ".", "new", "(", "banana_message_text", ")", "end", "# try to connect server(if connection does not exist) and get response data", "begin", "request", "=", "current_params", "[", ":request", "]", "request", "[", "'User-Agent'", "]", "=", "get_param", "(", ":user_agent", ",", "current_params", ")", "||", "''", "unless", "@http", "&&", "@http", ".", "started?", "&&", "same_server_as_before", "same_auth_params_as_before", "=", "true", "start", "(", "current_params", ")", "end", "# Detect if the body is a streamable object like a file or socket. If so, stream that", "# bad boy.", "setup_streaming", "(", "request", ")", "# update READ_TIMEOUT value (it can be passed with request_params hash)", "@http", ".", "read_timeout", "=", "get_param", "(", ":http_connection_read_timeout", ",", "current_params", ")", "response", "=", "@http", ".", "request", "(", "request", ",", "block", ")", "error_reset", "eof_reset", "return", "response", "# We treat EOF errors and the timeout/network errors differently. Both", "# are tracked in different statistics blocks. Note below that EOF", "# errors will sleep for a certain (exponentially increasing) period.", "# Other errors don't sleep because there is already an inherent delay", "# in them; connect and read timeouts (for example) have already", "# 'slept'. It is still not clear which way we should treat errors", "# like RST and resolution failures. For now, there is no additional", "# delay for these errors although this may change in the future.", "# EOFError means the server closed the connection on us.", "rescue", "EOFError", "=>", "e", "finish", "(", "e", ".", "message", ")", "@logger", ".", "debug", "(", "\"#{err_header} server #{@server} closed connection\"", ")", "# if we have waited long enough - raise an exception...", "if", "raise_on_eof_exception?", "@logger", ".", "warn", "(", "\"#{err_header} raising #{exception} due to permanent EOF being received from #{@server}, error age: #{Time.now.to_i - eof_time.to_i}\"", ")", "raise", "exception", ".", "new", "(", "\"Permanent EOF is being received from #{@server}.\"", ")", "else", "# ... else just sleep a bit before new retry", "sleep", "(", "add_eof", ")", "# We will be retrying the request, so reset the file pointer", "reset_fileptr_offset", "(", "request", ",", "mypos", ")", "end", "rescue", "ArgumentError", "=>", "e", "finish", "(", "e", ".", "message", ")", "if", "e", ".", "message", ".", "include?", "(", "'wrong number of arguments (5 for 4)'", ")", "# seems our net_fix patch was overriden...", "raise", "exception", ".", "new", "(", "'incompatible Net::HTTP monkey-patch'", ")", "else", "raise", "e", "end", "rescue", "Timeout", "::", "Error", ",", "SocketError", ",", "SystemCallError", ",", "Interrupt", "=>", "e", "# See comment at bottom for the list of errors seen...", "finish", "(", "e", ".", "message", ")", "if", "e", ".", "is_a?", "(", "Errno", "::", "ETIMEDOUT", ")", "||", "e", ".", "is_a?", "(", "Timeout", "::", "Error", ")", "# Omit retries if it was explicitly requested", "# #6481:", "# ... When creating a resource in EC2 (instance, volume, snapshot, etc) it is undetermined what happened if the call times out.", "# The resource may or may not have been created in EC2. Retrying the call may cause multiple resources to be created...", "raise", "exception", ".", "new", "(", "\"#{e.class.name}: #{e.message}\"", ")", "if", "current_params", "[", ":raise_on_timeout", "]", "elsif", "e", ".", "is_a?", "(", "Interrupt", ")", "# if ctrl+c is pressed - we have to reraise exception to terminate proggy", "@logger", ".", "debug", "(", "\"#{err_header} request to server #{@server} interrupted by ctrl-c\"", ")", "raise", "e", "end", "# oops - we got a banana: log it", "error_add", "(", "e", ")", "@logger", ".", "warn", "(", "\"#{err_header} request failure count: #{error_count}, exception: #{e.inspect}\"", ")", "# We will be retrying the request, so reset the file pointer", "reset_fileptr_offset", "(", "request", ",", "mypos", ")", "end", "end", "end" ]
=begin rdoc Send HTTP request to server request_params hash: :server => 'www.HostName.com' # Hostname or IP address of HTTP server :port => '80' # Port of HTTP server :protocol => 'https' # http and https are supported on any port :request => 'requeststring' # Fully-formed HTTP request to make :proxy_host => 'hostname' # hostname of HTTP proxy host to use, default none. :proxy_port => port # port of HTTP proxy host to use, default none. :proxy_username => 'username' # username to use for proxy authentication, default none. :proxy_password => 'password' # password to use for proxy authentication, default none. :raise_on_timeout # do not perform a retry if timeout is received (false by default) :http_connection_retry_count :http_connection_open_timeout :http_connection_read_timeout :http_connection_retry_delay :user_agent :exception Raises RuntimeError, Interrupt, and params[:exception] (if specified in new). =end
[ "=", "begin", "rdoc", "Send", "HTTP", "request", "to", "server" ]
9c8450bb6b8ae37a8a662f0e0415700f36ac6f89
https://github.com/rightscale/right_http_connection/blob/9c8450bb6b8ae37a8a662f0e0415700f36ac6f89/lib/right_http_connection.rb#L417-L529
20,157
mbleigh/princely
lib/princely/pdf.rb
Princely.Pdf.pdf_from_string
def pdf_from_string(string, output_file = '-') with_timeout do pdf = initialize_pdf_from_string(string, output_file, {:output_to_log_file => false}) pdf.close_write result = pdf.gets(nil) pdf.close_read result.force_encoding('BINARY') if RUBY_VERSION >= "1.9" result end end
ruby
def pdf_from_string(string, output_file = '-') with_timeout do pdf = initialize_pdf_from_string(string, output_file, {:output_to_log_file => false}) pdf.close_write result = pdf.gets(nil) pdf.close_read result.force_encoding('BINARY') if RUBY_VERSION >= "1.9" result end end
[ "def", "pdf_from_string", "(", "string", ",", "output_file", "=", "'-'", ")", "with_timeout", "do", "pdf", "=", "initialize_pdf_from_string", "(", "string", ",", "output_file", ",", "{", ":output_to_log_file", "=>", "false", "}", ")", "pdf", ".", "close_write", "result", "=", "pdf", ".", "gets", "(", "nil", ")", "pdf", ".", "close_read", "result", ".", "force_encoding", "(", "'BINARY'", ")", "if", "RUBY_VERSION", ">=", "\"1.9\"", "result", "end", "end" ]
Makes a pdf from a passed in string. Returns PDF as a stream, so we can use send_data to shoot it down the pipe using Rails.
[ "Makes", "a", "pdf", "from", "a", "passed", "in", "string", "." ]
559f374e89089f5206498aa34306c8eac8c2aa25
https://github.com/mbleigh/princely/blob/559f374e89089f5206498aa34306c8eac8c2aa25/lib/princely/pdf.rb#L69-L79
20,158
jmettraux/ruote
lib/ruote/dashboard.rb
Ruote.Dashboard.attach
def attach(fei_or_fe, definition, opts={}) fe = Ruote.extract_fexp(@context, fei_or_fe).to_h fei = fe['fei'] cfei = fei.merge( 'expid' => "#{fei['expid']}_0", 'subid' => Ruote.generate_subid(fei.inspect)) tree = @context.reader.read(definition) tree[0] = 'sequence' fields = fe['applied_workitem']['fields'] if fs = opts[:fields] || opts[:workitem] fields = fs elsif fs = opts[:merge_fields] fields.merge!(fs) end @context.storage.put_msg( 'launch', # "apply" is OK, but "launch" stands out better 'parent_id' => fei, 'fei' => cfei, 'tree' => tree, 'workitem' => { 'fields' => fields }, 'attached' => true) Ruote::FlowExpressionId.new(cfei) end
ruby
def attach(fei_or_fe, definition, opts={}) fe = Ruote.extract_fexp(@context, fei_or_fe).to_h fei = fe['fei'] cfei = fei.merge( 'expid' => "#{fei['expid']}_0", 'subid' => Ruote.generate_subid(fei.inspect)) tree = @context.reader.read(definition) tree[0] = 'sequence' fields = fe['applied_workitem']['fields'] if fs = opts[:fields] || opts[:workitem] fields = fs elsif fs = opts[:merge_fields] fields.merge!(fs) end @context.storage.put_msg( 'launch', # "apply" is OK, but "launch" stands out better 'parent_id' => fei, 'fei' => cfei, 'tree' => tree, 'workitem' => { 'fields' => fields }, 'attached' => true) Ruote::FlowExpressionId.new(cfei) end
[ "def", "attach", "(", "fei_or_fe", ",", "definition", ",", "opts", "=", "{", "}", ")", "fe", "=", "Ruote", ".", "extract_fexp", "(", "@context", ",", "fei_or_fe", ")", ".", "to_h", "fei", "=", "fe", "[", "'fei'", "]", "cfei", "=", "fei", ".", "merge", "(", "'expid'", "=>", "\"#{fei['expid']}_0\"", ",", "'subid'", "=>", "Ruote", ".", "generate_subid", "(", "fei", ".", "inspect", ")", ")", "tree", "=", "@context", ".", "reader", ".", "read", "(", "definition", ")", "tree", "[", "0", "]", "=", "'sequence'", "fields", "=", "fe", "[", "'applied_workitem'", "]", "[", "'fields'", "]", "if", "fs", "=", "opts", "[", ":fields", "]", "||", "opts", "[", ":workitem", "]", "fields", "=", "fs", "elsif", "fs", "=", "opts", "[", ":merge_fields", "]", "fields", ".", "merge!", "(", "fs", ")", "end", "@context", ".", "storage", ".", "put_msg", "(", "'launch'", ",", "# \"apply\" is OK, but \"launch\" stands out better", "'parent_id'", "=>", "fei", ",", "'fei'", "=>", "cfei", ",", "'tree'", "=>", "tree", ",", "'workitem'", "=>", "{", "'fields'", "=>", "fields", "}", ",", "'attached'", "=>", "true", ")", "Ruote", "::", "FlowExpressionId", ".", "new", "(", "cfei", ")", "end" ]
Given a flow expression id, locates the corresponding ruote expression and attaches a subprocess to it. Accepts the fei as a Hash or as a FlowExpressionId instance. By default, the workitem of the expression you attach to provides the initial workitem for the attached branch. By using the :fields/:workitem or :merge_fields options, one can change that. Returns the fei of the attached [root] expression (as a FlowExpressionId instance).
[ "Given", "a", "flow", "expression", "id", "locates", "the", "corresponding", "ruote", "expression", "and", "attaches", "a", "subprocess", "to", "it", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dashboard.rb#L194-L222
20,159
jmettraux/ruote
lib/ruote/dashboard.rb
Ruote.Dashboard.apply_mutation
def apply_mutation(wfid, pdef) Mutation.new(self, wfid, @context.reader.read(pdef)).apply end
ruby
def apply_mutation(wfid, pdef) Mutation.new(self, wfid, @context.reader.read(pdef)).apply end
[ "def", "apply_mutation", "(", "wfid", ",", "pdef", ")", "Mutation", ".", "new", "(", "self", ",", "wfid", ",", "@context", ".", "reader", ".", "read", "(", "pdef", ")", ")", ".", "apply", "end" ]
Computes mutation and immediately applies it... See #compute_mutation Return the mutation instance (forensic?)
[ "Computes", "mutation", "and", "immediately", "applies", "it", "..." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dashboard.rb#L431-L434
20,160
jmettraux/ruote
lib/ruote/dashboard.rb
Ruote.Dashboard.processes
def processes(opts={}) wfids = @context.storage.expression_wfids(opts) opts[:count] ? wfids.size : ProcessStatus.fetch(@context, wfids, opts) end
ruby
def processes(opts={}) wfids = @context.storage.expression_wfids(opts) opts[:count] ? wfids.size : ProcessStatus.fetch(@context, wfids, opts) end
[ "def", "processes", "(", "opts", "=", "{", "}", ")", "wfids", "=", "@context", ".", "storage", ".", "expression_wfids", "(", "opts", ")", "opts", "[", ":count", "]", "?", "wfids", ".", "size", ":", "ProcessStatus", ".", "fetch", "(", "@context", ",", "wfids", ",", "opts", ")", "end" ]
Returns an array of ProcessStatus instances. WARNING : this is an expensive operation, but it understands :skip and :limit, so pagination is our friend. Please note, if you're interested only in processes that have errors, Engine#errors is a more efficient means. To simply list the wfids of the currently running, Engine#process_wfids is way cheaper to call.
[ "Returns", "an", "array", "of", "ProcessStatus", "instances", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dashboard.rb#L477-L482
20,161
jmettraux/ruote
lib/ruote/dashboard.rb
Ruote.Dashboard.wait_for
def wait_for(*items) opts = (items.size > 1 && items.last.is_a?(Hash)) ? items.pop : {} @context.logger.wait_for(items, opts) end
ruby
def wait_for(*items) opts = (items.size > 1 && items.last.is_a?(Hash)) ? items.pop : {} @context.logger.wait_for(items, opts) end
[ "def", "wait_for", "(", "*", "items", ")", "opts", "=", "(", "items", ".", "size", ">", "1", "&&", "items", ".", "last", ".", "is_a?", "(", "Hash", ")", ")", "?", "items", ".", "pop", ":", "{", "}", "@context", ".", "logger", ".", "wait_for", "(", "items", ",", "opts", ")", "end" ]
This method expects there to be a logger with a wait_for method in the context, else it will raise an exception. *WARNING*: #wait_for() is meant for environments where there is a unique worker and that worker is nested in this engine. In a multiple worker environment wait_for doesn't see events handled by 'other' workers. This method is only useful for test/quickstart/examples environments. dashboard.wait_for(:alpha) # will make the current thread block until a workitem is delivered # to the participant named 'alpha' engine.wait_for('123432123-9043') # will make the current thread block until the processed whose # wfid is given (String) terminates or produces an error. engine.wait_for(5) # will make the current thread block until 5 messages have been # processed on the workqueue... engine.wait_for(:empty) # will return as soon as the engine/storage is empty, ie as soon # as there are no more processes running in the engine (no more # expressions placed in the storage) engine.wait_for('terminated') # will return as soon as any process has a 'terminated' event. It's OK to wait for multiple wfids: engine.wait_for('20100612-bezerijozo', '20100612-yakisoba') If one needs to wait for something else than a wfid but needs to break in case of error: engine.wait_for(:alpha, :or_error) == ruote 2.3.0 and wait_for(event) Ruote 2.3.0 introduced the ability to wait for an event given its name. Here is a quick list of event names and a their description: * 'launch' - [sub]process launch * 'terminated' - process terminated * 'ceased' - orphan process terminated * 'apply' - expression application * 'reply' - expression reply * 'dispatched' - emitted workitem towards participant * 'receive' - received workitem from participant * 'pause' - pause order * 'resume' - pause order * 'dispatch_cancel' - emitting a cancel order to a participant * 'dispatch_pause' - emitting a pause order to a participant * 'dispatch_resume' - emitting a resume order to a participant Names that are past participles are for notification events, while plain verbs are for action events. Most of the time, a notitication is emitted has the result of an action event, workers don't take any action on them, but services that are listening to the ruote activity might want to do something about them. == ruote 2.3.0 and wait_for(hash) For more precise testing, wait_for accepts hashes, for example: r = dashboard.wait_for('action' => 'apply', 'exp_name' => 'wait') will block until a wait expression is applied. If you know ruote msgs, you can pinpoint at will: r = dashboard.wait_for( 'action' => 'apply', 'exp_name' => 'wait', 'fei.wfid' => wfid) == what wait_for returns #wait_for returns the intercepted event. It's useful when testing/ spec'ing, as in: it 'completes successfully' do definition = Ruote.define :on_error => 'charly' do alpha bravo end wfid = @board.launch(definition) r = @board.wait_for(wfid) # wait until process terminates or hits an error r['workitem'].should_not == nil r['workitem']['fields']['alpha'].should == 'was here' r['workitem']['fields']['bravo'].should == 'was here' r['workitem']['fields']['charly'].should == nil end == :timeout option One can pass a timeout value in seconds for the #wait_for call, as in: dashboard.wait_for(wfid, :timeout => 5 * 60) The default timeout is 60 (seconds). A nil or negative timeout disables the timeout.
[ "This", "method", "expects", "there", "to", "be", "a", "logger", "with", "a", "wait_for", "method", "in", "the", "context", "else", "it", "will", "raise", "an", "exception", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dashboard.rb#L710-L715
20,162
jmettraux/ruote
lib/ruote/dashboard.rb
Ruote.Dashboard.register_participant
def register_participant(regex, participant=nil, opts={}, &block) if participant.is_a?(Hash) opts = participant participant = nil end pa = @context.plist.register(regex, participant, opts, block) @context.storage.put_msg( 'participant_registered', 'regex' => regex.is_a?(Regexp) ? regex.inspect : regex.to_s) pa end
ruby
def register_participant(regex, participant=nil, opts={}, &block) if participant.is_a?(Hash) opts = participant participant = nil end pa = @context.plist.register(regex, participant, opts, block) @context.storage.put_msg( 'participant_registered', 'regex' => regex.is_a?(Regexp) ? regex.inspect : regex.to_s) pa end
[ "def", "register_participant", "(", "regex", ",", "participant", "=", "nil", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "if", "participant", ".", "is_a?", "(", "Hash", ")", "opts", "=", "participant", "participant", "=", "nil", "end", "pa", "=", "@context", ".", "plist", ".", "register", "(", "regex", ",", "participant", ",", "opts", ",", "block", ")", "@context", ".", "storage", ".", "put_msg", "(", "'participant_registered'", ",", "'regex'", "=>", "regex", ".", "is_a?", "(", "Regexp", ")", "?", "regex", ".", "inspect", ":", "regex", ".", "to_s", ")", "pa", "end" ]
Registers a participant in the engine. Takes the form dashboard.register_participant name_or_regex, klass, opts={} With the form dashboard.register_participant name_or_regex do |workitem| # ... end A BlockParticipant is automatically created. == name or regex When registering participants, strings or regexes are accepted. Behind the scenes, a regex is kept. Passing a string like "alain" will get ruote to automatically turn it into the following regex : /^alain$/. For finer control over this, pass a regex directly dashboard.register_participant /^user-/, MyParticipant # will match all workitems whose participant name starts with "user-" == some examples dashboard.register_participant 'compute_sum' do |wi| wi.fields['sum'] = wi.fields['articles'].inject(0) do |s, (c, v)| s + c * v # sum + count * value end # a block participant implicitely replies to the engine immediately end class MyParticipant def initialize(opts) @name = opts['name'] end def on_workitem workitem.fields['rocket_name'] = @name send_to_the_moon(workitem) end def on_cancel # do nothing end end dashboard.register_participant( /^moon-.+/, MyParticipant, 'name' => 'Saturn-V') # computing the total for a invoice being passed in the workitem. class TotalParticipant include Ruote::LocalParticipant def on_workitem workitem['total'] = workitem.fields['items'].inject(0.0) { |t, item| t + item['count'] * PricingService.lookup(item['id']) } reply end def on_cancel end end dashboard.register_participant 'total', TotalParticipant Remember that the options (the hash that follows the class name), must be serializable via JSON. == require_path and load_path It's OK to register a participant by passing its full classname as a String. dashboard.register_participant( 'auditor', 'AuditParticipant', 'require_path' => 'part/audit.rb') dashboard.register_participant( 'auto_decision', 'DecParticipant', 'load_path' => 'part/dec.rb') Note the option load_path / require_path that point to the ruby file containing the participant implementation. 'require' will load and eval the ruby code only once, 'load' each time. == :override => false By default, when registering a participant, if this results in a regex that is already used, the previously registered participant gets unregistered. dashboard.register_participant 'alpha', AaParticipant dashboard.register_participant 'alpha', BbParticipant, :override => false This can be useful when the #accept? method of participants are in use. Note that using the #register(&block) method, :override => false is automatically enforced. dashboard.register do alpha AaParticipant alpha BbParticipant end == :position / :pos => 'last' / 'first' / 'before' / 'after' / 'over' One can specify the position where the participant should be inserted in the participant list. dashboard.register_participant 'auditor', AuditParticipant, :pos => 'last' * last : it's the default, places the participant at the end of the list * first : top of the list * before : implies :override => false, places before the existing participant with the same regex * after : implies :override => false, places after the last existing participant with the same regex * over : overrides in the same position (while the regular, default overide removes and then places the new participant at the end of the list)
[ "Registers", "a", "participant", "in", "the", "engine", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dashboard.rb#L859-L873
20,163
jmettraux/ruote
lib/ruote/exp/ro_attributes.rb
Ruote::Exp.FlowExpression.has_attribute
def has_attribute(*args) args.each { |a| a = a.to_s; return a if attributes[a] != nil } nil end
ruby
def has_attribute(*args) args.each { |a| a = a.to_s; return a if attributes[a] != nil } nil end
[ "def", "has_attribute", "(", "*", "args", ")", "args", ".", "each", "{", "|", "a", "|", "a", "=", "a", ".", "to_s", ";", "return", "a", "if", "attributes", "[", "a", "]", "!=", "nil", "}", "nil", "end" ]
Given a list of attribute names, returns the first attribute name for which there is a value.
[ "Given", "a", "list", "of", "attribute", "names", "returns", "the", "first", "attribute", "name", "for", "which", "there", "is", "a", "value", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/ro_attributes.rb#L37-L42
20,164
jmettraux/ruote
lib/ruote/exp/ro_attributes.rb
Ruote::Exp.FlowExpression.attribute
def attribute(n, workitem=h.applied_workitem, options={}) n = n.to_s default = options[:default] escape = options[:escape] string = options[:to_s] || options[:string] v = attributes[n] v = if v == nil default elsif escape v else dsub(v, workitem) end v = v.to_s if v and string v end
ruby
def attribute(n, workitem=h.applied_workitem, options={}) n = n.to_s default = options[:default] escape = options[:escape] string = options[:to_s] || options[:string] v = attributes[n] v = if v == nil default elsif escape v else dsub(v, workitem) end v = v.to_s if v and string v end
[ "def", "attribute", "(", "n", ",", "workitem", "=", "h", ".", "applied_workitem", ",", "options", "=", "{", "}", ")", "n", "=", "n", ".", "to_s", "default", "=", "options", "[", ":default", "]", "escape", "=", "options", "[", ":escape", "]", "string", "=", "options", "[", ":to_s", "]", "||", "options", "[", ":string", "]", "v", "=", "attributes", "[", "n", "]", "v", "=", "if", "v", "==", "nil", "default", "elsif", "escape", "v", "else", "dsub", "(", "v", ",", "workitem", ")", "end", "v", "=", "v", ".", "to_s", "if", "v", "and", "string", "v", "end" ]
Looks up the value for attribute n.
[ "Looks", "up", "the", "value", "for", "attribute", "n", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/ro_attributes.rb#L48-L69
20,165
jmettraux/ruote
lib/ruote/exp/ro_attributes.rb
Ruote::Exp.FlowExpression.att
def att(keys, values, opts={}) default = opts[:default] || values.first val = Array(keys).collect { |key| attribute(key) }.compact.first.to_s values.include?(val) ? val : default end
ruby
def att(keys, values, opts={}) default = opts[:default] || values.first val = Array(keys).collect { |key| attribute(key) }.compact.first.to_s values.include?(val) ? val : default end
[ "def", "att", "(", "keys", ",", "values", ",", "opts", "=", "{", "}", ")", "default", "=", "opts", "[", ":default", "]", "||", "values", ".", "first", "val", "=", "Array", "(", "keys", ")", ".", "collect", "{", "|", "key", "|", "attribute", "(", "key", ")", "}", ".", "compact", ".", "first", ".", "to_s", "values", ".", "include?", "(", "val", ")", "?", "val", ":", "default", "end" ]
Returns the value for attribute 'key', this value should be present in the array list 'values'. If not, the default value is returned. By default, the default value is the first element of 'values'.
[ "Returns", "the", "value", "for", "attribute", "key", "this", "value", "should", "be", "present", "in", "the", "array", "list", "values", ".", "If", "not", "the", "default", "value", "is", "returned", ".", "By", "default", "the", "default", "value", "is", "the", "first", "element", "of", "values", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/ro_attributes.rb#L75-L82
20,166
jmettraux/ruote
lib/ruote/exp/ro_attributes.rb
Ruote::Exp.FlowExpression.lookup_val_prefix
def lookup_val_prefix(prefix, att_options={}) lval( [ prefix ] + [ 'val', 'value' ].map { |s| "#{prefix}_#{s}" }, %w[ v var variable ].map { |s| "#{prefix}_#{s}" }, %w[ f fld field ].map { |s| "#{prefix}_#{s}" }, att_options) end
ruby
def lookup_val_prefix(prefix, att_options={}) lval( [ prefix ] + [ 'val', 'value' ].map { |s| "#{prefix}_#{s}" }, %w[ v var variable ].map { |s| "#{prefix}_#{s}" }, %w[ f fld field ].map { |s| "#{prefix}_#{s}" }, att_options) end
[ "def", "lookup_val_prefix", "(", "prefix", ",", "att_options", "=", "{", "}", ")", "lval", "(", "[", "prefix", "]", "+", "[", "'val'", ",", "'value'", "]", ".", "map", "{", "|", "s", "|", "\"#{prefix}_#{s}\"", "}", ",", "%w[", "v", "var", "variable", "]", ".", "map", "{", "|", "s", "|", "\"#{prefix}_#{s}\"", "}", ",", "%w[", "f", "fld", "field", "]", ".", "map", "{", "|", "s", "|", "\"#{prefix}_#{s}\"", "}", ",", "att_options", ")", "end" ]
prefix = 'on' => will lookup on, on_val, on_value, on_v, on_var, on_variable, on_f, on_fld, on_field...
[ "prefix", "=", "on", "=", ">", "will", "lookup", "on", "on_val", "on_value", "on_v", "on_var", "on_variable", "on_f", "on_fld", "on_field", "..." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/ro_attributes.rb#L87-L94
20,167
jmettraux/ruote
lib/ruote/exp/ro_attributes.rb
Ruote::Exp.FlowExpression.compile_atts
def compile_atts(opts={}) attributes.keys.each_with_object({}) { |k, r| r[dsub(k)] = attribute(k, h.applied_workitem, opts) } end
ruby
def compile_atts(opts={}) attributes.keys.each_with_object({}) { |k, r| r[dsub(k)] = attribute(k, h.applied_workitem, opts) } end
[ "def", "compile_atts", "(", "opts", "=", "{", "}", ")", "attributes", ".", "keys", ".", "each_with_object", "(", "{", "}", ")", "{", "|", "k", ",", "r", "|", "r", "[", "dsub", "(", "k", ")", "]", "=", "attribute", "(", "k", ",", "h", ".", "applied_workitem", ",", "opts", ")", "}", "end" ]
Returns a Hash containing all attributes set for an expression with their values resolved.
[ "Returns", "a", "Hash", "containing", "all", "attributes", "set", "for", "an", "expression", "with", "their", "values", "resolved", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/ro_attributes.rb#L108-L113
20,168
jmettraux/ruote
lib/ruote/exp/ro_attributes.rb
Ruote::Exp.FlowExpression.attribute_text
def attribute_text(workitem=h.applied_workitem) text = attributes.keys.find { |k| attributes[k] == nil } dsub(text.to_s, workitem) end
ruby
def attribute_text(workitem=h.applied_workitem) text = attributes.keys.find { |k| attributes[k] == nil } dsub(text.to_s, workitem) end
[ "def", "attribute_text", "(", "workitem", "=", "h", ".", "applied_workitem", ")", "text", "=", "attributes", ".", "keys", ".", "find", "{", "|", "k", "|", "attributes", "[", "k", "]", "==", "nil", "}", "dsub", "(", "text", ".", "to_s", ",", "workitem", ")", "end" ]
Given something like sequence do participant 'alpha' end in the context of the participant expression attribute_text() will yield 'alpha'. Note : an empty text returns '', not the nil value.
[ "Given", "something", "like" ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/ro_attributes.rb#L129-L134
20,169
jmettraux/ruote
lib/ruote/exp/ro_attributes.rb
Ruote::Exp.FlowExpression.determine_tos
def determine_tos to_v = attribute(:to_v) || attribute(:to_var) || attribute(:to_variable) to_f = attribute(:to_f) || attribute(:to_fld) || attribute(:to_field) if to = attribute(:to) pre, key = to.split(':') pre, key = [ 'f', pre ] if key == nil if pre.match(/^f/) to_f = key else to_v = key end end [ to_v, to_f ] end
ruby
def determine_tos to_v = attribute(:to_v) || attribute(:to_var) || attribute(:to_variable) to_f = attribute(:to_f) || attribute(:to_fld) || attribute(:to_field) if to = attribute(:to) pre, key = to.split(':') pre, key = [ 'f', pre ] if key == nil if pre.match(/^f/) to_f = key else to_v = key end end [ to_v, to_f ] end
[ "def", "determine_tos", "to_v", "=", "attribute", "(", ":to_v", ")", "||", "attribute", "(", ":to_var", ")", "||", "attribute", "(", ":to_variable", ")", "to_f", "=", "attribute", "(", ":to_f", ")", "||", "attribute", "(", ":to_fld", ")", "||", "attribute", "(", ":to_field", ")", "if", "to", "=", "attribute", "(", ":to", ")", "pre", ",", "key", "=", "to", ".", "split", "(", "':'", ")", "pre", ",", "key", "=", "[", "'f'", ",", "pre", "]", "if", "key", "==", "nil", "if", "pre", ".", "match", "(", "/", "/", ")", "to_f", "=", "key", "else", "to_v", "=", "key", "end", "end", "[", "to_v", ",", "to_f", "]", "end" ]
'tos' meaning 'many "to"'
[ "tos", "meaning", "many", "to" ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/ro_attributes.rb#L157-L173
20,170
jmettraux/ruote
lib/ruote/exp/flow_expression.rb
Ruote::Exp.FlowExpression.do_apply
def do_apply(msg) if msg['state'] == 'paused' return pause_on_apply(msg) end if msg['flavour'].nil? && (aw = attribute(:await)) return await(aw, msg) end unless Condition.apply?(attribute(:if), attribute(:unless)) return do_reply_to_parent(h.applied_workitem) end pi = h.parent_id reply_immediately = false if attribute(:scope).to_s == 'true' h.variables ||= {} end if attribute(:forget).to_s == 'true' h.variables = compile_variables h.parent_id = nil h.forgotten = true reply_immediately = true elsif attribute(:lose).to_s == 'true' h.lost = true elsif msg['flanking'] or (attribute(:flank).to_s == 'true') h.flanking = true reply_immediately = true end if reply_immediately and pi @context.storage.put_msg( 'reply', 'fei' => pi, 'workitem' => Ruote.fulldup(h.applied_workitem), 'flanking' => h.flanking) end filter consider_tag consider_timers apply end
ruby
def do_apply(msg) if msg['state'] == 'paused' return pause_on_apply(msg) end if msg['flavour'].nil? && (aw = attribute(:await)) return await(aw, msg) end unless Condition.apply?(attribute(:if), attribute(:unless)) return do_reply_to_parent(h.applied_workitem) end pi = h.parent_id reply_immediately = false if attribute(:scope).to_s == 'true' h.variables ||= {} end if attribute(:forget).to_s == 'true' h.variables = compile_variables h.parent_id = nil h.forgotten = true reply_immediately = true elsif attribute(:lose).to_s == 'true' h.lost = true elsif msg['flanking'] or (attribute(:flank).to_s == 'true') h.flanking = true reply_immediately = true end if reply_immediately and pi @context.storage.put_msg( 'reply', 'fei' => pi, 'workitem' => Ruote.fulldup(h.applied_workitem), 'flanking' => h.flanking) end filter consider_tag consider_timers apply end
[ "def", "do_apply", "(", "msg", ")", "if", "msg", "[", "'state'", "]", "==", "'paused'", "return", "pause_on_apply", "(", "msg", ")", "end", "if", "msg", "[", "'flavour'", "]", ".", "nil?", "&&", "(", "aw", "=", "attribute", "(", ":await", ")", ")", "return", "await", "(", "aw", ",", "msg", ")", "end", "unless", "Condition", ".", "apply?", "(", "attribute", "(", ":if", ")", ",", "attribute", "(", ":unless", ")", ")", "return", "do_reply_to_parent", "(", "h", ".", "applied_workitem", ")", "end", "pi", "=", "h", ".", "parent_id", "reply_immediately", "=", "false", "if", "attribute", "(", ":scope", ")", ".", "to_s", "==", "'true'", "h", ".", "variables", "||=", "{", "}", "end", "if", "attribute", "(", ":forget", ")", ".", "to_s", "==", "'true'", "h", ".", "variables", "=", "compile_variables", "h", ".", "parent_id", "=", "nil", "h", ".", "forgotten", "=", "true", "reply_immediately", "=", "true", "elsif", "attribute", "(", ":lose", ")", ".", "to_s", "==", "'true'", "h", ".", "lost", "=", "true", "elsif", "msg", "[", "'flanking'", "]", "or", "(", "attribute", "(", ":flank", ")", ".", "to_s", "==", "'true'", ")", "h", ".", "flanking", "=", "true", "reply_immediately", "=", "true", "end", "if", "reply_immediately", "and", "pi", "@context", ".", "storage", ".", "put_msg", "(", "'reply'", ",", "'fei'", "=>", "pi", ",", "'workitem'", "=>", "Ruote", ".", "fulldup", "(", "h", ".", "applied_workitem", ")", ",", "'flanking'", "=>", "h", ".", "flanking", ")", "end", "filter", "consider_tag", "consider_timers", "apply", "end" ]
Called by the worker when it has just created this FlowExpression and wants to apply it.
[ "Called", "by", "the", "worker", "when", "it", "has", "just", "created", "this", "FlowExpression", "and", "wants", "to", "apply", "it", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/flow_expression.rb#L356-L415
20,171
jmettraux/ruote
lib/ruote/exp/flow_expression.rb
Ruote::Exp.FlowExpression.do_reply_to_parent
def do_reply_to_parent(workitem, delete=true) # propagate the cancel "flavour" back, so that one can know # why a branch got cancelled. flavour = if @msg.nil? nil elsif @msg['action'] == 'cancel' @msg['flavour'] || 'cancel' elsif h.state.nil? nil else @msg['flavour'] end # deal with the timers and the schedules %w[ timeout_schedule_id job_id ].each do |sid| @context.storage.delete_schedule(h[sid]) if h[sid] end # # legacy schedule ids, to be removed for ruote 2.4.0 @context.storage.delete_schedule(h.schedule_id) if h.schedule_id # # time-driven exps like cron, wait and once now all use h.schedule_id h.timers.each do |schedule_id, action| @context.storage.delete_schedule(schedule_id) end if h.timers # cancel flanking expressions if any cancel_flanks(h.state == 'dying' ? 'kill' : nil) # trigger or vanilla reply if h.state == 'failing' # on_error is implicit (#do_fail got called) trigger('on_error', workitem) elsif h.state == 'cancelling' && h.on_cancel trigger('on_cancel', workitem) elsif h.state == 'cancelling' && h.on_re_apply trigger('on_re_apply', workitem) elsif h.state == 'timing_out' && h.on_timeout trigger('on_timeout', workitem) elsif h.state == nil && h.on_reply trigger('on_reply', workitem) elsif h.flanking && h.state.nil? # # do vanish do_unpersist elsif h.lost && h.state.nil? # # do not reply, sit here (and wait for cancellation probably) do_persist elsif h.trigger && workitem['fields']["__#{h.trigger}__"] # # the "second take" trigger(h.trigger, workitem) else # vanilla reply filter(workitem) if h.state.nil? f = h.state.nil? && attribute(:vars_to_f) Ruote.set(workitem['fields'], f, h.variables) if f workitem['sub_wf_name'] = h.applied_workitem['sub_wf_name'] workitem['sub_wf_revision'] = h.applied_workitem['sub_wf_revision'] leave_tag(workitem) if h.tagname (do_unpersist || return) if delete # remove expression from storage if h.parent_id && ! h.attached @context.storage.put_msg( 'reply', 'fei' => h.parent_id, 'workitem' => workitem.merge!('fei' => h.fei), 'updated_tree' => h.updated_tree, # nil most of the time 'flavour' => flavour) else @context.storage.put_msg( (h.forgotten || h.attached) ? 'ceased' : 'terminated', 'wfid' => h.fei['wfid'], 'fei' => h.fei, 'workitem' => workitem, 'variables' => h.variables, 'flavour' => flavour) if h.state.nil? && h.on_terminate == 'regenerate' && ! (h.forgotten || h.attached) then @context.storage.put_msg( 'regenerate', 'wfid' => h.fei['wfid'], 'tree' => h.original_tree, 'workitem' => workitem, 'variables' => h.variables, 'flavour' => flavour) #'stash' => end end end end
ruby
def do_reply_to_parent(workitem, delete=true) # propagate the cancel "flavour" back, so that one can know # why a branch got cancelled. flavour = if @msg.nil? nil elsif @msg['action'] == 'cancel' @msg['flavour'] || 'cancel' elsif h.state.nil? nil else @msg['flavour'] end # deal with the timers and the schedules %w[ timeout_schedule_id job_id ].each do |sid| @context.storage.delete_schedule(h[sid]) if h[sid] end # # legacy schedule ids, to be removed for ruote 2.4.0 @context.storage.delete_schedule(h.schedule_id) if h.schedule_id # # time-driven exps like cron, wait and once now all use h.schedule_id h.timers.each do |schedule_id, action| @context.storage.delete_schedule(schedule_id) end if h.timers # cancel flanking expressions if any cancel_flanks(h.state == 'dying' ? 'kill' : nil) # trigger or vanilla reply if h.state == 'failing' # on_error is implicit (#do_fail got called) trigger('on_error', workitem) elsif h.state == 'cancelling' && h.on_cancel trigger('on_cancel', workitem) elsif h.state == 'cancelling' && h.on_re_apply trigger('on_re_apply', workitem) elsif h.state == 'timing_out' && h.on_timeout trigger('on_timeout', workitem) elsif h.state == nil && h.on_reply trigger('on_reply', workitem) elsif h.flanking && h.state.nil? # # do vanish do_unpersist elsif h.lost && h.state.nil? # # do not reply, sit here (and wait for cancellation probably) do_persist elsif h.trigger && workitem['fields']["__#{h.trigger}__"] # # the "second take" trigger(h.trigger, workitem) else # vanilla reply filter(workitem) if h.state.nil? f = h.state.nil? && attribute(:vars_to_f) Ruote.set(workitem['fields'], f, h.variables) if f workitem['sub_wf_name'] = h.applied_workitem['sub_wf_name'] workitem['sub_wf_revision'] = h.applied_workitem['sub_wf_revision'] leave_tag(workitem) if h.tagname (do_unpersist || return) if delete # remove expression from storage if h.parent_id && ! h.attached @context.storage.put_msg( 'reply', 'fei' => h.parent_id, 'workitem' => workitem.merge!('fei' => h.fei), 'updated_tree' => h.updated_tree, # nil most of the time 'flavour' => flavour) else @context.storage.put_msg( (h.forgotten || h.attached) ? 'ceased' : 'terminated', 'wfid' => h.fei['wfid'], 'fei' => h.fei, 'workitem' => workitem, 'variables' => h.variables, 'flavour' => flavour) if h.state.nil? && h.on_terminate == 'regenerate' && ! (h.forgotten || h.attached) then @context.storage.put_msg( 'regenerate', 'wfid' => h.fei['wfid'], 'tree' => h.original_tree, 'workitem' => workitem, 'variables' => h.variables, 'flavour' => flavour) #'stash' => end end end end
[ "def", "do_reply_to_parent", "(", "workitem", ",", "delete", "=", "true", ")", "# propagate the cancel \"flavour\" back, so that one can know", "# why a branch got cancelled.", "flavour", "=", "if", "@msg", ".", "nil?", "nil", "elsif", "@msg", "[", "'action'", "]", "==", "'cancel'", "@msg", "[", "'flavour'", "]", "||", "'cancel'", "elsif", "h", ".", "state", ".", "nil?", "nil", "else", "@msg", "[", "'flavour'", "]", "end", "# deal with the timers and the schedules", "%w[", "timeout_schedule_id", "job_id", "]", ".", "each", "do", "|", "sid", "|", "@context", ".", "storage", ".", "delete_schedule", "(", "h", "[", "sid", "]", ")", "if", "h", "[", "sid", "]", "end", "#", "# legacy schedule ids, to be removed for ruote 2.4.0", "@context", ".", "storage", ".", "delete_schedule", "(", "h", ".", "schedule_id", ")", "if", "h", ".", "schedule_id", "#", "# time-driven exps like cron, wait and once now all use h.schedule_id", "h", ".", "timers", ".", "each", "do", "|", "schedule_id", ",", "action", "|", "@context", ".", "storage", ".", "delete_schedule", "(", "schedule_id", ")", "end", "if", "h", ".", "timers", "# cancel flanking expressions if any", "cancel_flanks", "(", "h", ".", "state", "==", "'dying'", "?", "'kill'", ":", "nil", ")", "# trigger or vanilla reply", "if", "h", ".", "state", "==", "'failing'", "# on_error is implicit (#do_fail got called)", "trigger", "(", "'on_error'", ",", "workitem", ")", "elsif", "h", ".", "state", "==", "'cancelling'", "&&", "h", ".", "on_cancel", "trigger", "(", "'on_cancel'", ",", "workitem", ")", "elsif", "h", ".", "state", "==", "'cancelling'", "&&", "h", ".", "on_re_apply", "trigger", "(", "'on_re_apply'", ",", "workitem", ")", "elsif", "h", ".", "state", "==", "'timing_out'", "&&", "h", ".", "on_timeout", "trigger", "(", "'on_timeout'", ",", "workitem", ")", "elsif", "h", ".", "state", "==", "nil", "&&", "h", ".", "on_reply", "trigger", "(", "'on_reply'", ",", "workitem", ")", "elsif", "h", ".", "flanking", "&&", "h", ".", "state", ".", "nil?", "#", "# do vanish", "do_unpersist", "elsif", "h", ".", "lost", "&&", "h", ".", "state", ".", "nil?", "#", "# do not reply, sit here (and wait for cancellation probably)", "do_persist", "elsif", "h", ".", "trigger", "&&", "workitem", "[", "'fields'", "]", "[", "\"__#{h.trigger}__\"", "]", "#", "# the \"second take\"", "trigger", "(", "h", ".", "trigger", ",", "workitem", ")", "else", "# vanilla reply", "filter", "(", "workitem", ")", "if", "h", ".", "state", ".", "nil?", "f", "=", "h", ".", "state", ".", "nil?", "&&", "attribute", "(", ":vars_to_f", ")", "Ruote", ".", "set", "(", "workitem", "[", "'fields'", "]", ",", "f", ",", "h", ".", "variables", ")", "if", "f", "workitem", "[", "'sub_wf_name'", "]", "=", "h", ".", "applied_workitem", "[", "'sub_wf_name'", "]", "workitem", "[", "'sub_wf_revision'", "]", "=", "h", ".", "applied_workitem", "[", "'sub_wf_revision'", "]", "leave_tag", "(", "workitem", ")", "if", "h", ".", "tagname", "(", "do_unpersist", "||", "return", ")", "if", "delete", "# remove expression from storage", "if", "h", ".", "parent_id", "&&", "!", "h", ".", "attached", "@context", ".", "storage", ".", "put_msg", "(", "'reply'", ",", "'fei'", "=>", "h", ".", "parent_id", ",", "'workitem'", "=>", "workitem", ".", "merge!", "(", "'fei'", "=>", "h", ".", "fei", ")", ",", "'updated_tree'", "=>", "h", ".", "updated_tree", ",", "# nil most of the time", "'flavour'", "=>", "flavour", ")", "else", "@context", ".", "storage", ".", "put_msg", "(", "(", "h", ".", "forgotten", "||", "h", ".", "attached", ")", "?", "'ceased'", ":", "'terminated'", ",", "'wfid'", "=>", "h", ".", "fei", "[", "'wfid'", "]", ",", "'fei'", "=>", "h", ".", "fei", ",", "'workitem'", "=>", "workitem", ",", "'variables'", "=>", "h", ".", "variables", ",", "'flavour'", "=>", "flavour", ")", "if", "h", ".", "state", ".", "nil?", "&&", "h", ".", "on_terminate", "==", "'regenerate'", "&&", "!", "(", "h", ".", "forgotten", "||", "h", ".", "attached", ")", "then", "@context", ".", "storage", ".", "put_msg", "(", "'regenerate'", ",", "'wfid'", "=>", "h", ".", "fei", "[", "'wfid'", "]", ",", "'tree'", "=>", "h", ".", "original_tree", ",", "'workitem'", "=>", "workitem", ",", "'variables'", "=>", "h", ".", "variables", ",", "'flavour'", "=>", "flavour", ")", "#'stash' =>", "end", "end", "end", "end" ]
The essence of the reply_to_parent job...
[ "The", "essence", "of", "the", "reply_to_parent", "job", "..." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/flow_expression.rb#L477-L602
20,172
jmettraux/ruote
lib/ruote/exp/flow_expression.rb
Ruote::Exp.FlowExpression.do_pause
def do_pause(msg) return if h.state != nil h.state = 'paused' do_persist || return h.children.each { |i| @context.storage.put_msg('pause', 'fei' => i) } unless msg['breakpoint'] end
ruby
def do_pause(msg) return if h.state != nil h.state = 'paused' do_persist || return h.children.each { |i| @context.storage.put_msg('pause', 'fei' => i) } unless msg['breakpoint'] end
[ "def", "do_pause", "(", "msg", ")", "return", "if", "h", ".", "state", "!=", "nil", "h", ".", "state", "=", "'paused'", "do_persist", "||", "return", "h", ".", "children", ".", "each", "{", "|", "i", "|", "@context", ".", "storage", ".", "put_msg", "(", "'pause'", ",", "'fei'", "=>", "i", ")", "}", "unless", "msg", "[", "'breakpoint'", "]", "end" ]
Expression received a "pause" message. Will put the expression in the "paused" state and then pass the message to the children. If the expression is in a non-nil state (failed, timed_out, ...), the message will be ignored.
[ "Expression", "received", "a", "pause", "message", ".", "Will", "put", "the", "expression", "in", "the", "paused", "state", "and", "then", "pass", "the", "message", "to", "the", "children", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/flow_expression.rb#L787-L798
20,173
jmettraux/ruote
lib/ruote/exp/flow_expression.rb
Ruote::Exp.FlowExpression.ancestor?
def ancestor?(fei) fei = fei.to_h if fei.respond_to?(:to_h) return false unless h.parent_id return true if h.parent_id == fei parent.ancestor?(fei) end
ruby
def ancestor?(fei) fei = fei.to_h if fei.respond_to?(:to_h) return false unless h.parent_id return true if h.parent_id == fei parent.ancestor?(fei) end
[ "def", "ancestor?", "(", "fei", ")", "fei", "=", "fei", ".", "to_h", "if", "fei", ".", "respond_to?", "(", ":to_h", ")", "return", "false", "unless", "h", ".", "parent_id", "return", "true", "if", "h", ".", "parent_id", "==", "fei", "parent", ".", "ancestor?", "(", "fei", ")", "end" ]
Returns true if the given fei points to an expression in the parent chain of this expression.
[ "Returns", "true", "if", "the", "given", "fei", "points", "to", "an", "expression", "in", "the", "parent", "chain", "of", "this", "expression", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/flow_expression.rb#L866-L874
20,174
jmettraux/ruote
lib/ruote/exp/flow_expression.rb
Ruote::Exp.FlowExpression.pre_apply_child
def pre_apply_child(child_index, workitem, forget) child_fei = h.fei.merge( 'expid' => "#{h.fei['expid']}_#{child_index}", 'subid' => Ruote.generate_subid(h.fei.inspect)) h.children << child_fei unless forget msg = { 'fei' => child_fei, 'tree' => tree.last[child_index], 'parent_id' => forget ? nil : h.fei, 'variables' => forget ? compile_variables : nil, 'workitem' => workitem } msg['forgotten'] = true if forget msg end
ruby
def pre_apply_child(child_index, workitem, forget) child_fei = h.fei.merge( 'expid' => "#{h.fei['expid']}_#{child_index}", 'subid' => Ruote.generate_subid(h.fei.inspect)) h.children << child_fei unless forget msg = { 'fei' => child_fei, 'tree' => tree.last[child_index], 'parent_id' => forget ? nil : h.fei, 'variables' => forget ? compile_variables : nil, 'workitem' => workitem } msg['forgotten'] = true if forget msg end
[ "def", "pre_apply_child", "(", "child_index", ",", "workitem", ",", "forget", ")", "child_fei", "=", "h", ".", "fei", ".", "merge", "(", "'expid'", "=>", "\"#{h.fei['expid']}_#{child_index}\"", ",", "'subid'", "=>", "Ruote", ".", "generate_subid", "(", "h", ".", "fei", ".", "inspect", ")", ")", "h", ".", "children", "<<", "child_fei", "unless", "forget", "msg", "=", "{", "'fei'", "=>", "child_fei", ",", "'tree'", "=>", "tree", ".", "last", "[", "child_index", "]", ",", "'parent_id'", "=>", "forget", "?", "nil", ":", "h", ".", "fei", ",", "'variables'", "=>", "forget", "?", "compile_variables", ":", "nil", ",", "'workitem'", "=>", "workitem", "}", "msg", "[", "'forgotten'", "]", "=", "true", "if", "forget", "msg", "end" ]
Used locally but also by ConcurrenceExpression, when preparing children before they get applied.
[ "Used", "locally", "but", "also", "by", "ConcurrenceExpression", "when", "preparing", "children", "before", "they", "get", "applied", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/flow_expression.rb#L965-L983
20,175
jmettraux/ruote
lib/ruote/exp/flow_expression.rb
Ruote::Exp.FlowExpression.apply_child
def apply_child(child_index, workitem, forget=false) msg = pre_apply_child(child_index, workitem, forget) persist_or_raise unless forget # no need to persist the parent (this) if the child is to be forgotten @context.storage.put_msg('apply', msg) end
ruby
def apply_child(child_index, workitem, forget=false) msg = pre_apply_child(child_index, workitem, forget) persist_or_raise unless forget # no need to persist the parent (this) if the child is to be forgotten @context.storage.put_msg('apply', msg) end
[ "def", "apply_child", "(", "child_index", ",", "workitem", ",", "forget", "=", "false", ")", "msg", "=", "pre_apply_child", "(", "child_index", ",", "workitem", ",", "forget", ")", "persist_or_raise", "unless", "forget", "# no need to persist the parent (this) if the child is to be forgotten", "@context", ".", "storage", ".", "put_msg", "(", "'apply'", ",", "msg", ")", "end" ]
Used by expressions when, well, applying a child expression of theirs.
[ "Used", "by", "expressions", "when", "well", "applying", "a", "child", "expression", "of", "theirs", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/flow_expression.rb#L987-L995
20,176
jmettraux/ruote
lib/ruote/exp/flow_expression.rb
Ruote::Exp.FlowExpression.leave_tag
def leave_tag(workitem) unset_variable(h.tagname) Ruote::Workitem.new(workitem).send(:remove_tag, h.tagname) @context.storage.put_msg( 'left_tag', 'tag' => h.tagname, 'full_tag' => h.full_tagname, 'fei' => h.fei, 'workitem' => workitem) return unless h.full_tagname # for backward compatibility r = root return unless r && r.variables # might happen r.variables.delete(h.full_tagname) state = case (h.trigger || h.state) when 'on_cancel' then 'cancelled' when 'on_error' then 'failed' when 'on_timeout' then 'timed out' when 'on_re_apply' then nil when 'cancelling' then 'cancelled' when 'dying' then 'killed' else nil end (r.variables['__past_tags__'] ||= []) << [ h.full_tagname, fei.sid, state, Ruote.now_to_utc_s, Ruote.fulldup(h.variables) # not fullduping here triggers a segfault at some point with YAJL ] r.do_persist unless r.fei == self.fei end
ruby
def leave_tag(workitem) unset_variable(h.tagname) Ruote::Workitem.new(workitem).send(:remove_tag, h.tagname) @context.storage.put_msg( 'left_tag', 'tag' => h.tagname, 'full_tag' => h.full_tagname, 'fei' => h.fei, 'workitem' => workitem) return unless h.full_tagname # for backward compatibility r = root return unless r && r.variables # might happen r.variables.delete(h.full_tagname) state = case (h.trigger || h.state) when 'on_cancel' then 'cancelled' when 'on_error' then 'failed' when 'on_timeout' then 'timed out' when 'on_re_apply' then nil when 'cancelling' then 'cancelled' when 'dying' then 'killed' else nil end (r.variables['__past_tags__'] ||= []) << [ h.full_tagname, fei.sid, state, Ruote.now_to_utc_s, Ruote.fulldup(h.variables) # not fullduping here triggers a segfault at some point with YAJL ] r.do_persist unless r.fei == self.fei end
[ "def", "leave_tag", "(", "workitem", ")", "unset_variable", "(", "h", ".", "tagname", ")", "Ruote", "::", "Workitem", ".", "new", "(", "workitem", ")", ".", "send", "(", ":remove_tag", ",", "h", ".", "tagname", ")", "@context", ".", "storage", ".", "put_msg", "(", "'left_tag'", ",", "'tag'", "=>", "h", ".", "tagname", ",", "'full_tag'", "=>", "h", ".", "full_tagname", ",", "'fei'", "=>", "h", ".", "fei", ",", "'workitem'", "=>", "workitem", ")", "return", "unless", "h", ".", "full_tagname", "# for backward compatibility", "r", "=", "root", "return", "unless", "r", "&&", "r", ".", "variables", "# might happen", "r", ".", "variables", ".", "delete", "(", "h", ".", "full_tagname", ")", "state", "=", "case", "(", "h", ".", "trigger", "||", "h", ".", "state", ")", "when", "'on_cancel'", "then", "'cancelled'", "when", "'on_error'", "then", "'failed'", "when", "'on_timeout'", "then", "'timed out'", "when", "'on_re_apply'", "then", "nil", "when", "'cancelling'", "then", "'cancelled'", "when", "'dying'", "then", "'killed'", "else", "nil", "end", "(", "r", ".", "variables", "[", "'__past_tags__'", "]", "||=", "[", "]", ")", "<<", "[", "h", ".", "full_tagname", ",", "fei", ".", "sid", ",", "state", ",", "Ruote", ".", "now_to_utc_s", ",", "Ruote", ".", "fulldup", "(", "h", ".", "variables", ")", "# not fullduping here triggers a segfault at some point with YAJL", "]", "r", ".", "do_persist", "unless", "r", ".", "fei", "==", "self", ".", "fei", "end" ]
Called when the expression is about to reply to its parent and wants to get rid of its tags.
[ "Called", "when", "the", "expression", "is", "about", "to", "reply", "to", "its", "parent", "and", "wants", "to", "get", "rid", "of", "its", "tags", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/flow_expression.rb#L1041-L1085
20,177
jmettraux/ruote
lib/ruote/util/filter.rb
Ruote.RuleSession.do_merge
def do_merge(field, target, value) value = Rufus::Json.dup(value) if target.is_a?(Array) target.push(value) elsif value.is_a?(Hash) target.merge!(value) else # deal with non Hash target[field.split('.').last] = value end target.delete('~') target.delete('~~') end
ruby
def do_merge(field, target, value) value = Rufus::Json.dup(value) if target.is_a?(Array) target.push(value) elsif value.is_a?(Hash) target.merge!(value) else # deal with non Hash target[field.split('.').last] = value end target.delete('~') target.delete('~~') end
[ "def", "do_merge", "(", "field", ",", "target", ",", "value", ")", "value", "=", "Rufus", "::", "Json", ".", "dup", "(", "value", ")", "if", "target", ".", "is_a?", "(", "Array", ")", "target", ".", "push", "(", "value", ")", "elsif", "value", ".", "is_a?", "(", "Hash", ")", "target", ".", "merge!", "(", "value", ")", "else", "# deal with non Hash", "target", "[", "field", ".", "split", "(", "'.'", ")", ".", "last", "]", "=", "value", "end", "target", ".", "delete", "(", "'~'", ")", "target", ".", "delete", "(", "'~~'", ")", "end" ]
Used by both _merge_to and _merge_from
[ "Used", "by", "both", "_merge_to", "and", "_merge_from" ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/util/filter.rb#L275-L289
20,178
jmettraux/ruote
lib/ruote/dboard/process_status.rb
Ruote.ProcessStatus.tags
def tags variables ? Hash[variables.select { |k, v| Ruote.is_a_fei?(v) }] : nil end
ruby
def tags variables ? Hash[variables.select { |k, v| Ruote.is_a_fei?(v) }] : nil end
[ "def", "tags", "variables", "?", "Hash", "[", "variables", ".", "select", "{", "|", "k", ",", "v", "|", "Ruote", ".", "is_a_fei?", "(", "v", ")", "}", "]", ":", "nil", "end" ]
Returns a hash tagname => fei of tags set at the root of the process instance. Returns nil if there is no defined root expression.
[ "Returns", "a", "hash", "tagname", "=", ">", "fei", "of", "tags", "set", "at", "the", "root", "of", "the", "process", "instance", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dboard/process_status.rb#L153-L156
20,179
jmettraux/ruote
lib/ruote/dboard/process_status.rb
Ruote.ProcessStatus.all_tags
def all_tags all_variables.remap do |(fei, vars), h| vars.each { |k, v| (h[k] ||= []) << v if Ruote.is_a_fei?(v) } end end
ruby
def all_tags all_variables.remap do |(fei, vars), h| vars.each { |k, v| (h[k] ||= []) << v if Ruote.is_a_fei?(v) } end end
[ "def", "all_tags", "all_variables", ".", "remap", "do", "|", "(", "fei", ",", "vars", ")", ",", "h", "|", "vars", ".", "each", "{", "|", "k", ",", "v", "|", "(", "h", "[", "k", "]", "||=", "[", "]", ")", "<<", "v", "if", "Ruote", ".", "is_a_fei?", "(", "v", ")", "}", "end", "end" ]
Returns a hash tagname => array of feis of all the tags set in the process instance.
[ "Returns", "a", "hash", "tagname", "=", ">", "array", "of", "feis", "of", "all", "the", "tags", "set", "in", "the", "process", "instance", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dboard/process_status.rb#L161-L166
20,180
jmettraux/ruote
lib/ruote/dboard/process_status.rb
Ruote.ProcessStatus.wfid
def wfid l = [ @expressions, @errors, @stored_workitems ].find { |l| l.any? } l ? l.first.fei.wfid : nil end
ruby
def wfid l = [ @expressions, @errors, @stored_workitems ].find { |l| l.any? } l ? l.first.fei.wfid : nil end
[ "def", "wfid", "l", "=", "[", "@expressions", ",", "@errors", ",", "@stored_workitems", "]", ".", "find", "{", "|", "l", "|", "l", ".", "any?", "}", "l", "?", "l", ".", "first", ".", "fei", ".", "wfid", ":", "nil", "end" ]
Returns the unique identifier for this process instance.
[ "Returns", "the", "unique", "identifier", "for", "this", "process", "instance", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dboard/process_status.rb#L197-L202
20,181
jmettraux/ruote
lib/ruote/dboard/process_status.rb
Ruote.ProcessStatus.position
def position workitems.collect { |wi| r = [ wi.fei.sid, wi.participant_name ] params = (wi.fields['params'] || {}).dup params.delete('ref') if err = errors.find { |e| e.fei == wi.fei } params['error'] = err.message end r << params r } end
ruby
def position workitems.collect { |wi| r = [ wi.fei.sid, wi.participant_name ] params = (wi.fields['params'] || {}).dup params.delete('ref') if err = errors.find { |e| e.fei == wi.fei } params['error'] = err.message end r << params r } end
[ "def", "position", "workitems", ".", "collect", "{", "|", "wi", "|", "r", "=", "[", "wi", ".", "fei", ".", "sid", ",", "wi", ".", "participant_name", "]", "params", "=", "(", "wi", ".", "fields", "[", "'params'", "]", "||", "{", "}", ")", ".", "dup", "params", ".", "delete", "(", "'ref'", ")", "if", "err", "=", "errors", ".", "find", "{", "|", "e", "|", "e", ".", "fei", "==", "wi", ".", "fei", "}", "params", "[", "'error'", "]", "=", "err", ".", "message", "end", "r", "<<", "params", "r", "}", "end" ]
Returns the 'position' of the process. pdef = Ruote.process_definition do alpha :task => 'clean car' end wfid = engine.launch(pdef) sleep 0.500 engine.process(wfid) # => [["0_0", "alpha", {"task"=>"clean car"}]] A process with concurrent branches will yield multiple 'positions'. It uses #workitems underneath. If you want to list all the expressions where the "flow currently is" regardless they are participant expressions or errors, look at the #leaves method.
[ "Returns", "the", "position", "of", "the", "process", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dboard/process_status.rb#L255-L271
20,182
jmettraux/ruote
lib/ruote/dboard/process_status.rb
Ruote.ProcessStatus.leaves
def leaves expressions.inject([]) { |a, exp| a.select { |e| ! exp.ancestor?(e.fei) } + [ exp ] } end
ruby
def leaves expressions.inject([]) { |a, exp| a.select { |e| ! exp.ancestor?(e.fei) } + [ exp ] } end
[ "def", "leaves", "expressions", ".", "inject", "(", "[", "]", ")", "{", "|", "a", ",", "exp", "|", "a", ".", "select", "{", "|", "e", "|", "!", "exp", ".", "ancestor?", "(", "e", ".", "fei", ")", "}", "+", "[", "exp", "]", "}", "end" ]
Returns the expressions where the flow is currently, ak the leaves of the execution tree. Whereas #position only looks at participant expressions (and errors), #leaves looks at any expressions that is a leave (which has no child at this point). Returns an array of FlowExpression instances. (Note that they may have their attribute #error set).
[ "Returns", "the", "expressions", "where", "the", "flow", "is", "currently", "ak", "the", "leaves", "of", "the", "execution", "tree", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dboard/process_status.rb#L283-L288
20,183
jmettraux/ruote
lib/ruote/dboard/process_status.rb
Ruote.ProcessStatus.workitems
def workitems @expressions.select { |fexp| #fexp.is_a?(Ruote::Exp::ParticipantExpression) fexp.h.name == 'participant' }.collect { |fexp| Ruote::Workitem.new(fexp.h.applied_workitem) } end
ruby
def workitems @expressions.select { |fexp| #fexp.is_a?(Ruote::Exp::ParticipantExpression) fexp.h.name == 'participant' }.collect { |fexp| Ruote::Workitem.new(fexp.h.applied_workitem) } end
[ "def", "workitems", "@expressions", ".", "select", "{", "|", "fexp", "|", "#fexp.is_a?(Ruote::Exp::ParticipantExpression)", "fexp", ".", "h", ".", "name", "==", "'participant'", "}", ".", "collect", "{", "|", "fexp", "|", "Ruote", "::", "Workitem", ".", "new", "(", "fexp", ".", "h", ".", "applied_workitem", ")", "}", "end" ]
Returns a list of the workitems currently 'out' to participants For example, with an instance of Ruote.process_definition do concurrence do alpha :task => 'clean car' bravo :task => 'sell car' end end calling engine.process(wfid).workitems will yield two workitems (alpha and bravo). Warning : do not confuse the workitems here with the workitems held in a storage participant or equivalent. The workitem returned here are the workitems as they were right before being sent out to the participant. Note: the workitems handed out here are not "workitem documents", they are extracted from the 'participant' expressions in the expression trees not from the stored workitems lot, they cannot be updated/proceeded via a storage participant. Consider them "read only".
[ "Returns", "a", "list", "of", "the", "workitems", "currently", "out", "to", "participants" ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dboard/process_status.rb#L326-L334
20,184
jmettraux/ruote
lib/ruote/dboard/process_status.rb
Ruote.ProcessStatus.to_dot
def to_dot(opts={}) s = [ "digraph \"process wfid #{wfid}\" {" ] @expressions.each { |e| s.push(*e.send(:to_dot, opts)) } @errors.each { |e| s.push(*e.send(:to_dot, opts)) } s << '}' s.join("\n") end
ruby
def to_dot(opts={}) s = [ "digraph \"process wfid #{wfid}\" {" ] @expressions.each { |e| s.push(*e.send(:to_dot, opts)) } @errors.each { |e| s.push(*e.send(:to_dot, opts)) } s << '}' s.join("\n") end
[ "def", "to_dot", "(", "opts", "=", "{", "}", ")", "s", "=", "[", "\"digraph \\\"process wfid #{wfid}\\\" {\"", "]", "@expressions", ".", "each", "{", "|", "e", "|", "s", ".", "push", "(", "e", ".", "send", "(", ":to_dot", ",", "opts", ")", ")", "}", "@errors", ".", "each", "{", "|", "e", "|", "s", ".", "push", "(", "e", ".", "send", "(", ":to_dot", ",", "opts", ")", ")", "}", "s", "<<", "'}'", "s", ".", "join", "(", "\"\\n\"", ")", "end" ]
Returns a 'dot' representation of the process. A graph describing the tree of flow expressions that compose the process.
[ "Returns", "a", "dot", "representation", "of", "the", "process", ".", "A", "graph", "describing", "the", "tree", "of", "flow", "expressions", "that", "compose", "the", "process", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/dboard/process_status.rb#L477-L485
20,185
jmettraux/ruote
lib/ruote/part/template.rb
Ruote.TemplateMixin.render_template
def render_template(template, flow_expression, workitem) template = (File.read(template) rescue nil) if is_a_file?(template) return render_default_template(workitem) unless template template = template.to_s workitem = workitem.to_h if workitem.respond_to?(:to_h) @context.dollar_sub.s(template, flow_expression, workitem) end
ruby
def render_template(template, flow_expression, workitem) template = (File.read(template) rescue nil) if is_a_file?(template) return render_default_template(workitem) unless template template = template.to_s workitem = workitem.to_h if workitem.respond_to?(:to_h) @context.dollar_sub.s(template, flow_expression, workitem) end
[ "def", "render_template", "(", "template", ",", "flow_expression", ",", "workitem", ")", "template", "=", "(", "File", ".", "read", "(", "template", ")", "rescue", "nil", ")", "if", "is_a_file?", "(", "template", ")", "return", "render_default_template", "(", "workitem", ")", "unless", "template", "template", "=", "template", ".", "to_s", "workitem", "=", "workitem", ".", "to_h", "if", "workitem", ".", "respond_to?", "(", ":to_h", ")", "@context", ".", "dollar_sub", ".", "s", "(", "template", ",", "flow_expression", ",", "workitem", ")", "end" ]
Do the rendering.
[ "Do", "the", "rendering", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/part/template.rb#L44-L54
20,186
jmettraux/ruote
lib/ruote/part/template.rb
Ruote.TemplateMixin.render_default_template
def render_default_template(workitem) workitem = workitem.to_h if workitem.respond_to?(:to_h) s = [] s << "workitem for #{workitem['participant_name']}" s << '' s << Rufus::Json.pretty_encode(workitem['fei']) s << '' workitem['fields'].keys.sort.each do |key| s << " - '#{key}' ==> #{Rufus::Json.encode(workitem['fields'][key])}" end s.join("\n") end
ruby
def render_default_template(workitem) workitem = workitem.to_h if workitem.respond_to?(:to_h) s = [] s << "workitem for #{workitem['participant_name']}" s << '' s << Rufus::Json.pretty_encode(workitem['fei']) s << '' workitem['fields'].keys.sort.each do |key| s << " - '#{key}' ==> #{Rufus::Json.encode(workitem['fields'][key])}" end s.join("\n") end
[ "def", "render_default_template", "(", "workitem", ")", "workitem", "=", "workitem", ".", "to_h", "if", "workitem", ".", "respond_to?", "(", ":to_h", ")", "s", "=", "[", "]", "s", "<<", "\"workitem for #{workitem['participant_name']}\"", "s", "<<", "''", "s", "<<", "Rufus", "::", "Json", ".", "pretty_encode", "(", "workitem", "[", "'fei'", "]", ")", "s", "<<", "''", "workitem", "[", "'fields'", "]", ".", "keys", ".", "sort", ".", "each", "do", "|", "key", "|", "s", "<<", "\" - '#{key}' ==> #{Rufus::Json.encode(workitem['fields'][key])}\"", "end", "s", ".", "join", "(", "\"\\n\"", ")", "end" ]
Simply returns a pretty-printed view of the workitem
[ "Simply", "returns", "a", "pretty", "-", "printed", "view", "of", "the", "workitem" ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/part/template.rb#L58-L71
20,187
jmettraux/ruote
lib/ruote/exp/fe_participant.rb
Ruote::Exp.ParticipantExpression.consider_participant_timers
def consider_participant_timers(p_info) return if h.has_timers # process definition takes precedence over participant defined timers. timers = nil [ :rtimers, :timers, :rtimeout ].each do |meth| pa = @context.plist.instantiate(p_info, :if_respond_to? => meth) next unless pa timers = Ruote.participant_send( pa, meth, 'workitem' => Ruote::Workitem.new(h.applied_workitem)) break if timers end return unless timers timers = if timers.index(':') timers.split(/,/) else [ "#{timers}: timeout" ] end schedule_timers(timers) end
ruby
def consider_participant_timers(p_info) return if h.has_timers # process definition takes precedence over participant defined timers. timers = nil [ :rtimers, :timers, :rtimeout ].each do |meth| pa = @context.plist.instantiate(p_info, :if_respond_to? => meth) next unless pa timers = Ruote.participant_send( pa, meth, 'workitem' => Ruote::Workitem.new(h.applied_workitem)) break if timers end return unless timers timers = if timers.index(':') timers.split(/,/) else [ "#{timers}: timeout" ] end schedule_timers(timers) end
[ "def", "consider_participant_timers", "(", "p_info", ")", "return", "if", "h", ".", "has_timers", "# process definition takes precedence over participant defined timers.", "timers", "=", "nil", "[", ":rtimers", ",", ":timers", ",", ":rtimeout", "]", ".", "each", "do", "|", "meth", "|", "pa", "=", "@context", ".", "plist", ".", "instantiate", "(", "p_info", ",", ":if_respond_to?", "=>", "meth", ")", "next", "unless", "pa", "timers", "=", "Ruote", ".", "participant_send", "(", "pa", ",", "meth", ",", "'workitem'", "=>", "Ruote", "::", "Workitem", ".", "new", "(", "h", ".", "applied_workitem", ")", ")", "break", "if", "timers", "end", "return", "unless", "timers", "timers", "=", "if", "timers", ".", "index", "(", "':'", ")", "timers", ".", "split", "(", "/", "/", ")", "else", "[", "\"#{timers}: timeout\"", "]", "end", "schedule_timers", "(", "timers", ")", "end" ]
Determines and schedules timeout if any. Note that process definition timeout has priority over participant specified timeout.
[ "Determines", "and", "schedules", "timeout", "if", "any", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/fe_participant.rb#L279-L307
20,188
jmettraux/ruote
lib/ruote/part/local_participant.rb
Ruote.LocalParticipant.re_dispatch
def re_dispatch(wi=nil, opts=nil) wi, opts = [ nil, wi ] if wi.is_a?(Hash) && opts.nil? wi ||= workitem() opts ||= {} wi.h.re_dispatch_count = wi.h.re_dispatch_count.to_s.to_i + 1 msg = { 'action' => 'dispatch', 'fei' => wi.h.fei, 'workitem' => wi.to_h, 'participant_name' => wi.participant_name } if t = opts[:in] || opts[:at] sched_id = @context.storage.put_schedule('at', wi.h.fei, t, msg) exp = fexp(wi) exp.h['re_dispatch_sched_id'] = sched_id exp.try_persist else @context.storage.put_msg('dispatch', msg) end end
ruby
def re_dispatch(wi=nil, opts=nil) wi, opts = [ nil, wi ] if wi.is_a?(Hash) && opts.nil? wi ||= workitem() opts ||= {} wi.h.re_dispatch_count = wi.h.re_dispatch_count.to_s.to_i + 1 msg = { 'action' => 'dispatch', 'fei' => wi.h.fei, 'workitem' => wi.to_h, 'participant_name' => wi.participant_name } if t = opts[:in] || opts[:at] sched_id = @context.storage.put_schedule('at', wi.h.fei, t, msg) exp = fexp(wi) exp.h['re_dispatch_sched_id'] = sched_id exp.try_persist else @context.storage.put_msg('dispatch', msg) end end
[ "def", "re_dispatch", "(", "wi", "=", "nil", ",", "opts", "=", "nil", ")", "wi", ",", "opts", "=", "[", "nil", ",", "wi", "]", "if", "wi", ".", "is_a?", "(", "Hash", ")", "&&", "opts", ".", "nil?", "wi", "||=", "workitem", "(", ")", "opts", "||=", "{", "}", "wi", ".", "h", ".", "re_dispatch_count", "=", "wi", ".", "h", ".", "re_dispatch_count", ".", "to_s", ".", "to_i", "+", "1", "msg", "=", "{", "'action'", "=>", "'dispatch'", ",", "'fei'", "=>", "wi", ".", "h", ".", "fei", ",", "'workitem'", "=>", "wi", ".", "to_h", ",", "'participant_name'", "=>", "wi", ".", "participant_name", "}", "if", "t", "=", "opts", "[", ":in", "]", "||", "opts", "[", ":at", "]", "sched_id", "=", "@context", ".", "storage", ".", "put_schedule", "(", "'at'", ",", "wi", ".", "h", ".", "fei", ",", "t", ",", "msg", ")", "exp", "=", "fexp", "(", "wi", ")", "exp", ".", "h", "[", "'re_dispatch_sched_id'", "]", "=", "sched_id", "exp", ".", "try_persist", "else", "@context", ".", "storage", ".", "put_msg", "(", "'dispatch'", ",", "msg", ")", "end", "end" ]
Use this method to re_dispatch the workitem. It takes two options :in and :at for "later re_dispatch". Look at the unschedule_re_dispatch method for an example of participant implementation that uses re_dispatch. Without one of those options, the method is a "reject".
[ "Use", "this", "method", "to", "re_dispatch", "the", "workitem", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/part/local_participant.rb#L156-L183
20,189
jmettraux/ruote
lib/ruote/svc/error_handler.rb
Ruote.ErrorHandler.msg_handle
def msg_handle(msg, err) fexp = Ruote::Exp::FlowExpression.fetch( @context, msg['fei'] || msg['workitem']['fei'] ) rescue nil handle(msg, fexp, err) end
ruby
def msg_handle(msg, err) fexp = Ruote::Exp::FlowExpression.fetch( @context, msg['fei'] || msg['workitem']['fei'] ) rescue nil handle(msg, fexp, err) end
[ "def", "msg_handle", "(", "msg", ",", "err", ")", "fexp", "=", "Ruote", "::", "Exp", "::", "FlowExpression", ".", "fetch", "(", "@context", ",", "msg", "[", "'fei'", "]", "||", "msg", "[", "'workitem'", "]", "[", "'fei'", "]", ")", "rescue", "nil", "handle", "(", "msg", ",", "fexp", ",", "err", ")", "end" ]
As used by the dispatch pool and the worker.
[ "As", "used", "by", "the", "dispatch", "pool", "and", "the", "worker", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/svc/error_handler.rb#L59-L66
20,190
jmettraux/ruote
lib/ruote/svc/error_handler.rb
Ruote.ErrorHandler.msg_raise
def msg_raise(msg, err) fei = msg['fei'] wfid = msg['wfid'] || msg.fetch('fei', {})['wfid'] @context.storage.put_msg( 'raise', 'fei' => fei, 'wfid' => wfid, 'msg' => msg, 'error' => deflate(err, fei)) end
ruby
def msg_raise(msg, err) fei = msg['fei'] wfid = msg['wfid'] || msg.fetch('fei', {})['wfid'] @context.storage.put_msg( 'raise', 'fei' => fei, 'wfid' => wfid, 'msg' => msg, 'error' => deflate(err, fei)) end
[ "def", "msg_raise", "(", "msg", ",", "err", ")", "fei", "=", "msg", "[", "'fei'", "]", "wfid", "=", "msg", "[", "'wfid'", "]", "||", "msg", ".", "fetch", "(", "'fei'", ",", "{", "}", ")", "[", "'wfid'", "]", "@context", ".", "storage", ".", "put_msg", "(", "'raise'", ",", "'fei'", "=>", "fei", ",", "'wfid'", "=>", "wfid", ",", "'msg'", "=>", "msg", ",", "'error'", "=>", "deflate", "(", "err", ",", "fei", ")", ")", "end" ]
Packages the error in a 'raise' msg and places it in the storage, for a worker to pick it up. TODO: investigate: is it still used, relevant? (probably yes, ruote-swf)
[ "Packages", "the", "error", "in", "a", "raise", "msg", "and", "places", "it", "in", "the", "storage", "for", "a", "worker", "to", "pick", "it", "up", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/svc/error_handler.rb#L73-L84
20,191
jmettraux/ruote
lib/ruote/svc/error_handler.rb
Ruote.ErrorHandler.handle
def handle(msg, fexp, err) err = RaisedError.new(err) unless err.respond_to?(:backtrace) meta = err.is_a?(Ruote::MetaError) fei = msg['fei'] || (fexp.h.fei rescue nil) wfid = msg['wfid'] || (fei || {})['wfid'] # on_error ? return if ( ! meta) && fexp && fexp.handle_on_error(msg, err) # emit 'msg' # # (this message might get intercepted by a tracker) herr = deflate(err, fei, fexp) # fill error in the error journal @context.storage.put( herr.merge( 'type' => 'errors', '_id' => "err_#{Ruote.to_storage_id(fei)}", 'message' => err.inspect, # :-( 'trace' => (err.backtrace || []).join("\n"), # :-( 'msg' => msg) ) if fei # advertise 'error_intercepted' @context.storage.put_msg( 'error_intercepted', 'error' => herr, 'wfid' => wfid, 'fei' => fei, 'msg' => msg) rescue => e raise e unless @context.worker @context.worker.send( :handle_step_error, e, { 'action' => 'error_intercepted', 'error' => deflate(err, fei), 'fei' => fei, 'wfid' => wfid, 'msg' => msg }) end
ruby
def handle(msg, fexp, err) err = RaisedError.new(err) unless err.respond_to?(:backtrace) meta = err.is_a?(Ruote::MetaError) fei = msg['fei'] || (fexp.h.fei rescue nil) wfid = msg['wfid'] || (fei || {})['wfid'] # on_error ? return if ( ! meta) && fexp && fexp.handle_on_error(msg, err) # emit 'msg' # # (this message might get intercepted by a tracker) herr = deflate(err, fei, fexp) # fill error in the error journal @context.storage.put( herr.merge( 'type' => 'errors', '_id' => "err_#{Ruote.to_storage_id(fei)}", 'message' => err.inspect, # :-( 'trace' => (err.backtrace || []).join("\n"), # :-( 'msg' => msg) ) if fei # advertise 'error_intercepted' @context.storage.put_msg( 'error_intercepted', 'error' => herr, 'wfid' => wfid, 'fei' => fei, 'msg' => msg) rescue => e raise e unless @context.worker @context.worker.send( :handle_step_error, e, { 'action' => 'error_intercepted', 'error' => deflate(err, fei), 'fei' => fei, 'wfid' => wfid, 'msg' => msg }) end
[ "def", "handle", "(", "msg", ",", "fexp", ",", "err", ")", "err", "=", "RaisedError", ".", "new", "(", "err", ")", "unless", "err", ".", "respond_to?", "(", ":backtrace", ")", "meta", "=", "err", ".", "is_a?", "(", "Ruote", "::", "MetaError", ")", "fei", "=", "msg", "[", "'fei'", "]", "||", "(", "fexp", ".", "h", ".", "fei", "rescue", "nil", ")", "wfid", "=", "msg", "[", "'wfid'", "]", "||", "(", "fei", "||", "{", "}", ")", "[", "'wfid'", "]", "# on_error ?", "return", "if", "(", "!", "meta", ")", "&&", "fexp", "&&", "fexp", ".", "handle_on_error", "(", "msg", ",", "err", ")", "# emit 'msg'", "#", "# (this message might get intercepted by a tracker)", "herr", "=", "deflate", "(", "err", ",", "fei", ",", "fexp", ")", "# fill error in the error journal", "@context", ".", "storage", ".", "put", "(", "herr", ".", "merge", "(", "'type'", "=>", "'errors'", ",", "'_id'", "=>", "\"err_#{Ruote.to_storage_id(fei)}\"", ",", "'message'", "=>", "err", ".", "inspect", ",", "# :-(", "'trace'", "=>", "(", "err", ".", "backtrace", "||", "[", "]", ")", ".", "join", "(", "\"\\n\"", ")", ",", "# :-(", "'msg'", "=>", "msg", ")", ")", "if", "fei", "# advertise 'error_intercepted'", "@context", ".", "storage", ".", "put_msg", "(", "'error_intercepted'", ",", "'error'", "=>", "herr", ",", "'wfid'", "=>", "wfid", ",", "'fei'", "=>", "fei", ",", "'msg'", "=>", "msg", ")", "rescue", "=>", "e", "raise", "e", "unless", "@context", ".", "worker", "@context", ".", "worker", ".", "send", "(", ":handle_step_error", ",", "e", ",", "{", "'action'", "=>", "'error_intercepted'", ",", "'error'", "=>", "deflate", "(", "err", ",", "fei", ")", ",", "'fei'", "=>", "fei", ",", "'wfid'", "=>", "wfid", ",", "'msg'", "=>", "msg", "}", ")", "end" ]
Called by msg_handle or action_handle.
[ "Called", "by", "msg_handle", "or", "action_handle", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/svc/error_handler.rb#L108-L156
20,192
jmettraux/ruote
lib/ruote/svc/error_handler.rb
Ruote.ErrorHandler.deflate
def deflate(err, fei, fexp=nil) return err unless err.respond_to?(:backtrace) fexp ||= Ruote::Exp::FlowExpression.dummy('fei' => fei, 'original_tree' => nil) fexp.deflate(err) end
ruby
def deflate(err, fei, fexp=nil) return err unless err.respond_to?(:backtrace) fexp ||= Ruote::Exp::FlowExpression.dummy('fei' => fei, 'original_tree' => nil) fexp.deflate(err) end
[ "def", "deflate", "(", "err", ",", "fei", ",", "fexp", "=", "nil", ")", "return", "err", "unless", "err", ".", "respond_to?", "(", ":backtrace", ")", "fexp", "||=", "Ruote", "::", "Exp", "::", "FlowExpression", ".", "dummy", "(", "'fei'", "=>", "fei", ",", "'original_tree'", "=>", "nil", ")", "fexp", ".", "deflate", "(", "err", ")", "end" ]
Returns a serializable hash with all the details of the error.
[ "Returns", "a", "serializable", "hash", "with", "all", "the", "details", "of", "the", "error", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/svc/error_handler.rb#L160-L168
20,193
jmettraux/ruote
lib/ruote/exp/fe_concurrence.rb
Ruote::Exp.ConcurrenceExpression.expected_count
def expected_count if h.ccount.nil? count_list_size elsif h.ccount >= 0 [ h.ccount, count_list_size ].min else # all but 1, 2, ... i = count_list_size + h.ccount i < 1 ? 1 : i end end
ruby
def expected_count if h.ccount.nil? count_list_size elsif h.ccount >= 0 [ h.ccount, count_list_size ].min else # all but 1, 2, ... i = count_list_size + h.ccount i < 1 ? 1 : i end end
[ "def", "expected_count", "if", "h", ".", "ccount", ".", "nil?", "count_list_size", "elsif", "h", ".", "ccount", ">=", "0", "[", "h", ".", "ccount", ",", "count_list_size", "]", ".", "min", "else", "# all but 1, 2, ...", "i", "=", "count_list_size", "+", "h", ".", "ccount", "i", "<", "1", "?", "1", ":", "i", "end", "end" ]
How many branch replies are expected before the concurrence is over ?
[ "How", "many", "branch", "replies", "are", "expected", "before", "the", "concurrence", "is", "over", "?" ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/fe_concurrence.rb#L449-L459
20,194
jmettraux/ruote
lib/ruote/exp/fe_concurrence.rb
Ruote::Exp.ConcurrenceExpression.merge_workitems
def merge_workitems(workitems, merge_type) workitems.inject(nil) do |t, wi| Ruote.merge_workitem(workitem_index(wi), t, wi, merge_type) end end
ruby
def merge_workitems(workitems, merge_type) workitems.inject(nil) do |t, wi| Ruote.merge_workitem(workitem_index(wi), t, wi, merge_type) end end
[ "def", "merge_workitems", "(", "workitems", ",", "merge_type", ")", "workitems", ".", "inject", "(", "nil", ")", "do", "|", "t", ",", "wi", "|", "Ruote", ".", "merge_workitem", "(", "workitem_index", "(", "wi", ")", ",", "t", ",", "wi", ",", "merge_type", ")", "end", "end" ]
Given a list of workitems and a merge_type, will merge according to the merge type. The return value is the merged workitem. (Still used when dealing with highest/lowest merge_type and legacy concurrence/citerator expressions)
[ "Given", "a", "list", "of", "workitems", "and", "a", "merge_type", "will", "merge", "according", "to", "the", "merge", "type", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/exp/fe_concurrence.rb#L593-L598
20,195
jmettraux/ruote
lib/ruote/workitem.rb
Ruote.Workitem.as_json
def as_json(pretty=false) pretty ? Rufus::Json.pretty_encode(@h) : Rufus::Json.encode(@h) end
ruby
def as_json(pretty=false) pretty ? Rufus::Json.pretty_encode(@h) : Rufus::Json.encode(@h) end
[ "def", "as_json", "(", "pretty", "=", "false", ")", "pretty", "?", "Rufus", "::", "Json", ".", "pretty_encode", "(", "@h", ")", ":", "Rufus", "::", "Json", ".", "encode", "(", "@h", ")", "end" ]
Encodes this workitem as JSON. If pretty is set to true, will output prettified JSON.
[ "Encodes", "this", "workitem", "as", "JSON", ".", "If", "pretty", "is", "set", "to", "true", "will", "output", "prettified", "JSON", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/workitem.rb#L385-L388
20,196
jmettraux/ruote
lib/ruote/workitem.rb
Ruote.Workitem.remove_tag
def remove_tag(tag) # it's a bit convoluted... trying to cope with potential inconsistencies # # normally, it should only be a tags.pop(), but since user have # access to the workitem and its fields... better be safe than sorry tags = (h.fields['__tags__'] || []) if index = tags.rindex(tag) tags.delete_at(index) end h.fields['__left_tag__'] = tag end
ruby
def remove_tag(tag) # it's a bit convoluted... trying to cope with potential inconsistencies # # normally, it should only be a tags.pop(), but since user have # access to the workitem and its fields... better be safe than sorry tags = (h.fields['__tags__'] || []) if index = tags.rindex(tag) tags.delete_at(index) end h.fields['__left_tag__'] = tag end
[ "def", "remove_tag", "(", "tag", ")", "# it's a bit convoluted... trying to cope with potential inconsistencies", "#", "# normally, it should only be a tags.pop(), but since user have", "# access to the workitem and its fields... better be safe than sorry", "tags", "=", "(", "h", ".", "fields", "[", "'__tags__'", "]", "||", "[", "]", ")", "if", "index", "=", "tags", ".", "rindex", "(", "tag", ")", "tags", ".", "delete_at", "(", "index", ")", "end", "h", ".", "fields", "[", "'__left_tag__'", "]", "=", "tag", "end" ]
Used by FlowExpression when leaving a tag.
[ "Used", "by", "FlowExpression", "when", "leaving", "a", "tag", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/workitem.rb#L415-L429
20,197
jmettraux/ruote
lib/ruote/svc/dispatch_pool.rb
Ruote.DispatchPool.dispatch
def dispatch(msg) participant = @context.plist.lookup( msg['participant'] || msg['participant_name'], msg['workitem']) if @context['participant_threads_enabled'] == false || do_not_thread?(participant, msg) then do_dispatch(participant, msg) else do_threaded_dispatch(participant, msg) end end
ruby
def dispatch(msg) participant = @context.plist.lookup( msg['participant'] || msg['participant_name'], msg['workitem']) if @context['participant_threads_enabled'] == false || do_not_thread?(participant, msg) then do_dispatch(participant, msg) else do_threaded_dispatch(participant, msg) end end
[ "def", "dispatch", "(", "msg", ")", "participant", "=", "@context", ".", "plist", ".", "lookup", "(", "msg", "[", "'participant'", "]", "||", "msg", "[", "'participant_name'", "]", ",", "msg", "[", "'workitem'", "]", ")", "if", "@context", "[", "'participant_threads_enabled'", "]", "==", "false", "||", "do_not_thread?", "(", "participant", ",", "msg", ")", "then", "do_dispatch", "(", "participant", ",", "msg", ")", "else", "do_threaded_dispatch", "(", "participant", ",", "msg", ")", "end", "end" ]
Dispatching the msg.
[ "Dispatching", "the", "msg", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/svc/dispatch_pool.rb#L53-L66
20,198
jmettraux/ruote
lib/ruote/svc/dispatch_pool.rb
Ruote.DispatchPool.do_dispatch
def do_dispatch(participant, msg) do_raw_dispatch(participant, msg) rescue => err @context.error_handler.msg_handle(msg, err) end
ruby
def do_dispatch(participant, msg) do_raw_dispatch(participant, msg) rescue => err @context.error_handler.msg_handle(msg, err) end
[ "def", "do_dispatch", "(", "participant", ",", "msg", ")", "do_raw_dispatch", "(", "participant", ",", "msg", ")", "rescue", "=>", "err", "@context", ".", "error_handler", ".", "msg_handle", "(", "msg", ",", "err", ")", "end" ]
The raw dispatch work, wrapped in error handling.
[ "The", "raw", "dispatch", "work", "wrapped", "in", "error", "handling", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/svc/dispatch_pool.rb#L93-L99
20,199
jmettraux/ruote
lib/ruote/svc/dispatch_pool.rb
Ruote.DispatchPool.do_threaded_dispatch
def do_threaded_dispatch(participant, msg) msg = Rufus::Json.dup(msg) # # the thread gets its own copy of the message # (especially important if the main thread does something with # the message 'during' the dispatch) # Maybe at some point a limit on the number of dispatch threads # would be OK. # Or maybe it's the job of an extension / subclass Thread.new { do_dispatch(participant, msg) } end
ruby
def do_threaded_dispatch(participant, msg) msg = Rufus::Json.dup(msg) # # the thread gets its own copy of the message # (especially important if the main thread does something with # the message 'during' the dispatch) # Maybe at some point a limit on the number of dispatch threads # would be OK. # Or maybe it's the job of an extension / subclass Thread.new { do_dispatch(participant, msg) } end
[ "def", "do_threaded_dispatch", "(", "participant", ",", "msg", ")", "msg", "=", "Rufus", "::", "Json", ".", "dup", "(", "msg", ")", "#", "# the thread gets its own copy of the message", "# (especially important if the main thread does something with", "# the message 'during' the dispatch)", "# Maybe at some point a limit on the number of dispatch threads", "# would be OK.", "# Or maybe it's the job of an extension / subclass", "Thread", ".", "new", "{", "do_dispatch", "(", "participant", ",", "msg", ")", "}", "end" ]
Wraps the call to do_dispatch in a thread.
[ "Wraps", "the", "call", "to", "do_dispatch", "in", "a", "thread", "." ]
30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c
https://github.com/jmettraux/ruote/blob/30a6bb88a4e48ed2e1b9089754f1c8be8c1a879c/lib/ruote/svc/dispatch_pool.rb#L103-L116