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
partition
stringclasses
1 value
mojolingo/sippy_cup
lib/sippy_cup/scenario.rb
SippyCup.Scenario.call_length_repartition
def call_length_repartition(min, max, interval) partition_table 'CallLengthRepartition', min.to_i, max.to_i, interval.to_i end
ruby
def call_length_repartition(min, max, interval) partition_table 'CallLengthRepartition', min.to_i, max.to_i, interval.to_i end
[ "def", "call_length_repartition", "(", "min", ",", "max", ",", "interval", ")", "partition_table", "'CallLengthRepartition'", ",", "min", ".", "to_i", ",", "max", ".", "to_i", ",", "interval", ".", "to_i", "end" ]
Create partition table for Call Length @param [Integer] min An value specifying the minimum time in milliseconds for the table @param [Integer] max An value specifying the maximum time in milliseconds for the table @param [Integer] interval An value specifying the interval in milliseconds for the table
[ "Create", "partition", "table", "for", "Call", "Length" ]
f778cdf429dc9a95884d05669dd1ed04b07134e4
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L637-L639
train
mojolingo/sippy_cup
lib/sippy_cup/scenario.rb
SippyCup.Scenario.response_time_repartition
def response_time_repartition(min, max, interval) partition_table 'ResponseTimeRepartition', min.to_i, max.to_i, interval.to_i end
ruby
def response_time_repartition(min, max, interval) partition_table 'ResponseTimeRepartition', min.to_i, max.to_i, interval.to_i end
[ "def", "response_time_repartition", "(", "min", ",", "max", ",", "interval", ")", "partition_table", "'ResponseTimeRepartition'", ",", "min", ".", "to_i", ",", "max", ".", "to_i", ",", "interval", ".", "to_i", "end" ]
Create partition table for Response Time @param [Integer] min An value specifying the minimum time in milliseconds for the table @param [Integer] max An value specifying the maximum time in milliseconds for the table @param [Integer] interval An value specifying the interval in milliseconds for the table
[ "Create", "partition", "table", "for", "Response", "Time" ]
f778cdf429dc9a95884d05669dd1ed04b07134e4
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L646-L648
train
mojolingo/sippy_cup
lib/sippy_cup/scenario.rb
SippyCup.Scenario.to_xml
def to_xml(options = {}) pcap_path = options[:pcap_path] docdup = doc.dup # Not removing in reverse would most likely remove the wrong # nodes because of changing indices. @media_nodes.reverse.each do |nop| nopdup = docdup.xpath(nop.path) if pcap_path.nil? or @media.blank? nopdup.remove else exec = nopdup.xpath("./action/exec").first exec['play_pcap_audio'] = pcap_path end end unless @reference_variables.empty? scenario_node = docdup.xpath('scenario').first scenario_node << docdup.create_element('Reference') do |ref| ref[:variables] = @reference_variables.to_a.join ',' end end docdup.to_xml end
ruby
def to_xml(options = {}) pcap_path = options[:pcap_path] docdup = doc.dup # Not removing in reverse would most likely remove the wrong # nodes because of changing indices. @media_nodes.reverse.each do |nop| nopdup = docdup.xpath(nop.path) if pcap_path.nil? or @media.blank? nopdup.remove else exec = nopdup.xpath("./action/exec").first exec['play_pcap_audio'] = pcap_path end end unless @reference_variables.empty? scenario_node = docdup.xpath('scenario').first scenario_node << docdup.create_element('Reference') do |ref| ref[:variables] = @reference_variables.to_a.join ',' end end docdup.to_xml end
[ "def", "to_xml", "(", "options", "=", "{", "}", ")", "pcap_path", "=", "options", "[", ":pcap_path", "]", "docdup", "=", "doc", ".", "dup", "@media_nodes", ".", "reverse", ".", "each", "do", "|", "nop", "|", "nopdup", "=", "docdup", ".", "xpath", "(", "nop", ".", "path", ")", "if", "pcap_path", ".", "nil?", "or", "@media", ".", "blank?", "nopdup", ".", "remove", "else", "exec", "=", "nopdup", ".", "xpath", "(", "\"./action/exec\"", ")", ".", "first", "exec", "[", "'play_pcap_audio'", "]", "=", "pcap_path", "end", "end", "unless", "@reference_variables", ".", "empty?", "scenario_node", "=", "docdup", ".", "xpath", "(", "'scenario'", ")", ".", "first", "scenario_node", "<<", "docdup", ".", "create_element", "(", "'Reference'", ")", "do", "|", "ref", "|", "ref", "[", ":variables", "]", "=", "@reference_variables", ".", "to_a", ".", "join", "','", "end", "end", "docdup", ".", "to_xml", "end" ]
Dump the scenario to a SIPp XML string @return [String] the SIPp XML scenario
[ "Dump", "the", "scenario", "to", "a", "SIPp", "XML", "string" ]
f778cdf429dc9a95884d05669dd1ed04b07134e4
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L654-L679
train
mojolingo/sippy_cup
lib/sippy_cup/scenario.rb
SippyCup.Scenario.compile!
def compile! unless @media.blank? print "Compiling media to #{@filename}.pcap..." compile_media.to_file filename: "#{@filename}.pcap" puts "done." end scenario_filename = "#{@filename}.xml" print "Compiling scenario to #{scenario_filename}..." File.open scenario_filename, 'w' do |file| file.write to_xml(:pcap_path => "#{@filename}.pcap") end puts "done." scenario_filename end
ruby
def compile! unless @media.blank? print "Compiling media to #{@filename}.pcap..." compile_media.to_file filename: "#{@filename}.pcap" puts "done." end scenario_filename = "#{@filename}.xml" print "Compiling scenario to #{scenario_filename}..." File.open scenario_filename, 'w' do |file| file.write to_xml(:pcap_path => "#{@filename}.pcap") end puts "done." scenario_filename end
[ "def", "compile!", "unless", "@media", ".", "blank?", "print", "\"Compiling media to #{@filename}.pcap...\"", "compile_media", ".", "to_file", "filename", ":", "\"#{@filename}.pcap\"", "puts", "\"done.\"", "end", "scenario_filename", "=", "\"#{@filename}.xml\"", "print", "\"Compiling scenario to #{scenario_filename}...\"", "File", ".", "open", "scenario_filename", ",", "'w'", "do", "|", "file", "|", "file", ".", "write", "to_xml", "(", ":pcap_path", "=>", "\"#{@filename}.pcap\"", ")", "end", "puts", "\"done.\"", "scenario_filename", "end" ]
Compile the scenario and its media to disk Writes the SIPp scenario file to disk at {filename}.xml, and the PCAP media to {filename}.pcap if applicable. {filename} is taken from the :filename option when creating the scenario, or falls back to a down-snake-cased version of the scenario name. @return [String] the path to the resulting scenario file @example Export a scenario to a specified filename scenario = Scenario.new 'Test Scenario', filename: 'my_scenario' scenario.compile! # Leaves files at my_scenario.xml and my_scenario.pcap @example Export a scenario to a calculated filename scenario = Scenario.new 'Test Scenario' scenario.compile! # Leaves files at test_scenario.xml and test_scenario.pcap
[ "Compile", "the", "scenario", "and", "its", "media", "to", "disk" ]
f778cdf429dc9a95884d05669dd1ed04b07134e4
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/scenario.rb#L697-L712
train
mojolingo/sippy_cup
lib/sippy_cup/xml_scenario.rb
SippyCup.XMLScenario.to_tmpfiles
def to_tmpfiles scenario_file = Tempfile.new 'scenario' scenario_file.write @xml scenario_file.rewind if @media media_file = Tempfile.new 'media' media_file.write @media media_file.rewind else media_file = nil end {scenario: scenario_file, media: media_file} end
ruby
def to_tmpfiles scenario_file = Tempfile.new 'scenario' scenario_file.write @xml scenario_file.rewind if @media media_file = Tempfile.new 'media' media_file.write @media media_file.rewind else media_file = nil end {scenario: scenario_file, media: media_file} end
[ "def", "to_tmpfiles", "scenario_file", "=", "Tempfile", ".", "new", "'scenario'", "scenario_file", ".", "write", "@xml", "scenario_file", ".", "rewind", "if", "@media", "media_file", "=", "Tempfile", ".", "new", "'media'", "media_file", ".", "write", "@media", "media_file", ".", "rewind", "else", "media_file", "=", "nil", "end", "{", "scenario", ":", "scenario_file", ",", "media", ":", "media_file", "}", "end" ]
Create a scenario instance @param [String] name The scenario's name @param [String] xml The XML document representing the scenario @param [String] media The media to be invoked by the scenario in PCAP format @param [Hash] args options to customise the scenario. @see Scenario#initialize. Write compiled Scenario XML and PCAP media to tempfiles. These will automatically be closed and deleted once they have gone out of scope, and can be used to execute the scenario without leaving stuff behind. @return [Hash<Symbol => Tempfile>] handles to created Tempfiles at :scenario and :media @see http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html
[ "Create", "a", "scenario", "instance" ]
f778cdf429dc9a95884d05669dd1ed04b07134e4
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/xml_scenario.rb#L34-L48
train
mojolingo/sippy_cup
lib/sippy_cup/runner.rb
SippyCup.Runner.wait
def wait exit_status = Process.wait2 @sipp_pid.to_i @err_rd.close if @err_rd @stdout_rd.close if @stdout_rd final_result = process_exit_status exit_status, @stderr_buffer if final_result @logger.info "Test completed successfully!" else @logger.info "Test completed successfully but some calls failed." end @logger.info "Statistics logged at #{File.expand_path @scenario_options[:stats_file]}" if @scenario_options[:stats_file] final_result ensure cleanup_input_files end
ruby
def wait exit_status = Process.wait2 @sipp_pid.to_i @err_rd.close if @err_rd @stdout_rd.close if @stdout_rd final_result = process_exit_status exit_status, @stderr_buffer if final_result @logger.info "Test completed successfully!" else @logger.info "Test completed successfully but some calls failed." end @logger.info "Statistics logged at #{File.expand_path @scenario_options[:stats_file]}" if @scenario_options[:stats_file] final_result ensure cleanup_input_files end
[ "def", "wait", "exit_status", "=", "Process", ".", "wait2", "@sipp_pid", ".", "to_i", "@err_rd", ".", "close", "if", "@err_rd", "@stdout_rd", ".", "close", "if", "@stdout_rd", "final_result", "=", "process_exit_status", "exit_status", ",", "@stderr_buffer", "if", "final_result", "@logger", ".", "info", "\"Test completed successfully!\"", "else", "@logger", ".", "info", "\"Test completed successfully but some calls failed.\"", "end", "@logger", ".", "info", "\"Statistics logged at #{File.expand_path @scenario_options[:stats_file]}\"", "if", "@scenario_options", "[", ":stats_file", "]", "final_result", "ensure", "cleanup_input_files", "end" ]
Waits for the runner to finish execution @raises Errno::ENOENT when the SIPp executable cannot be found @raises SippyCup::ExitOnInternalCommand when SIPp exits on an internal command. Calls may have been processed @raises SippyCup::NoCallsProcessed when SIPp exit normally, but has processed no calls @raises SippyCup::FatalError when SIPp encounters a fatal failure @raises SippyCup::FatalSocketBindingError when SIPp fails to bind to the specified socket @raises SippyCup::SippGenericError when SIPp encounters another type of error @return Boolean true if execution succeeded without any failed calls, false otherwise
[ "Waits", "for", "the", "runner", "to", "finish", "execution" ]
f778cdf429dc9a95884d05669dd1ed04b07134e4
https://github.com/mojolingo/sippy_cup/blob/f778cdf429dc9a95884d05669dd1ed04b07134e4/lib/sippy_cup/runner.rb#L70-L85
train
notahat/machinist
lib/machinist/machinable.rb
Machinist.Machinable.blueprint
def blueprint(name = :master, &block) @blueprints ||= {} if block_given? parent = (name == :master ? superclass : self) # Where should we look for the parent blueprint? @blueprints[name] = blueprint_class.new(self, :parent => parent, &block) end @blueprints[name] end
ruby
def blueprint(name = :master, &block) @blueprints ||= {} if block_given? parent = (name == :master ? superclass : self) # Where should we look for the parent blueprint? @blueprints[name] = blueprint_class.new(self, :parent => parent, &block) end @blueprints[name] end
[ "def", "blueprint", "(", "name", "=", ":master", ",", "&", "block", ")", "@blueprints", "||=", "{", "}", "if", "block_given?", "parent", "=", "(", "name", "==", ":master", "?", "superclass", ":", "self", ")", "@blueprints", "[", "name", "]", "=", "blueprint_class", ".", "new", "(", "self", ",", ":parent", "=>", "parent", ",", "&", "block", ")", "end", "@blueprints", "[", "name", "]", "end" ]
Define a blueprint with the given name for this class. e.g. Post.blueprint do title { "A Post" } body { "Lorem ipsum..." } end If you provide the +name+ argument, a named blueprint will be created. See the +blueprint_name+ argument to the make method.
[ "Define", "a", "blueprint", "with", "the", "given", "name", "for", "this", "class", "." ]
dba78a430cd67646a270393c4adfa19a5516f569
https://github.com/notahat/machinist/blob/dba78a430cd67646a270393c4adfa19a5516f569/lib/machinist/machinable.rb#L15-L22
train
notahat/machinist
lib/machinist/machinable.rb
Machinist.Machinable.make!
def make!(*args) decode_args_to_make(*args) do |blueprint, attributes| raise BlueprintCantSaveError.new(blueprint) unless blueprint.respond_to?(:make!) blueprint.make!(attributes) end end
ruby
def make!(*args) decode_args_to_make(*args) do |blueprint, attributes| raise BlueprintCantSaveError.new(blueprint) unless blueprint.respond_to?(:make!) blueprint.make!(attributes) end end
[ "def", "make!", "(", "*", "args", ")", "decode_args_to_make", "(", "*", "args", ")", "do", "|", "blueprint", ",", "attributes", "|", "raise", "BlueprintCantSaveError", ".", "new", "(", "blueprint", ")", "unless", "blueprint", ".", "respond_to?", "(", ":make!", ")", "blueprint", ".", "make!", "(", "attributes", ")", "end", "end" ]
Construct and save an object from a blueprint, if the class allows saving. :call-seq: make!([count], [blueprint_name], [attributes = {}]) Arguments are the same as for make.
[ "Construct", "and", "save", "an", "object", "from", "a", "blueprint", "if", "the", "class", "allows", "saving", "." ]
dba78a430cd67646a270393c4adfa19a5516f569
https://github.com/notahat/machinist/blob/dba78a430cd67646a270393c4adfa19a5516f569/lib/machinist/machinable.rb#L49-L54
train
notahat/machinist
lib/machinist/machinable.rb
Machinist.Machinable.decode_args_to_make
def decode_args_to_make(*args) #:nodoc: shift_arg = lambda {|klass| args.shift if args.first.is_a?(klass) } count = shift_arg[Fixnum] name = shift_arg[Symbol] || :master attributes = shift_arg[Hash] || {} raise ArgumentError.new("Couldn't understand arguments") unless args.empty? @blueprints ||= {} blueprint = @blueprints[name] raise NoBlueprintError.new(self, name) unless blueprint if count.nil? yield(blueprint, attributes) else Array.new(count) { yield(blueprint, attributes) } end end
ruby
def decode_args_to_make(*args) #:nodoc: shift_arg = lambda {|klass| args.shift if args.first.is_a?(klass) } count = shift_arg[Fixnum] name = shift_arg[Symbol] || :master attributes = shift_arg[Hash] || {} raise ArgumentError.new("Couldn't understand arguments") unless args.empty? @blueprints ||= {} blueprint = @blueprints[name] raise NoBlueprintError.new(self, name) unless blueprint if count.nil? yield(blueprint, attributes) else Array.new(count) { yield(blueprint, attributes) } end end
[ "def", "decode_args_to_make", "(", "*", "args", ")", "shift_arg", "=", "lambda", "{", "|", "klass", "|", "args", ".", "shift", "if", "args", ".", "first", ".", "is_a?", "(", "klass", ")", "}", "count", "=", "shift_arg", "[", "Fixnum", "]", "name", "=", "shift_arg", "[", "Symbol", "]", "||", ":master", "attributes", "=", "shift_arg", "[", "Hash", "]", "||", "{", "}", "raise", "ArgumentError", ".", "new", "(", "\"Couldn't understand arguments\"", ")", "unless", "args", ".", "empty?", "@blueprints", "||=", "{", "}", "blueprint", "=", "@blueprints", "[", "name", "]", "raise", "NoBlueprintError", ".", "new", "(", "self", ",", "name", ")", "unless", "blueprint", "if", "count", ".", "nil?", "yield", "(", "blueprint", ",", "attributes", ")", "else", "Array", ".", "new", "(", "count", ")", "{", "yield", "(", "blueprint", ",", "attributes", ")", "}", "end", "end" ]
Parses the arguments to make. Yields a blueprint and an attributes hash to the block, which should construct an object from them. The block may be called multiple times to construct multiple objects.
[ "Parses", "the", "arguments", "to", "make", "." ]
dba78a430cd67646a270393c4adfa19a5516f569
https://github.com/notahat/machinist/blob/dba78a430cd67646a270393c4adfa19a5516f569/lib/machinist/machinable.rb#L76-L92
train
notahat/machinist
lib/machinist/blueprint.rb
Machinist.Blueprint.make
def make(attributes = {}) lathe = lathe_class.new(@klass, new_serial_number, attributes) lathe.instance_eval(&@block) each_ancestor {|blueprint| lathe.instance_eval(&blueprint.block) } lathe.object end
ruby
def make(attributes = {}) lathe = lathe_class.new(@klass, new_serial_number, attributes) lathe.instance_eval(&@block) each_ancestor {|blueprint| lathe.instance_eval(&blueprint.block) } lathe.object end
[ "def", "make", "(", "attributes", "=", "{", "}", ")", "lathe", "=", "lathe_class", ".", "new", "(", "@klass", ",", "new_serial_number", ",", "attributes", ")", "lathe", ".", "instance_eval", "(", "&", "@block", ")", "each_ancestor", "{", "|", "blueprint", "|", "lathe", ".", "instance_eval", "(", "&", "blueprint", ".", "block", ")", "}", "lathe", ".", "object", "end" ]
Generate an object from this blueprint. Pass in attributes to override values defined in the blueprint.
[ "Generate", "an", "object", "from", "this", "blueprint", "." ]
dba78a430cd67646a270393c4adfa19a5516f569
https://github.com/notahat/machinist/blob/dba78a430cd67646a270393c4adfa19a5516f569/lib/machinist/blueprint.rb#L23-L30
train
zk-ruby/zookeeper
lib/zookeeper/request_registry.rb
Zookeeper.RequestRegistry.get_watcher
def get_watcher(req_id, opts={}) @mutex.synchronize do if Constants::ZKRB_GLOBAL_CB_REQ == req_id { :watcher => @default_watcher, :watcher_context => nil } elsif opts[:keep] @watcher_reqs[req_id] else @watcher_reqs.delete(req_id) end end end
ruby
def get_watcher(req_id, opts={}) @mutex.synchronize do if Constants::ZKRB_GLOBAL_CB_REQ == req_id { :watcher => @default_watcher, :watcher_context => nil } elsif opts[:keep] @watcher_reqs[req_id] else @watcher_reqs.delete(req_id) end end end
[ "def", "get_watcher", "(", "req_id", ",", "opts", "=", "{", "}", ")", "@mutex", ".", "synchronize", "do", "if", "Constants", "::", "ZKRB_GLOBAL_CB_REQ", "==", "req_id", "{", ":watcher", "=>", "@default_watcher", ",", ":watcher_context", "=>", "nil", "}", "elsif", "opts", "[", ":keep", "]", "@watcher_reqs", "[", "req_id", "]", "else", "@watcher_reqs", ".", "delete", "(", "req_id", ")", "end", "end", "end" ]
Return the watcher hash associated with the req_id. If the req_id is the ZKRB_GLOBAL_CB_REQ, then does not clear the req from the internal store, otherwise the req_id is removed.
[ "Return", "the", "watcher", "hash", "associated", "with", "the", "req_id", ".", "If", "the", "req_id", "is", "the", "ZKRB_GLOBAL_CB_REQ", "then", "does", "not", "clear", "the", "req", "from", "the", "internal", "store", "otherwise", "the", "req_id", "is", "removed", "." ]
b99cb25195b8c947be0eb82141cc261eec9c8724
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/lib/zookeeper/request_registry.rb#L82-L92
train
zk-ruby/zookeeper
ext/c_zookeeper.rb
Zookeeper.CZookeeper.wait_until_connected
def wait_until_connected(timeout=10) time_to_stop = timeout ? Time.now + timeout : nil return false unless wait_until_running(timeout) @state_mutex.synchronize do while true if timeout now = Time.now break if (@state == ZOO_CONNECTED_STATE) || unhealthy? || (now > time_to_stop) delay = time_to_stop.to_f - now.to_f @state_cond.wait(delay) else break if (@state == ZOO_CONNECTED_STATE) || unhealthy? @state_cond.wait end end end connected? end
ruby
def wait_until_connected(timeout=10) time_to_stop = timeout ? Time.now + timeout : nil return false unless wait_until_running(timeout) @state_mutex.synchronize do while true if timeout now = Time.now break if (@state == ZOO_CONNECTED_STATE) || unhealthy? || (now > time_to_stop) delay = time_to_stop.to_f - now.to_f @state_cond.wait(delay) else break if (@state == ZOO_CONNECTED_STATE) || unhealthy? @state_cond.wait end end end connected? end
[ "def", "wait_until_connected", "(", "timeout", "=", "10", ")", "time_to_stop", "=", "timeout", "?", "Time", ".", "now", "+", "timeout", ":", "nil", "return", "false", "unless", "wait_until_running", "(", "timeout", ")", "@state_mutex", ".", "synchronize", "do", "while", "true", "if", "timeout", "now", "=", "Time", ".", "now", "break", "if", "(", "@state", "==", "ZOO_CONNECTED_STATE", ")", "||", "unhealthy?", "||", "(", "now", ">", "time_to_stop", ")", "delay", "=", "time_to_stop", ".", "to_f", "-", "now", ".", "to_f", "@state_cond", ".", "wait", "(", "delay", ")", "else", "break", "if", "(", "@state", "==", "ZOO_CONNECTED_STATE", ")", "||", "unhealthy?", "@state_cond", ".", "wait", "end", "end", "end", "connected?", "end" ]
this implementation is gross, but i don't really see another way of doing it without more grossness returns true if we're connected, false if we're not if timeout is nil, we never time out, and wait forever for CONNECTED state
[ "this", "implementation", "is", "gross", "but", "i", "don", "t", "really", "see", "another", "way", "of", "doing", "it", "without", "more", "grossness" ]
b99cb25195b8c947be0eb82141cc261eec9c8724
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/c_zookeeper.rb#L178-L198
train
zk-ruby/zookeeper
ext/c_zookeeper.rb
Zookeeper.CZookeeper.submit_and_block
def submit_and_block(meth, *args) @mutex.synchronize do raise Exceptions::NotConnected if unhealthy? end cnt = Continuation.new(meth, *args) @reg.synchronize do |r| if meth == :state r.state_check << cnt else r.pending << cnt end end wake_event_loop! cnt.value end
ruby
def submit_and_block(meth, *args) @mutex.synchronize do raise Exceptions::NotConnected if unhealthy? end cnt = Continuation.new(meth, *args) @reg.synchronize do |r| if meth == :state r.state_check << cnt else r.pending << cnt end end wake_event_loop! cnt.value end
[ "def", "submit_and_block", "(", "meth", ",", "*", "args", ")", "@mutex", ".", "synchronize", "do", "raise", "Exceptions", "::", "NotConnected", "if", "unhealthy?", "end", "cnt", "=", "Continuation", ".", "new", "(", "meth", ",", "*", "args", ")", "@reg", ".", "synchronize", "do", "|", "r", "|", "if", "meth", "==", ":state", "r", ".", "state_check", "<<", "cnt", "else", "r", ".", "pending", "<<", "cnt", "end", "end", "wake_event_loop!", "cnt", ".", "value", "end" ]
submits a job for processing blocks the caller until result has returned
[ "submits", "a", "job", "for", "processing", "blocks", "the", "caller", "until", "result", "has", "returned" ]
b99cb25195b8c947be0eb82141cc261eec9c8724
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/c_zookeeper.rb#L217-L232
train
zk-ruby/zookeeper
lib/zookeeper/continuation.rb
Zookeeper.Continuation.call
def call(hash) logger.debug { "continuation req_id #{req_id}, got hash: #{hash.inspect}" } @rval = hash.values_at(*METH_TO_ASYNC_RESULT_KEYS.fetch(meth)) logger.debug { "delivering result #{@rval.inspect}" } deliver! end
ruby
def call(hash) logger.debug { "continuation req_id #{req_id}, got hash: #{hash.inspect}" } @rval = hash.values_at(*METH_TO_ASYNC_RESULT_KEYS.fetch(meth)) logger.debug { "delivering result #{@rval.inspect}" } deliver! end
[ "def", "call", "(", "hash", ")", "logger", ".", "debug", "{", "\"continuation req_id #{req_id}, got hash: #{hash.inspect}\"", "}", "@rval", "=", "hash", ".", "values_at", "(", "*", "METH_TO_ASYNC_RESULT_KEYS", ".", "fetch", "(", "meth", ")", ")", "logger", ".", "debug", "{", "\"delivering result #{@rval.inspect}\"", "}", "deliver!", "end" ]
receive the response from the server, set @rval, notify caller
[ "receive", "the", "response", "from", "the", "server", "set" ]
b99cb25195b8c947be0eb82141cc261eec9c8724
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/lib/zookeeper/continuation.rb#L141-L146
train
zk-ruby/zookeeper
ext/zookeeper_base.rb
Zookeeper.ZookeeperBase.close
def close sd_thread = nil @mutex.synchronize do return unless @czk inst, @czk = @czk, nil sd_thread = Thread.new(inst) do |_inst| stop_dispatch_thread! _inst.close end end # if we're on the event dispatch thread for some stupid reason, then don't join unless event_dispatch_thread? # hard-coded 30 second delay, don't hang forever if sd_thread.join(30) != sd_thread logger.error { "timed out waiting for shutdown thread to exit" } end end nil end
ruby
def close sd_thread = nil @mutex.synchronize do return unless @czk inst, @czk = @czk, nil sd_thread = Thread.new(inst) do |_inst| stop_dispatch_thread! _inst.close end end # if we're on the event dispatch thread for some stupid reason, then don't join unless event_dispatch_thread? # hard-coded 30 second delay, don't hang forever if sd_thread.join(30) != sd_thread logger.error { "timed out waiting for shutdown thread to exit" } end end nil end
[ "def", "close", "sd_thread", "=", "nil", "@mutex", ".", "synchronize", "do", "return", "unless", "@czk", "inst", ",", "@czk", "=", "@czk", ",", "nil", "sd_thread", "=", "Thread", ".", "new", "(", "inst", ")", "do", "|", "_inst", "|", "stop_dispatch_thread!", "_inst", ".", "close", "end", "end", "unless", "event_dispatch_thread?", "if", "sd_thread", ".", "join", "(", "30", ")", "!=", "sd_thread", "logger", ".", "error", "{", "\"timed out waiting for shutdown thread to exit\"", "}", "end", "end", "nil", "end" ]
close the connection normally, stops the dispatch thread and closes the underlying connection cleanly
[ "close", "the", "connection", "normally", "stops", "the", "dispatch", "thread", "and", "closes", "the", "underlying", "connection", "cleanly" ]
b99cb25195b8c947be0eb82141cc261eec9c8724
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/zookeeper_base.rb#L129-L151
train
zk-ruby/zookeeper
ext/zookeeper_base.rb
Zookeeper.ZookeeperBase.create
def create(*args) # since we don't care about the inputs, just glob args rc, new_path = czk.create(*args) [rc, @req_registry.strip_chroot_from(new_path)] end
ruby
def create(*args) # since we don't care about the inputs, just glob args rc, new_path = czk.create(*args) [rc, @req_registry.strip_chroot_from(new_path)] end
[ "def", "create", "(", "*", "args", ")", "rc", ",", "new_path", "=", "czk", ".", "create", "(", "*", "args", ")", "[", "rc", ",", "@req_registry", ".", "strip_chroot_from", "(", "new_path", ")", "]", "end" ]
the C lib doesn't strip the chroot path off of returned path values, which is pretty damn annoying. this is used to clean things up.
[ "the", "C", "lib", "doesn", "t", "strip", "the", "chroot", "path", "off", "of", "returned", "path", "values", "which", "is", "pretty", "damn", "annoying", ".", "this", "is", "used", "to", "clean", "things", "up", "." ]
b99cb25195b8c947be0eb82141cc261eec9c8724
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/zookeeper_base.rb#L155-L159
train
zk-ruby/zookeeper
ext/zookeeper_base.rb
Zookeeper.ZookeeperBase.strip_chroot_from
def strip_chroot_from(path) return path unless (chrooted? and path and path.start_with?(chroot_path)) path[chroot_path.length..-1] end
ruby
def strip_chroot_from(path) return path unless (chrooted? and path and path.start_with?(chroot_path)) path[chroot_path.length..-1] end
[ "def", "strip_chroot_from", "(", "path", ")", "return", "path", "unless", "(", "chrooted?", "and", "path", "and", "path", ".", "start_with?", "(", "chroot_path", ")", ")", "path", "[", "chroot_path", ".", "length", "..", "-", "1", "]", "end" ]
if we're chrooted, this method will strip the chroot prefix from +path+
[ "if", "we", "re", "chrooted", "this", "method", "will", "strip", "the", "chroot", "prefix", "from", "+", "path", "+" ]
b99cb25195b8c947be0eb82141cc261eec9c8724
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/ext/zookeeper_base.rb#L227-L230
train
zk-ruby/zookeeper
spec/support/zookeeper_spec_helpers.rb
Zookeeper.SpecHelpers.rm_rf
def rm_rf(z, path) z.get_children(:path => path).tap do |h| if h[:rc].zero? h[:children].each do |child| rm_rf(z, File.join(path, child)) end elsif h[:rc] == ZNONODE # no-op else raise "Oh noes! unexpected return value! #{h.inspect}" end end rv = z.delete(:path => path) unless (rv[:rc].zero? or rv[:rc] == ZNONODE) raise "oh noes! failed to delete #{path}" end path end
ruby
def rm_rf(z, path) z.get_children(:path => path).tap do |h| if h[:rc].zero? h[:children].each do |child| rm_rf(z, File.join(path, child)) end elsif h[:rc] == ZNONODE # no-op else raise "Oh noes! unexpected return value! #{h.inspect}" end end rv = z.delete(:path => path) unless (rv[:rc].zero? or rv[:rc] == ZNONODE) raise "oh noes! failed to delete #{path}" end path end
[ "def", "rm_rf", "(", "z", ",", "path", ")", "z", ".", "get_children", "(", ":path", "=>", "path", ")", ".", "tap", "do", "|", "h", "|", "if", "h", "[", ":rc", "]", ".", "zero?", "h", "[", ":children", "]", ".", "each", "do", "|", "child", "|", "rm_rf", "(", "z", ",", "File", ".", "join", "(", "path", ",", "child", ")", ")", "end", "elsif", "h", "[", ":rc", "]", "==", "ZNONODE", "else", "raise", "\"Oh noes! unexpected return value! #{h.inspect}\"", "end", "end", "rv", "=", "z", ".", "delete", "(", ":path", "=>", "path", ")", "unless", "(", "rv", "[", ":rc", "]", ".", "zero?", "or", "rv", "[", ":rc", "]", "==", "ZNONODE", ")", "raise", "\"oh noes! failed to delete #{path}\"", "end", "path", "end" ]
this is not as safe as the one in ZK, just to be used to clean up when we're the only one adjusting a particular path
[ "this", "is", "not", "as", "safe", "as", "the", "one", "in", "ZK", "just", "to", "be", "used", "to", "clean", "up", "when", "we", "re", "the", "only", "one", "adjusting", "a", "particular", "path" ]
b99cb25195b8c947be0eb82141cc261eec9c8724
https://github.com/zk-ruby/zookeeper/blob/b99cb25195b8c947be0eb82141cc261eec9c8724/spec/support/zookeeper_spec_helpers.rb#L37-L57
train
cubesystems/releaf
releaf-content/lib/releaf/content/route.rb
Releaf::Content.Route.params
def params(method_or_path, options = {}) method_or_path = method_or_path.to_s [ path_for(method_or_path, options), options_for(method_or_path, options) ] end
ruby
def params(method_or_path, options = {}) method_or_path = method_or_path.to_s [ path_for(method_or_path, options), options_for(method_or_path, options) ] end
[ "def", "params", "(", "method_or_path", ",", "options", "=", "{", "}", ")", "method_or_path", "=", "method_or_path", ".", "to_s", "[", "path_for", "(", "method_or_path", ",", "options", ")", ",", "options_for", "(", "method_or_path", ",", "options", ")", "]", "end" ]
Return node route params which can be used in Rails route options @param method_or_path [String] string with action and controller for route (Ex. home#index) @param options [Hash] options to merge with internally built params. Passed params overrides route params. @return [Hash] route options. Will return at least node "node_id" and "locale" keys.
[ "Return", "node", "route", "params", "which", "can", "be", "used", "in", "Rails", "route", "options" ]
5ea615abcf6e62afbbf82259d0aa533221d6de08
https://github.com/cubesystems/releaf/blob/5ea615abcf6e62afbbf82259d0aa533221d6de08/releaf-content/lib/releaf/content/route.rb#L18-L24
train
cubesystems/releaf
releaf-content/lib/releaf/content/node.rb
Releaf::Content.Node.maintain_name
def maintain_name postfix = nil total_count = 0 while self.class.where(parent_id: parent_id, name: "#{name}#{postfix}").where("id != ?", id.to_i).exists? do total_count += 1 postfix = "(#{total_count})" end if postfix self.name = "#{name}#{postfix}" end end
ruby
def maintain_name postfix = nil total_count = 0 while self.class.where(parent_id: parent_id, name: "#{name}#{postfix}").where("id != ?", id.to_i).exists? do total_count += 1 postfix = "(#{total_count})" end if postfix self.name = "#{name}#{postfix}" end end
[ "def", "maintain_name", "postfix", "=", "nil", "total_count", "=", "0", "while", "self", ".", "class", ".", "where", "(", "parent_id", ":", "parent_id", ",", "name", ":", "\"#{name}#{postfix}\"", ")", ".", "where", "(", "\"id != ?\"", ",", "id", ".", "to_i", ")", ".", "exists?", "do", "total_count", "+=", "1", "postfix", "=", "\"(#{total_count})\"", "end", "if", "postfix", "self", ".", "name", "=", "\"#{name}#{postfix}\"", "end", "end" ]
Maintain unique name within parent_id scope. If name is not unique add numeric postfix.
[ "Maintain", "unique", "name", "within", "parent_id", "scope", ".", "If", "name", "is", "not", "unique", "add", "numeric", "postfix", "." ]
5ea615abcf6e62afbbf82259d0aa533221d6de08
https://github.com/cubesystems/releaf/blob/5ea615abcf6e62afbbf82259d0aa533221d6de08/releaf-content/lib/releaf/content/node.rb#L73-L85
train
cubesystems/releaf
releaf-content/lib/releaf/content/node.rb
Releaf::Content.Node.maintain_slug
def maintain_slug postfix = nil total_count = 0 while self.class.where(parent_id: parent_id, slug: "#{slug}#{postfix}").where("id != ?", id.to_i).exists? do total_count += 1 postfix = "-#{total_count}" end if postfix self.slug = "#{slug}#{postfix}" end end
ruby
def maintain_slug postfix = nil total_count = 0 while self.class.where(parent_id: parent_id, slug: "#{slug}#{postfix}").where("id != ?", id.to_i).exists? do total_count += 1 postfix = "-#{total_count}" end if postfix self.slug = "#{slug}#{postfix}" end end
[ "def", "maintain_slug", "postfix", "=", "nil", "total_count", "=", "0", "while", "self", ".", "class", ".", "where", "(", "parent_id", ":", "parent_id", ",", "slug", ":", "\"#{slug}#{postfix}\"", ")", ".", "where", "(", "\"id != ?\"", ",", "id", ".", "to_i", ")", ".", "exists?", "do", "total_count", "+=", "1", "postfix", "=", "\"-#{total_count}\"", "end", "if", "postfix", "self", ".", "slug", "=", "\"#{slug}#{postfix}\"", "end", "end" ]
Maintain unique slug within parent_id scope. If slug is not unique add numeric postfix.
[ "Maintain", "unique", "slug", "within", "parent_id", "scope", ".", "If", "slug", "is", "not", "unique", "add", "numeric", "postfix", "." ]
5ea615abcf6e62afbbf82259d0aa533221d6de08
https://github.com/cubesystems/releaf/blob/5ea615abcf6e62afbbf82259d0aa533221d6de08/releaf-content/lib/releaf/content/node.rb#L89-L101
train
cubesystems/releaf
releaf-content/lib/releaf/content/acts_as_node.rb
ActsAsNode.ClassMethods.acts_as_node
def acts_as_node(params: nil, fields: nil) configuration = {params: params, fields: fields} ActsAsNode.register_class(self.name) # Store acts_as_node configuration cattr_accessor :acts_as_node_configuration self.acts_as_node_configuration = configuration end
ruby
def acts_as_node(params: nil, fields: nil) configuration = {params: params, fields: fields} ActsAsNode.register_class(self.name) # Store acts_as_node configuration cattr_accessor :acts_as_node_configuration self.acts_as_node_configuration = configuration end
[ "def", "acts_as_node", "(", "params", ":", "nil", ",", "fields", ":", "nil", ")", "configuration", "=", "{", "params", ":", "params", ",", "fields", ":", "fields", "}", "ActsAsNode", ".", "register_class", "(", "self", ".", "name", ")", "cattr_accessor", ":acts_as_node_configuration", "self", ".", "acts_as_node_configuration", "=", "configuration", "end" ]
There are no configuration options yet.
[ "There", "are", "no", "configuration", "options", "yet", "." ]
5ea615abcf6e62afbbf82259d0aa533221d6de08
https://github.com/cubesystems/releaf/blob/5ea615abcf6e62afbbf82259d0aa533221d6de08/releaf-content/lib/releaf/content/acts_as_node.rb#L15-L23
train
rr/rr
lib/rr/space.rb
RR.Space.verify_ordered_double
def verify_ordered_double(double) unless double.terminal? raise RR::Errors.build_error(:DoubleOrderError, "Ordered Doubles cannot have a NonTerminal TimesCalledExpectation") end unless @ordered_doubles.first == double message = Double.formatted_name(double.method_name, double.expected_arguments) message << " called out of order in list\n" message << Double.list_message_part(@ordered_doubles) raise RR::Errors.build_error(:DoubleOrderError, message) end @ordered_doubles.shift unless double.attempt? double end
ruby
def verify_ordered_double(double) unless double.terminal? raise RR::Errors.build_error(:DoubleOrderError, "Ordered Doubles cannot have a NonTerminal TimesCalledExpectation") end unless @ordered_doubles.first == double message = Double.formatted_name(double.method_name, double.expected_arguments) message << " called out of order in list\n" message << Double.list_message_part(@ordered_doubles) raise RR::Errors.build_error(:DoubleOrderError, message) end @ordered_doubles.shift unless double.attempt? double end
[ "def", "verify_ordered_double", "(", "double", ")", "unless", "double", ".", "terminal?", "raise", "RR", "::", "Errors", ".", "build_error", "(", ":DoubleOrderError", ",", "\"Ordered Doubles cannot have a NonTerminal TimesCalledExpectation\"", ")", "end", "unless", "@ordered_doubles", ".", "first", "==", "double", "message", "=", "Double", ".", "formatted_name", "(", "double", ".", "method_name", ",", "double", ".", "expected_arguments", ")", "message", "<<", "\" called out of order in list\\n\"", "message", "<<", "Double", ".", "list_message_part", "(", "@ordered_doubles", ")", "raise", "RR", "::", "Errors", ".", "build_error", "(", ":DoubleOrderError", ",", "message", ")", "end", "@ordered_doubles", ".", "shift", "unless", "double", ".", "attempt?", "double", "end" ]
Verifies that the passed in ordered Double is being called in the correct position.
[ "Verifies", "that", "the", "passed", "in", "ordered", "Double", "is", "being", "called", "in", "the", "correct", "position", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/lib/rr/space.rb#L38-L51
train
rr/rr
lib/rr/space.rb
RR.Space.reset
def reset RR.trim_backtrace = false RR.overridden_error_class = nil reset_ordered_doubles Injections::DoubleInjection.reset reset_method_missing_injections reset_singleton_method_added_injections reset_recorded_calls reset_bound_objects end
ruby
def reset RR.trim_backtrace = false RR.overridden_error_class = nil reset_ordered_doubles Injections::DoubleInjection.reset reset_method_missing_injections reset_singleton_method_added_injections reset_recorded_calls reset_bound_objects end
[ "def", "reset", "RR", ".", "trim_backtrace", "=", "false", "RR", ".", "overridden_error_class", "=", "nil", "reset_ordered_doubles", "Injections", "::", "DoubleInjection", ".", "reset", "reset_method_missing_injections", "reset_singleton_method_added_injections", "reset_recorded_calls", "reset_bound_objects", "end" ]
Resets the registered Doubles and ordered Doubles
[ "Resets", "the", "registered", "Doubles", "and", "ordered", "Doubles" ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/lib/rr/space.rb#L61-L70
train
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.load_gems_in
def load_gems_in(*spec_dirs) @gems.clear spec_dirs.reverse_each do |spec_dir| spec_files = Dir.glob File.join(spec_dir, '*.gemspec') spec_files.each do |spec_file| gemspec = self.class.load_specification spec_file.untaint add_spec gemspec if gemspec end end self end
ruby
def load_gems_in(*spec_dirs) @gems.clear spec_dirs.reverse_each do |spec_dir| spec_files = Dir.glob File.join(spec_dir, '*.gemspec') spec_files.each do |spec_file| gemspec = self.class.load_specification spec_file.untaint add_spec gemspec if gemspec end end self end
[ "def", "load_gems_in", "(", "*", "spec_dirs", ")", "@gems", ".", "clear", "spec_dirs", ".", "reverse_each", "do", "|", "spec_dir", "|", "spec_files", "=", "Dir", ".", "glob", "File", ".", "join", "(", "spec_dir", ",", "'*.gemspec'", ")", "spec_files", ".", "each", "do", "|", "spec_file", "|", "gemspec", "=", "self", ".", "class", ".", "load_specification", "spec_file", ".", "untaint", "add_spec", "gemspec", "if", "gemspec", "end", "end", "self", "end" ]
Reconstruct the source index from the specifications in +spec_dirs+.
[ "Reconstruct", "the", "source", "index", "from", "the", "specifications", "in", "+", "spec_dirs", "+", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L119-L132
train
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
Gem.SourceIndex.index_signature
def index_signature require 'digest' Digest::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s end
ruby
def index_signature require 'digest' Digest::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s end
[ "def", "index_signature", "require", "'digest'", "Digest", "::", "SHA256", ".", "new", ".", "hexdigest", "(", "@gems", ".", "keys", ".", "sort", ".", "join", "(", "','", ")", ")", ".", "to_s", "end" ]
The signature for the source index. Changes in the signature indicate a change in the index.
[ "The", "signature", "for", "the", "source", "index", ".", "Changes", "in", "the", "signature", "indicate", "a", "change", "in", "the", "index", "." ]
d110480098473531aebff319493dbb95a4d8e706
https://github.com/rr/rr/blob/d110480098473531aebff319493dbb95a4d8e706/spec/fixtures/rubygems_patch_for_187.rb#L228-L232
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "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", ")", "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
train
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
train
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
train
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", "$:", ".", "unshift", "\"./test\"", ",", "\"./spec\"", ",", "\"./lib\"", "begin", "require", "\"./#{testable.file}\"", "rescue", "LoadError", "=>", "e", "STDERR", ".", "puts", "\"Failed loading test file:\\n#{e.message}\"", "return", "[", "]", "end", "suites", "=", "runner", ".", "suites", "suites", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "suite_class", ",", "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
train
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
train
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", "(", ")", "prepare", "document", "case", "document", "when", "Array", "stack", "=", "@document", ".", "reverse", "when", "HTML", "::", "Node", "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", "=", "[", "]", "@stop", "=", "false", "rules", "=", "self", ".", "class", ".", "rules", ".", "clone", "begin", "while", "node", "=", "stack", ".", "pop", "break", "if", "@stop", "skip_this", "=", "false", "next", "unless", "node", ".", "tag?", "@skip", ".", "delete_if", "{", "|", "s", "|", "skip_this", "=", "true", "if", "s", ".", "equal?", "(", "node", ")", "}", "next", "if", "skip_this", "rules", ".", "delete_if", "do", "|", "selector", ",", "extractor", ",", "rule_name", ",", "first_only", "|", "break", "if", "skip_this", "if", "selected", "=", "selector", ".", "match", "(", "node", ",", "first_only", ")", "selected", "=", "[", "selected", "]", "unless", "selected", ".", "is_a?", "(", "Array", ")", "selected", "=", "[", "selected", ".", "first", "]", "if", "first_only", "selected", ".", "each", "do", "|", "element", "|", "next", "if", "@skip", ".", "find", "{", "|", "s", "|", "s", ".", "equal?", "(", "element", ")", "}", "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", "!", "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
train
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", ")", "options", "=", "{", "}", "READER_OPTIONS", ".", "each", "{", "|", "key", "|", "options", "[", "key", "]", "=", "option", "(", "key", ")", "}", "request", "(", "@document", ",", "options", ")", "end", "if", "@document", ".", "is_a?", "(", "String", ")", "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
train
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
train
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
train
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
train
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
train
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", "(", "/", "/", ")", "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", "(", "/", "/", ")", "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
train
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
train
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", "|", "return", "false", "unless", "element", ".", "parent", "and", "element", ".", "parent", ".", "tag?", "name", "=", "of_type", "?", "element", ".", "name", ":", "nil", "other", "=", "false", "for", "child", "in", "element", ".", "parent", ".", "children", "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
train
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
train
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 && [email protected]? 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 && [email protected]? 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
train
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
train
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
train
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
train
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
train
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'", "]", "raise", "UnknownCode", ",", "\"In \\#add_error: Unknown error code '#{code}'\"", "unless", "@descriptions", ".", "recognised?", "(", "code", ")", "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", "@http_status_code", "=", "(", "description", "[", "'status'", "]", "||", "200", ")", ".", "to_i", "if", "@errors", ".", "empty?", "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", ")", "}", "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
train
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
train
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 ||= '[email protected]: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 ||= '[email protected]: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", "||=", "'[email protected]: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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "finish", "@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", "|", "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", ")", "@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", "@http", ".", "verify_depth", "=", "9", "else", "@http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "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_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", "@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
train
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", "same_auth_params_as_before", "=", "SECURITY_PARAMS", ".", "select", "do", "|", "param", "|", "request_params", "[", "param", "]", "!=", "get_param", "(", "param", ")", "end", ".", "empty?", "mypos", "=", "get_fileptr_offset", "(", "current_params", ")", "loop", "do", "current_params", "[", ":protocol", "]", "||=", "(", "current_params", "[", ":port", "]", "==", "443", "?", "'https'", ":", "'http'", ")", "same_server_as_before", "=", "@server", "==", "current_params", "[", ":server", "]", "&&", "@port", "==", "current_params", "[", ":port", "]", "&&", "@protocol", "==", "current_params", "[", ":protocol", "]", "&&", "same_auth_params_as_before", "if", "error_count", ">", "current_params", "[", ":http_connection_retry_count", "]", "&&", "error_time", "+", "current_params", "[", ":http_connection_retry_delay", "]", ">", "Time", ".", "now", "&&", "same_server_as_before", "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", "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", "setup_streaming", "(", "request", ")", "@http", ".", "read_timeout", "=", "get_param", "(", ":http_connection_read_timeout", ",", "current_params", ")", "response", "=", "@http", ".", "request", "(", "request", ",", "&", "block", ")", "error_reset", "eof_reset", "return", "response", "rescue", "EOFError", "=>", "e", "finish", "(", "e", ".", "message", ")", "@logger", ".", "debug", "(", "\"#{err_header} server #{@server} closed connection\"", ")", "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", "sleep", "(", "add_eof", ")", "reset_fileptr_offset", "(", "request", ",", "mypos", ")", "end", "rescue", "ArgumentError", "=>", "e", "finish", "(", "e", ".", "message", ")", "if", "e", ".", "message", ".", "include?", "(", "'wrong number of arguments (5 for 4)'", ")", "raise", "exception", ".", "new", "(", "'incompatible Net::HTTP monkey-patch'", ")", "else", "raise", "e", "end", "rescue", "Timeout", "::", "Error", ",", "SocketError", ",", "SystemCallError", ",", "Interrupt", "=>", "e", "finish", "(", "e", ".", "message", ")", "if", "e", ".", "is_a?", "(", "Errno", "::", "ETIMEDOUT", ")", "||", "e", ".", "is_a?", "(", "Timeout", "::", "Error", ")", "raise", "exception", ".", "new", "(", "\"#{e.class.name}: #{e.message}\"", ")", "if", "current_params", "[", ":raise_on_timeout", "]", "elsif", "e", ".", "is_a?", "(", "Interrupt", ")", "@logger", ".", "debug", "(", "\"#{err_header} request to server #{@server} interrupted by ctrl-c\"", ")", "raise", "e", "end", "error_add", "(", "e", ")", "@logger", ".", "warn", "(", "\"#{err_header} request failure count: #{error_count}, exception: #{e.inspect}\"", ")", "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
train
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
train
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'", ",", "'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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "flavour", "=", "if", "@msg", ".", "nil?", "nil", "elsif", "@msg", "[", "'action'", "]", "==", "'cancel'", "@msg", "[", "'flavour'", "]", "||", "'cancel'", "elsif", "h", ".", "state", ".", "nil?", "nil", "else", "@msg", "[", "'flavour'", "]", "end", "%w[", "timeout_schedule_id", "job_id", "]", ".", "each", "do", "|", "sid", "|", "@context", ".", "storage", ".", "delete_schedule", "(", "h", "[", "sid", "]", ")", "if", "h", "[", "sid", "]", "end", "@context", ".", "storage", ".", "delete_schedule", "(", "h", ".", "schedule_id", ")", "if", "h", ".", "schedule_id", "h", ".", "timers", ".", "each", "do", "|", "schedule_id", ",", "action", "|", "@context", ".", "storage", ".", "delete_schedule", "(", "schedule_id", ")", "end", "if", "h", ".", "timers", "cancel_flanks", "(", "h", ".", "state", "==", "'dying'", "?", "'kill'", ":", "nil", ")", "if", "h", ".", "state", "==", "'failing'", "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_unpersist", "elsif", "h", ".", "lost", "&&", "h", ".", "state", ".", "nil?", "do_persist", "elsif", "h", ".", "trigger", "&&", "workitem", "[", "'fields'", "]", "[", "\"__#{h.trigger}__\"", "]", "trigger", "(", "h", ".", "trigger", ",", "workitem", ")", "else", "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", "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", ",", "'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", ")", "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
train
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
train
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
train