code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def perform_queries(count:) QueryCounter.new(count: count) end
Checks the number of queries performed on the database. expect { code }.to perform_queries(count: 2)
perform_queries
ruby
sudara/alonetone
spec/support/query_matchers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/query_matchers.rb
MIT
def storage_service(storage_service) ActiveStorage::Service.configure( storage_service, ::Rails.configuration.active_storage.service_configurations ) end
Returns a new storage service instance so we can configure a global service.
storage_service
ruby
sudara/alonetone
spec/support/storage_service_helpers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/storage_service_helpers.rb
MIT
def with_storage_service(storage_service) before = ::Rails.application.config.active_storage.service service = ActiveStorage::Blob.service begin ::Rails.application.config.active_storage.service = storage_service ActiveStorage::Blob.service = storage_service(storage_service) yield ensure ::Rails.application.config.active_storage.service = before ActiveStorage::Blob.service = service end end
Temporarily switches out the global storage service class.
with_storage_service
ruby
sudara/alonetone
spec/support/storage_service_helpers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/storage_service_helpers.rb
MIT
def generate_waveform waveform = [] 1.upto(500) do |i| positive_sine = Math.sin(i / 10.0) + 1 waveform << (positive_sine * 1000000).round end waveform end
Generates an array of 500 large integers which should resemble a sine shape when rendered.
generate_waveform
ruby
sudara/alonetone
spec/support/waveform_helpers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/waveform_helpers.rb
MIT
def initialize(invocation_path, context = {}) @invocation_path = invocation_path @context = context end
Create a command execution. @param [String] invocation_path the path used to invoke the command @param [Hash] context additional data the command may need
initialize
ruby
mdub/clamp
lib/clamp/command.rb
https://github.com/mdub/clamp/blob/master/lib/clamp/command.rb
MIT
def parse(arguments) @remaining_arguments = arguments.dup parse_options parse_parameters parse_subcommand verify_required_options_are_set handle_remaining_arguments end
Parse command-line arguments. @param [Array<String>] arguments command-line arguments @return [Array<String>] unconsumed arguments
parse
ruby
mdub/clamp
lib/clamp/command.rb
https://github.com/mdub/clamp/blob/master/lib/clamp/command.rb
MIT
def run(arguments) parse(arguments) execute end
Run the command, with the specified arguments. This calls {#parse} to process the command-line arguments, then delegates to {#execute}. @param [Array<String>] arguments command-line arguments
run
ruby
mdub/clamp
lib/clamp/command.rb
https://github.com/mdub/clamp/blob/master/lib/clamp/command.rb
MIT
def execute raise "you need to define #execute" end
Execute the command (assuming that all options/parameters have been set). This method is designed to be overridden in sub-classes.
execute
ruby
mdub/clamp
lib/clamp/command.rb
https://github.com/mdub/clamp/blob/master/lib/clamp/command.rb
MIT
def subcommand_missing(name) signal_usage_error(Clamp.message(:no_such_subcommand, name: name)) end
Abort with subcommand missing usage error @ param [String] name subcommand_name
subcommand_missing
ruby
mdub/clamp
lib/clamp/command.rb
https://github.com/mdub/clamp/blob/master/lib/clamp/command.rb
MIT
def run(invocation_path = File.basename($PROGRAM_NAME), arguments = ARGV, context = {}) new(invocation_path, context).run(arguments) rescue Clamp::UsageError => e $stderr.puts "ERROR: #{e.message}" $stderr.puts "" $stderr.puts "See: '#{e.command.invocation_path} --help'" exit(1) rescue Clamp::HelpWanted => e puts e.command.help rescue Clamp::ExecutionError => e $stderr.puts "ERROR: #{e.message}" exit(e.status) rescue SignalException => e exit(128 + e.signo) end
Create an instance of this command class, and run it. @param [String] invocation_path the path used to invoke the command @param [Array<String>] arguments command-line arguments @param [Hash] context additional data the command may need
run
ruby
mdub/clamp
lib/clamp/command.rb
https://github.com/mdub/clamp/blob/master/lib/clamp/command.rb
MIT
def _replace(values) set([]) Array(values).each { |value| take(value) } end
default implementation of write_method for multi-valued attributes
_replace
ruby
mdub/clamp
lib/clamp/attribute/instance.rb
https://github.com/mdub/clamp/blob/master/lib/clamp/attribute/instance.rb
MIT
def hash_literal(hash) literal = '{ ' hash.each_with_index do |(key, value), index| literal << ', ' unless index.zero? literal << "#{key.inspect} => #{value.inspect}" end literal << ' }' end
Hash#inspect generates invalid literal with following example: > eval({ :predicate? => 1 }.inspect) SyntaxError: (eval):1: syntax error, unexpected => {:predicate?=>1} ^
hash_literal
ruby
yujinakayama/transpec
lib/transpec/dynamic_analyzer/rewriter.rb
https://github.com/yujinakayama/transpec/blob/master/lib/transpec/dynamic_analyzer/rewriter.rb
MIT
def size_source if size_node.sym_type? && size_node.children.first == :no 0 elsif size_node.str_type? size_node.children.first.to_i else size_node.loc.expression.source end end
https://github.com/rspec/rspec-expectations/blob/v2.14.5/lib/rspec/matchers/built_in/have.rb#L8-L12
size_source
ruby
yujinakayama/transpec
lib/transpec/syntax/have.rb
https://github.com/yujinakayama/transpec/blob/master/lib/transpec/syntax/have.rb
MIT
def block_base_indentation block_node.metadata[:indentation] ||= indentation_of_line(node) end
TODO: This is an ad-hoc solution for nested indentation manipulations.
block_base_indentation
ruby
yujinakayama/transpec
lib/transpec/syntax/its.rb
https://github.com/yujinakayama/transpec/blob/master/lib/transpec/syntax/its.rb
MIT
def block_node_taken_by_with_method_with_no_normal_args each_backward_chained_node(node, :child_as_second_arg) do |chained_node, child_node| next unless chained_node.block_type? return nil unless child_node.children[1] == :with return nil if child_node.children[2] return chained_node end end
subject.should_receive(:method_name).once.with do |block_arg| end (block (send (send (send (send nil :subject) :should_receive (sym :method_name)) :once) :with) (args (arg :block_arg)) nil)
block_node_taken_by_with_method_with_no_normal_args
ruby
yujinakayama/transpec
lib/transpec/syntax/should_receive.rb
https://github.com/yujinakayama/transpec/blob/master/lib/transpec/syntax/should_receive.rb
MIT
def block_node_followed_by_fluent_method each_backward_chained_node(node, :child_as_second_arg) do |chained_node, child_node| next unless chained_node.send_type? return child_node if child_node.block_type? end end
subject.should_receive(:method_name) do |block_arg| end.once (send (block (send (send nil :subject) :should_receive (sym :method_name)) (args (arg :block_arg)) nil) :once)
block_node_followed_by_fluent_method
ruby
yujinakayama/transpec
lib/transpec/syntax/should_receive.rb
https://github.com/yujinakayama/transpec/blob/master/lib/transpec/syntax/should_receive.rb
MIT
def get_batch_iteration_arg_value_arrays(batch_keys_to_iteration_keys) batch_keys = batch_keys_to_iteration_keys.keys batch_keys_to_batch_values = @args.slice(*(batch_keys)) batch_values = batch_keys_to_batch_values.values batch_values_to_batch_arrays(batch_values) end
Returns an array of argument value arrays, each of which should be passed to each of the batch iterations
get_batch_iteration_arg_value_arrays
ruby
socialpandas/sidekiq-superworker
lib/sidekiq/superworker/dsl_hash.rb
https://github.com/socialpandas/sidekiq-superworker/blob/master/lib/sidekiq/superworker/dsl_hash.rb
MIT
def local_put_files_only(local_array_pos) item_location = Local_templates + local_list[local_array_pos] # if used on a file, give a warning if File.file?(item_location) notification('This option should only be used on directories') abort 'This option should only be used on directories' else FileUtils.cp_r(Dir[item_location + '/*'], finder_dir) # run _templatesmanagerscript.* local_script_run(finder_dir) end end
If source is a directory, copy what's inside of it
local_put_files_only
ruby
vitorgalvao/alfred-workflows
TemplatesManager/source/tmfunctions.rb
https://github.com/vitorgalvao/alfred-workflows/blob/master/TemplatesManager/source/tmfunctions.rb
BSD-3-Clause
def to_yaml options = {} Psych.dump self, options end
## call-seq: to_yaml(options = {}) Convert an object to YAML. See Psych.dump for more information on the available +options+.
to_yaml
ruby
ruby/psych
lib/psych/core_ext.rb
https://github.com/ruby/psych/blob/master/lib/psych/core_ext.rb
MIT
def initialize handler = Handler.new @handler = handler @external_encoding = ANY end
## Creates a new Psych::Parser instance with +handler+. YAML events will be called on +handler+. See Psych::Parser for more details.
initialize
ruby
ruby/psych
lib/psych/parser.rb
https://github.com/ruby/psych/blob/master/lib/psych/parser.rb
MIT
def parse yaml, path = yaml.respond_to?(:path) ? yaml.path : "<unknown>" _native_parse @handler, yaml, path end
## call-seq: parser.parse(yaml) Parse the YAML document contained in +yaml+. Events will be called on the handler set on the parser instance. See Psych::Parser and Psych::Parser#handler
parse
ruby
ruby/psych
lib/psych/parser.rb
https://github.com/ruby/psych/blob/master/lib/psych/parser.rb
MIT
def tokenize string return nil if string.empty? return @symbol_cache[string] if @symbol_cache.key?(string) integer_regex = @strict_integer ? INTEGER_STRICT : INTEGER_LEGACY # Check for a String type, being careful not to get caught by hash keys, hex values, and # special floats (e.g., -.inf). if string.match?(%r{^[^\d.:-]?[[:alpha:]_\s!@#$%\^&*(){}<>|/\\~;=]+}) || string.match?(/\n/) return string if string.length > 5 if string.match?(/^[^ytonf~]/i) string elsif string == '~' || string.match?(/^null$/i) nil elsif string.match?(/^(yes|true|on)$/i) true elsif string.match?(/^(no|false|off)$/i) false else string end elsif string.match?(TIME) begin parse_time string rescue ArgumentError string end elsif string.match?(/^\d{4}-(?:1[012]|0\d|\d)-(?:[12]\d|3[01]|0\d|\d)$/) begin class_loader.date.strptime(string, '%F', Date::GREGORIAN) rescue ArgumentError string end elsif string.match?(/^\+?\.inf$/i) Float::INFINITY elsif string.match?(/^-\.inf$/i) -Float::INFINITY elsif string.match?(/^\.nan$/i) Float::NAN elsif string.match?(/^:./) if string =~ /^:(["'])(.*)\1/ @symbol_cache[string] = class_loader.symbolize($2.sub(/^:/, '')) else @symbol_cache[string] = class_loader.symbolize(string.sub(/^:/, '')) end elsif string.match?(/^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}$/) i = 0 string.split(':').each_with_index do |n,e| i += (n.to_i * 60 ** (e - 2).abs) end i elsif string.match?(/^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}\.[0-9_]*$/) i = 0 string.split(':').each_with_index do |n,e| i += (n.to_f * 60 ** (e - 2).abs) end i elsif string.match?(FLOAT) if string.match?(/\A[-+]?\.\Z/) string else Float(string.delete(',_').gsub(/\.([Ee]|$)/, '\1')) end elsif string.match?(integer_regex) parse_int string else string end end
Tokenize +string+ returning the Ruby object
tokenize
ruby
ruby/psych
lib/psych/scalar_scanner.rb
https://github.com/ruby/psych/blob/master/lib/psych/scalar_scanner.rb
MIT
def parse_time string klass = class_loader.load 'Time' date, time = *(string.split(/[ tT]/, 2)) (yy, m, dd) = date.match(/^(-?\d{4})-(\d{1,2})-(\d{1,2})/).captures.map { |x| x.to_i } md = time.match(/(\d+:\d+:\d+)(?:\.(\d*))?\s*(Z|[-+]\d+(:\d\d)?)?/) (hh, mm, ss) = md[1].split(':').map { |x| x.to_i } us = (md[2] ? Rational("0.#{md[2]}") : 0) * 1000000 time = klass.utc(yy, m, dd, hh, mm, ss, us) return time if 'Z' == md[3] return klass.at(time.to_i, us) unless md[3] tz = md[3].match(/^([+\-]?\d{1,2})\:?(\d{1,2})?$/)[1..-1].compact.map { |digit| Integer(digit, 10) } offset = tz.first * 3600 if offset < 0 offset -= ((tz[1] || 0) * 60) else offset += ((tz[1] || 0) * 60) end klass.new(yy, m, dd, hh, mm, ss+us/(1_000_000r), offset) end
## Parse and return a Time from +string+
parse_time
ruby
ruby/psych
lib/psych/scalar_scanner.rb
https://github.com/ruby/psych/blob/master/lib/psych/scalar_scanner.rb
MIT
def start_document version, tag_directives, implicit n = Nodes::Document.new version, tag_directives, implicit set_start_location(n) @last.children << n push n end
## Handles start_document events with +version+, +tag_directives+, and +implicit+ styling. See Psych::Handler#start_document
start_document
ruby
ruby/psych
lib/psych/tree_builder.rb
https://github.com/ruby/psych/blob/master/lib/psych/tree_builder.rb
MIT
def end_document implicit_end = !streaming? @last.implicit_end = implicit_end n = pop set_end_location(n) n end
## Handles end_document events with +version+, +tag_directives+, and +implicit+ styling. See Psych::Handler#start_document
end_document
ruby
ruby/psych
lib/psych/tree_builder.rb
https://github.com/ruby/psych/blob/master/lib/psych/tree_builder.rb
MIT
def y *objects puts Psych.dump_stream(*objects) end
## An alias for Psych.dump_stream meant to be used with IRB.
y
ruby
ruby/psych
lib/psych/y.rb
https://github.com/ruby/psych/blob/master/lib/psych/y.rb
MIT
def initialize anchor @anchor = anchor end
Create a new Alias that points to an +anchor+
initialize
ruby
ruby/psych
lib/psych/nodes/alias.rb
https://github.com/ruby/psych/blob/master/lib/psych/nodes/alias.rb
MIT
def initialize version = [], tag_directives = [], implicit = false super() @version = version @tag_directives = tag_directives @implicit = implicit @implicit_end = true end
## Create a new Psych::Nodes::Document object. +version+ is a list indicating the YAML version. +tags_directives+ is a list of tag directive declarations +implicit+ is a flag indicating whether the document will be implicitly started. == Example: This creates a YAML document object that represents a YAML 1.1 document with one tag directive, and has an implicit start: Psych::Nodes::Document.new( [1,1], [["!", "tag:tenderlovemaking.com,2009:"]], true ) == See Also See also Psych::Handler#start_document
initialize
ruby
ruby/psych
lib/psych/nodes/document.rb
https://github.com/ruby/psych/blob/master/lib/psych/nodes/document.rb
MIT
def initialize anchor = nil, tag = nil, implicit = true, style = BLOCK super() @anchor = anchor @tag = tag @implicit = implicit @style = style end
## Create a new Psych::Nodes::Mapping object. +anchor+ is the anchor associated with the map or +nil+. +tag+ is the tag associated with the map or +nil+. +implicit+ is a boolean indicating whether or not the map was implicitly started. +style+ is an integer indicating the mapping style. == See Also See also Psych::Handler#start_mapping
initialize
ruby
ruby/psych
lib/psych/nodes/mapping.rb
https://github.com/ruby/psych/blob/master/lib/psych/nodes/mapping.rb
MIT
def each &block return enum_for :each unless block_given? Visitors::DepthFirst.new(block).accept self end
## Iterate over each node in the tree. Yields each node to +block+ depth first.
each
ruby
ruby/psych
lib/psych/nodes/node.rb
https://github.com/ruby/psych/blob/master/lib/psych/nodes/node.rb
MIT
def to_ruby(symbolize_names: false, freeze: false, strict_integer: false) Visitors::ToRuby.create(symbolize_names: symbolize_names, freeze: freeze, strict_integer: strict_integer).accept(self) end
## Convert this node to Ruby. See also Psych::Visitors::ToRuby
to_ruby
ruby
ruby/psych
lib/psych/nodes/node.rb
https://github.com/ruby/psych/blob/master/lib/psych/nodes/node.rb
MIT
def initialize value, anchor = nil, tag = nil, plain = true, quoted = false, style = ANY @value = value @anchor = anchor @tag = tag @plain = plain @quoted = quoted @style = style end
## Create a new Psych::Nodes::Scalar object. +value+ is the string value of the scalar +anchor+ is an associated anchor or nil +tag+ is an associated tag or nil +plain+ is a boolean value +quoted+ is a boolean value +style+ is an integer indicating the string style == See Also See also Psych::Handler#scalar
initialize
ruby
ruby/psych
lib/psych/nodes/scalar.rb
https://github.com/ruby/psych/blob/master/lib/psych/nodes/scalar.rb
MIT
def initialize anchor = nil, tag = nil, implicit = true, style = BLOCK super() @anchor = anchor @tag = tag @implicit = implicit @style = style end
## Create a new object representing a YAML sequence. +anchor+ is the anchor associated with the sequence or nil. +tag+ is the tag associated with the sequence or nil. +implicit+ a boolean indicating whether or not the sequence was implicitly started. +style+ is an integer indicating the list style. See Psych::Handler#start_sequence
initialize
ruby
ruby/psych
lib/psych/nodes/sequence.rb
https://github.com/ruby/psych/blob/master/lib/psych/nodes/sequence.rb
MIT
def initialize encoding = UTF8 super() @encoding = encoding end
## Create a new Psych::Nodes::Stream node with an +encoding+ that defaults to Psych::Nodes::Stream::UTF8. See also Psych::Handler#start_stream
initialize
ruby
ruby/psych
lib/psych/nodes/stream.rb
https://github.com/ruby/psych/blob/master/lib/psych/nodes/stream.rb
MIT
def mktime( year, mon, day, hour, min, sec, usec, zone = "Z" ) usec = Rational(usec.to_s) * 1000000 val = Time::utc( year.to_i, mon.to_i, day.to_i, hour.to_i, min.to_i, sec.to_i, usec ) if zone != "Z" hour = zone[0,3].to_i * 3600 min = zone[3,2].to_i * 60 ofs = (hour + min) val = Time.at( val.tv_sec - ofs, val.tv_nsec / 1000.0 ) end return val end
Make a time with the time zone
mktime
ruby
ruby/psych
test/psych/helper.rb
https://github.com/ruby/psych/blob/master/test/psych/helper.rb
MIT
def test_y assert_equal "y", Psych.load("--- y") assert_equal "Y", Psych.load("--- Y") end
## YAML spec says "y" and "Y" may be used as true, but Syck treats them as literal strings
test_y
ruby
ruby/psych
test/psych/test_boolean.rb
https://github.com/ruby/psych/blob/master/test/psych/test_boolean.rb
MIT
def test_n assert_equal "n", Psych.load("--- n") assert_equal "N", Psych.load("--- N") end
## YAML spec says "n" and "N" may be used as false, but Syck treats them as literal strings
test_n
ruby
ruby/psych
test/psych/test_boolean.rb
https://github.com/ruby/psych/blob/master/test/psych/test_boolean.rb
MIT
def test_recursive_quick_emit_encode_with qeew = QuickEmitterEncodeWith.new hash = { :qe => qeew } hash2 = Psych.unsafe_load Psych.dump hash qe = hash2[:qe] assert_equal qeew.name, qe.name assert_instance_of QuickEmitterEncodeWith, qe assert_nil qe.value end
## An object that defines both to_yaml and encode_with should only call encode_with.
test_recursive_quick_emit_encode_with
ruby
ruby/psych
test/psych/test_deprecated.rb
https://github.com/ruby/psych/blob/master/test/psych/test_deprecated.rb
MIT
def test_yaml_initialize_and_init_with hash = { :yi => YamlInitAndInitWith.new } hash2 = Psych.unsafe_load Psych.dump hash yi = hash2[:yi] assert_equal 'TGIF!', yi.name assert_equal 'TGIF!', yi.value assert_instance_of YamlInitAndInitWith, yi end
## An object that implements both yaml_initialize and init_with should not receive the yaml_initialize call.
test_yaml_initialize_and_init_with
ruby
ruby/psych
test/psych/test_deprecated.rb
https://github.com/ruby/psych/blob/master/test/psych/test_deprecated.rb
MIT
def test_string_with_commas number = Psych.load('--- 12,34,56') assert_equal 123456, number end
This behavior is not to YML spec, but is kept for backwards compatibility
test_string_with_commas
ruby
ruby/psych
test/psych/test_numeric.rb
https://github.com/ruby/psych/blob/master/test/psych/test_numeric.rb
MIT
def test_load_shorthand list = [["a", "b"], ["c", "d"]] map = Psych.load(<<-eoyml) --- !!omap - a: b - c: d eoyml assert_equal list, map.to_a end
NOTE: This test will not work with Syck
test_load_shorthand
ruby
ruby/psych
test/psych/test_omap.rb
https://github.com/ruby/psych/blob/master/test/psych/test_omap.rb
MIT
def test_load_from_yaml loaded = Psych.unsafe_load(<<-eoyml) --- !set foo: bar bar: baz eoyml assert_equal(@set, loaded) end
## FIXME: Syck should also support !!set as shorthand
test_load_from_yaml
ruby
ruby/psych
test/psych/test_psych_set.rb
https://github.com/ruby/psych/blob/master/test/psych/test_psych_set.rb
MIT
def test_stringio assert_nothing_raised do Psych.dump(StringIO.new("foo")) end end
The superclass of StringIO before Ruby 3.0 was `Data`, which can interfere with the Ruby 3.2+ `Data` dumping.
test_stringio
ruby
ruby/psych
test/psych/test_stringio.rb
https://github.com/ruby/psych/blob/master/test/psych/test_stringio.rb
MIT
def test_basic_map # Simple map assert_parse_only( { 'one' => 'foo', 'three' => 'baz', 'two' => 'bar' }, <<EOY one: foo two: bar three: baz EOY ) end
Tests modified from 00basic.t in Psych.pm
test_basic_map
ruby
ruby/psych
test/psych/test_yaml.rb
https://github.com/ruby/psych/blob/master/test/psych/test_yaml.rb
MIT
def test_spec_simple_implicit_sequence # Simple implicit sequence assert_to_yaml( [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ], <<EOY - Mark McGwire - Sammy Sosa - Ken Griffey EOY ) end
Test the specification examples - Many examples have been changes because of whitespace problems that caused the two to be inequivalent, or keys to be sorted wrong
test_spec_simple_implicit_sequence
ruby
ruby/psych
test/psych/test_yaml.rb
https://github.com/ruby/psych/blob/master/test/psych/test_yaml.rb
MIT
def test_spec_override_anchor # Override anchor a001 = "The alias node below is a repeated use of this value.\n" assert_parse_only( { 'anchor' => 'This scalar has an anchor.', 'override' => a001, 'alias' => a001 }, <<EOY anchor : &A001 This scalar has an anchor. override : &A001 > The alias node below is a repeated use of this value. alias : *A001 EOY ) end
## Commenting out this test. This line: - !domain.tld,2002/type\\x30 value Is invalid according to the YAML spec: http://yaml.org/spec/1.1/#id896876 def test_spec_url_escaping Psych.add_domain_type( "domain.tld,2002", "type0" ) { |type, val| "ONE: #{val}" } Psych.add_domain_type( "domain.tld,2002", "type%30" ) { |type, val| "TWO: #{val}" } assert_parse_only( { 'same' => [ 'ONE: value', 'ONE: value' ], 'different' => [ 'TWO: value' ] }, <<EOY same: - !domain.tld,2002/type\\x30 value - !domain.tld,2002/type0 value different: # As far as the Psych parser is concerned - !domain.tld,2002/type%30 value EOY ) end
test_spec_override_anchor
ruby
ruby/psych
test/psych/test_yaml.rb
https://github.com/ruby/psych/blob/master/test/psych/test_yaml.rb
MIT
def test_akira # Commas in plain scalars [ruby-core:1066] assert_to_yaml( {"A"=>"A,","B"=>"B"}, <<EOY A: "A," B: B EOY ) # Double-quoted keys [ruby-core:1069] assert_to_yaml( {"1"=>2, "2"=>3}, <<EOY '1': 2 "2": 3 EOY ) # Anchored mapping [ruby-core:1071] assert_to_yaml( [{"a"=>"b"}] * 2, <<EOY - &id001 a: b - *id001 EOY ) # Stress test [ruby-core:1071] # a = []; 1000.times { a << {"a"=>"b", "c"=>"d"} } # Psych::load( a.to_yaml ) end
# # Test the Psych::Stream class -- INACTIVE at the moment # def test_document y = Psych::Stream.new( :Indent => 2, :UseVersion => 0 ) y.add( { 'hi' => 'hello', 'map' => { 'good' => 'two' }, 'time' => Time.now, 'try' => /^po(.*)$/, 'bye' => 'goodbye' } ) y.add( { 'po' => 'nil', 'oper' => 90 } ) y.add( { 'hi' => 'wow!', 'bye' => 'wow!' } ) y.add( { [ 'Red Socks', 'Boston' ] => [ 'One', 'Two', 'Three' ] } ) y.add( [ true, false, false ] ) end Test YPath choices parsing def test_ypath_parsing assert_path_segments( "/*/((one|three)/name|place)|//place", [ ["*", "one", "name"], ["*", "three", "name"], ["*", "place"], ["/", "place"] ] ) end Tests from Tanaka Akira on [ruby-core]
test_akira
ruby
ruby/psych
test/psych/test_yaml.rb
https://github.com/ruby/psych/blob/master/test/psych/test_yaml.rb
MIT
def test_empty_map_key # # empty seq as key # assert_cycle({[]=>""}) # # empty map as key # assert_cycle({{}=>""}) end
Test empty map/seq in map cycle
test_empty_map_key
ruby
ruby/psych
test/psych/test_yaml.rb
https://github.com/ruby/psych/blob/master/test/psych/test_yaml.rb
MIT
def test_object_id_collision omap = Psych::Omap.new 1000.times { |i| omap["key_#{i}"] = { "value" => i } } raise "id collision in ordered map" if Psych.dump(omap) =~ /id\d+/ end
contributed by riley lynch [ruby-Bugs-8548]
test_object_id_collision
ruby
ruby/psych
test/psych/test_yaml.rb
https://github.com/ruby/psych/blob/master/test/psych/test_yaml.rb
MIT
def test_key @yamldbm['a'] = 'b' @yamldbm['c'] = 'd' assert_equal 'a', @yamldbm.key('b') assert_equal 'c', @yamldbm.key('d') assert_nil @yamldbm.key('f') end
Note: YAML::DBM#index makes warning from internal of ::DBM#index. It says 'DBM#index is deprecated; use DBM#key', but DBM#key behaves not same as DBM#index. def test_index @yamldbm['a'] = 'b' @yamldbm['c'] = 'd' assert_equal 'a', @yamldbm.index('b') assert_equal 'c', @yamldbm.index('d') assert_nil @yamldbm.index('f') end
test_key
ruby
ruby/psych
test/psych/test_yamldbm.rb
https://github.com/ruby/psych/blob/master/test/psych/test_yamldbm.rb
MIT
def test_boolean_true %w{ yes Yes YES true True TRUE on On ON }.each do |t| i = Nodes::Scalar.new(t, nil, 'tag:yaml.org,2002:bool') assert_equal true, i.to_ruby assert_equal true, Nodes::Scalar.new(t).to_ruby end end
http://yaml.org/type/bool.html
test_boolean_true
ruby
ruby/psych
test/psych/visitors/test_to_ruby.rb
https://github.com/ruby/psych/blob/master/test/psych/visitors/test_to_ruby.rb
MIT
def test_boolean_false %w{ no No NO false False FALSE off Off OFF }.each do |t| i = Nodes::Scalar.new(t, nil, 'tag:yaml.org,2002:bool') assert_equal false, i.to_ruby assert_equal false, Nodes::Scalar.new(t).to_ruby end end
http://yaml.org/type/bool.html
test_boolean_false
ruby
ruby/psych
test/psych/visitors/test_to_ruby.rb
https://github.com/ruby/psych/blob/master/test/psych/visitors/test_to_ruby.rb
MIT
def test_nil assert_cycle nil assert_nil Psych.load('null') assert_nil Psych.load('Null') assert_nil Psych.load('NULL') assert_nil Psych.load('~') assert_equal({'foo' => nil}, Psych.load('foo: ')) assert_cycle 'null' assert_cycle 'nUll' assert_cycle '~' end
http://yaml.org/type/null.html
test_nil
ruby
ruby/psych
test/psych/visitors/test_yaml_tree.rb
https://github.com/ruby/psych/blob/master/test/psych/visitors/test_yaml_tree.rb
MIT
def layout_in_effect(field_layout) field_layout = :inline if field_layout == true field_layout = :vertical if field_layout == false field_layout || layout end
true and false should only come from check_box and radio_button, and those don't have a :horizontal layout
layout_in_effect
ruby
bootstrap-ruby/bootstrap_form
lib/bootstrap_form/components/layout.rb
https://github.com/bootstrap-ruby/bootstrap_form/blob/master/lib/bootstrap_form/components/layout.rb
MIT
def bootstrap_alias(field_name) alias_method :"#{field_name}_without_bootstrap", field_name alias_method field_name, :"#{field_name}_with_bootstrap" rescue NameError # rubocop:disable Lint/SuppressedException end
Creates the methods *_without_bootstrap and *_with_bootstrap. If your application did not include the rails gem for one of the dsl methods, then a name error is raised and suppressed. This can happen if your application does not include the actiontext dependency due to `rich_text_area` not being defined.
bootstrap_alias
ruby
bootstrap-ruby/bootstrap_form
lib/bootstrap_form/inputs/base.rb
https://github.com/bootstrap-ruby/bootstrap_form/blob/master/lib/bootstrap_form/inputs/base.rb
MIT
def collection_select_with_bootstrap(method, collection, value_method, text_method, options={}, html_options={}) html_options = html_options.reverse_merge(control_class: "form-select") form_group_builder(method, options, html_options) do prepend_and_append_input(method, options) do collection_select_without_bootstrap(method, collection, value_method, text_method, options, html_options) end end end
Disabling Metrics/ParameterLists because the upstream Rails method has the same parameters rubocop:disable Metrics/ParameterLists
collection_select_with_bootstrap
ruby
bootstrap-ruby/bootstrap_form
lib/bootstrap_form/inputs/collection_select.rb
https://github.com/bootstrap-ruby/bootstrap_form/blob/master/lib/bootstrap_form/inputs/collection_select.rb
MIT
def grouped_collection_select_with_bootstrap(method, collection, group_method, group_label_method, option_key_method, option_value_method, options={}, html_options={}) html_options = html_options.reverse_merge(control_class: "form-select") form_group_builder(method, options, html_options) do prepend_and_append_input(method, options) do grouped_collection_select_without_bootstrap(method, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options) end end end
Disabling Metrics/ParameterLists because the upstream Rails method has the same parameters rubocop:disable Metrics/ParameterLists
grouped_collection_select_with_bootstrap
ruby
bootstrap-ruby/bootstrap_form
lib/bootstrap_form/inputs/grouped_collection_select.rb
https://github.com/bootstrap-ruby/bootstrap_form/blob/master/lib/bootstrap_form/inputs/grouped_collection_select.rb
MIT
def form_group_collection_input_options(options, text, obj, index, input_value, collection) input_options = options.merge(label: text.respond_to?(:call) ? text.call(obj) : obj.send(text)) if (checked = input_options[:checked]) input_options[:checked] = form_group_collection_input_checked?(checked, obj, input_value) end # add things like 'data-' attributes to the HTML obj.each { |inner_obj| input_options.merge!(inner_obj) if inner_obj.is_a?(Hash) } if obj.respond_to?(:each) input_options[:error_message] = index == collection.size - 1 input_options.except!(:class) input_options end
FIXME: Find a way to reduce the parameter list size rubocop:disable Metrics/ParameterLists
form_group_collection_input_options
ruby
bootstrap-ruby/bootstrap_form
lib/bootstrap_form/inputs/inputs_collection.rb
https://github.com/bootstrap-ruby/bootstrap_form/blob/master/lib/bootstrap_form/inputs/inputs_collection.rb
MIT
def form_with_builder builder = nil bootstrap_form_with(model: @user) { |f| builder = f } builder end
Originally only used in one test file but placed here in case it's needed in others in the future.
form_with_builder
ruby
bootstrap-ruby/bootstrap_form
test/test_helper.rb
https://github.com/bootstrap-ruby/bootstrap_form/blob/master/test/test_helper.rb
MIT
def slugify(str) str.gsub(/\W/, '_') end
replaces all non-ascii characters with an underscore
slugify
ruby
getkuby/kuby-core
lib/kuby/plugins/rails_app/crdb/plugin.rb
https://github.com/getkuby/kuby-core/blob/master/lib/kuby/plugins/rails_app/crdb/plugin.rb
MIT
def create(&block) task = Runner.run( name: params.fetch(:task_id), csv_file: params[:csv_file], arguments: params.fetch(:task, {}).permit!.to_h, metadata: instance_exec(&MaintenanceTasks.metadata || -> {}), &block ) redirect_to(task_path(task)) rescue ActiveRecord::RecordInvalid => error flash.now.alert = error.message @task = TaskDataShow.prepare(error.record.task_name, arguments: error.record.arguments) render(template: "maintenance_tasks/tasks/show") rescue ActiveRecord::ValueTooLong => error task_name = params.fetch(:task_id) redirect_to(task_path(task_name), alert: error.message) rescue Runner::EnqueuingError => error redirect_to(task_path(error.run.task_name), alert: error.message) end
Creates a Run for a given Task and redirects to the Task page.
create
ruby
Shopify/maintenance_tasks
app/controllers/maintenance_tasks/runs_controller.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/controllers/maintenance_tasks/runs_controller.rb
MIT
def index @available_tasks = TaskDataIndex.available_tasks.group_by(&:category) end
Renders the maintenance_tasks/tasks page, displaying available tasks to users, grouped by category.
index
ruby
Shopify/maintenance_tasks
app/controllers/maintenance_tasks/tasks_controller.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/controllers/maintenance_tasks/tasks_controller.rb
MIT
def show @task = TaskDataShow.prepare( params.fetch(:id), runs_cursor: params[:cursor], arguments: params.except(:id, :controller, :action).permit!, ) end
Renders the page responsible for providing Task actions to users. Shows running and completed instances of the Task.
show
ruby
Shopify/maintenance_tasks
app/controllers/maintenance_tasks/tasks_controller.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/controllers/maintenance_tasks/tasks_controller.rb
MIT
def time_ago(datetime) time_tag(datetime, title: datetime.utc, class: "is-clickable") do time_ago_in_words(datetime) + " ago" end end
Renders a time element with the given datetime, worded as relative to the current time. The ISO 8601 version of the datetime is shown on hover via a title attribute. @param datetime [ActiveSupport::TimeWithZone] the time to be presented. @return [String] the HTML to render with the relative datetime in words.
time_ago
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/application_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/application_helper.rb
MIT
def format_backtrace(backtrace) safe_join(backtrace.to_a, tag.br) end
Formats a run backtrace. @param backtrace [Array<String>] the backtrace associated with an exception on a Task that ran and raised. @return [String] the parsed, HTML formatted version of the backtrace.
format_backtrace
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def progress(run) return unless run.started? progress = Progress.new(run) progress_bar = tag.progress( value: progress.value, max: progress.max, class: ["progress", "mt-4"] + STATUS_COLOURS.fetch(run.status), ) progress_text = tag.p(tag.i(progress.text)) tag.div(progress_bar + progress_text, class: "block") end
Renders the progress bar. The style of the progress tag depends on the Run status. It also renders an infinite progress when a Run is active but there is no total information to estimate completion. @param run [Run] the Run which the progress bar will be based on. @return [String] the progress information properly formatted. @return [nil] if the run has not started yet.
progress
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def status_tag(status) tag.span( status.capitalize, class: ["tag", "has-text-weight-medium", "pr-2", "mr-4"] + STATUS_COLOURS.fetch(status), ) end
Renders a span with a Run's status, with the corresponding tag class attached. @param status [String] the status for the Run. @return [String] the span element containing the status, with the appropriate tag class attached.
status_tag
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def time_running_in_words(run) distance_of_time_in_words(0, run.time_running, include_seconds: true) end
Reports the approximate elapsed time a Run has been processed so far based on the Run's time running attribute. @param run [Run] the source of the time to be reported. @return [String] the description of the time running attribute.
time_running_in_words
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def highlight_code(code) tokens = Ripper.lex(code).map do |(_position, type, content, _state)| case type when :on_nl, :on_sp, :on_ignored_nl content else tag.span(content, class: type.to_s.sub("on_", "ruby-").dasherize) end end safe_join(tokens) end
Very simple syntax highlighter based on Ripper. It returns the same code except identifiers, keywords, etc. are wrapped in +<span>+ tags with CSS classes that match the types returned by Ripper.lex. @param code [String] the Ruby code source to syntax highlight. @return [ActiveSupport::SafeBuffer] HTML of the code.
highlight_code
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def csv_file_download_path(run) Rails.application.routes.url_helpers.rails_blob_path( run.csv_file, only_path: true, ) end
Returns a download link for a Run's CSV attachment
csv_file_download_path
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def resolve_inclusion_value(task, parameter_name) task_class = task.class inclusion_validator = task_class.validators_on(parameter_name).find do |validator| validator.kind == :inclusion end return unless inclusion_validator in_option = inclusion_validator.options[:in] || inclusion_validator.options[:within] resolved_in_option = case in_option when Proc if in_option.arity == 0 in_option.call else in_option.call(task) end when Symbol method = task.method(in_option) method.call if method.arity.zero? else if in_option.respond_to?(:call) in_option.call(task) else in_option end end resolved_in_option if resolved_in_option.is_a?(Array) end
Resolves values covered by the inclusion validator for a Task attribute. Supported option types: - Arrays - Procs and lambdas that optionally accept the Task instance, and return an Array. - Callable objects that receive one argument, the Task instance, and return an Array. - Methods that return an Array, called on the Task instance. Other types are not supported and will return nil. Returned values are used to populate a dropdown list of options. @param task [Task] The Task for which the value needs to be resolved. @param parameter_name [String] The parameter name. @return [Array] value of the resolved inclusion option.
resolve_inclusion_value
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def parameter_field(form_builder, parameter_name) inclusion_values = resolve_inclusion_value(form_builder.object, parameter_name) if inclusion_values return tag.div(form_builder.select(parameter_name, inclusion_values, prompt: "Select a value"), class: "select") end case form_builder.object.class.attribute_types[parameter_name] when ActiveModel::Type::Integer form_builder.number_field(parameter_name, class: "input") when ActiveModel::Type::Decimal, ActiveModel::Type::Float form_builder.number_field(parameter_name, { step: "any", class: "input" }) when ActiveModel::Type::DateTime form_builder.datetime_field(parameter_name, class: "input") + datetime_field_help_text when ActiveModel::Type::Date form_builder.date_field(parameter_name, class: "input") when ActiveModel::Type::Time form_builder.time_field(parameter_name, class: "input") when ActiveModel::Type::Boolean form_builder.check_box(parameter_name, class: "checkbox") else form_builder.text_area(parameter_name, class: "textarea") end .then { |input| tag.div(input, class: "control") } end
Return the appropriate field tag for the parameter, based on its type. If the parameter has a `validates_inclusion_of` validator, return a dropdown list of options instead.
parameter_field
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def datetime_field_help_text text = if Time.zone_default.nil? || Time.zone_default.name == "UTC" "Timezone: UTC." else "Timezone: #{Time.now.zone}." end tag.div( tag.p(text), class: "content is-small", ) end
Return helper text for the datetime-local form field.
datetime_field_help_text
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def attribute_required?(task, parameter_name) task.class.validators_on(parameter_name).any? do |validator| validator.kind == :presence end end
Checks if an attribute is required for a given Task. @param task [MaintenanceTasks::TaskDataShow] The TaskDataShow instance. @param parameter_name [Symbol] The name of the attribute to check. @return [Boolean] Whether the attribute is required.
attribute_required?
ruby
Shopify/maintenance_tasks
app/helpers/maintenance_tasks/tasks_helper.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/helpers/maintenance_tasks/tasks_helper.rb
MIT
def retry_on(*, **) raise NotImplementedError, "retry_on is not supported" end
Overrides ActiveJob::Exceptions.retry_on to declare it unsupported. The use of rescue_from prevents retry_on from being usable.
retry_on
ruby
Shopify/maintenance_tasks
app/jobs/concerns/maintenance_tasks/task_job_concern.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/jobs/concerns/maintenance_tasks/task_job_concern.rb
MIT
def each_iteration(input, _run) throw(:abort, :skip_complete_callbacks) if @run.stopping? task_iteration(input) @ticker.tick @run.reload_status end
Performs task iteration logic for the current input returned by the enumerator. @param input [Object] the current element from the enumerator. @param _run [Run] the current Run, passed as an argument by Job Iteration.
each_iteration
ruby
Shopify/maintenance_tasks
app/jobs/concerns/maintenance_tasks/task_job_concern.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/jobs/concerns/maintenance_tasks/task_job_concern.rb
MIT
def initialize(batch_size, **csv_options) @batch_size = batch_size super(**csv_options) end
Initialize a BatchCsvCollectionBuilder with a batch size. @param batch_size [Integer] the number of CSV rows in a batch. @param csv_options [Hash] options to pass to the CSV parser.
initialize
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/batch_csv_collection_builder.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/batch_csv_collection_builder.rb
MIT
def collection(task) BatchCsv.new( csv: CSV.new(task.csv_content, **@csv_options), batch_size: @batch_size, ) end
Defines the collection to be iterated over, based on the provided CSV. Includes the CSV and the batch size.
collection
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/batch_csv_collection_builder.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/batch_csv_collection_builder.rb
MIT
def count(task) count = task.csv_content.count("\n") - 1 (count + @batch_size - 1) / @batch_size end
The number of batches to be processed. Excludes the header row from the count and assumes a trailing newline is at the end of the CSV file. Note that this number is an approximation based on the number of newlines. @return [Integer] the approximate number of batches to process.
count
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/batch_csv_collection_builder.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/batch_csv_collection_builder.rb
MIT
def collection(task) CSV.new(task.csv_content, **@csv_options) end
Defines the collection to be iterated over, based on the provided CSV. @return [CSV] the CSV object constructed from the specified CSV content.
collection
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/csv_collection_builder.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/csv_collection_builder.rb
MIT
def count(task) CSV.new(task.csv_content, **@csv_options).count end
The number of rows to be processed. It uses the CSV library for an accurate row count. Note that the entire file is loaded. It will take several seconds with files with millions of rows. @return [Integer] the approximate number of rows to process.
count
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/csv_collection_builder.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/csv_collection_builder.rb
MIT
def collection(task) raise NoMethodError, "#{task.class.name} must implement `collection`." end
Placeholder method to raise in case a subclass fails to implement the expected instance method. @raise [NotImplementedError] with a message advising subclasses to implement an override for this method.
collection
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/null_collection_builder.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/null_collection_builder.rb
MIT
def initialize(run) @run = run end
Sets the Progress initial state with a Run. @param run [Run] the source of progress information.
initialize
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/progress.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/progress.rb
MIT
def value @run.tick_count if estimatable? || @run.stopped? end
Defines the value of progress information. This represents the amount that is already done out of the progress maximum. For indefinite-style progress information, value is nil. That highlights that a Run is in progress but it is not possible to estimate how close to completion it is. When a Run is stopped, the value is present even if there is no total. That represents a progress information that assumes that the current value is also equal to is max, showing a progress as completed. @return [Integer] if progress can be determined or the Run is stopped. @return [nil] if progress can't be determined and the Run isn't stopped.
value
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/progress.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/progress.rb
MIT
def max estimatable? ? @run.tick_total : @run.tick_count end
The maximum amount of work expected to be done. This is extracted from the Run's tick total attribute when present, or it is equal to the Run's tick count. This amount is enqual to the Run's tick count if the tick count is greater than the tick total. This represents that the total was underestimated. @return [Integer] the progress maximum amount.
max
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/progress.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/progress.rb
MIT
def text count = @run.tick_count total = @run.tick_total if !total? "Processed #{number_to_delimited(count)} " \ "#{"item".pluralize(count)}." elsif over_total? "Processed #{number_to_delimited(count)} " \ "#{"item".pluralize(count)} " \ "(expected #{number_to_delimited(total)})." else percentage = 100.0 * count / total "Processed #{number_to_delimited(count)} out of " \ "#{number_to_delimited(total)} #{"item".pluralize(total)} " \ "(#{number_to_percentage(percentage, precision: 0)})." end end
The text containing progress information. This describes the progress of the Run so far. It includes the percentage done out of the maximum, if an estimate is possible. @return [String] the text for the Run progress.
text
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/progress.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/progress.rb
MIT
def enqueued! status_will_change! super rescue ActiveRecord::StaleObjectError reload_status retry end
Sets the run status to enqueued, making sure the transition is validated in case it's already enqueued. Rescues and retries status transition if an ActiveRecord::StaleObjectError is encountered.
enqueued!
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def persist_transition save! callback = CALLBACKS_TRANSITION[status] run_task_callbacks(callback) if callback rescue ActiveRecord::StaleObjectError success = succeeded? reload_status if success self.status = :succeeded else job_shutdown end retry end
Saves the run, persisting the transition of its status, and all other changes to the object.
persist_transition
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def persist_progress(number_of_ticks, duration) self.class.update_counters( id, tick_count: number_of_ticks, time_running: duration, touch: true, ) if locking_enabled? locking_column = self.class.locking_column self[locking_column] += 1 clear_attribute_change(locking_column) end end
Increments +tick_count+ by +number_of_ticks+ and +time_running+ by +duration+, both directly in the DB. The attribute values are not set in the current instance, you need to reload the record. @param number_of_ticks [Integer] number of ticks to add to tick_count. @param duration [Float] the time in seconds that elapsed since the last increment of ticks.
persist_progress
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def persist_error(error) self.started_at ||= Time.now update!( status: :errored, error_class: truncate(:error_class, error.class.name), error_message: truncate(:error_message, error.message), backtrace: MaintenanceTasks.backtrace_cleaner.clean(error.backtrace), ended_at: Time.now, ) run_error_callback rescue ActiveRecord::StaleObjectError reload_status retry end
Marks the run as errored and persists the error data. @param error [StandardError] the Error being persisted.
persist_error
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def reload_status columns_to_reload = if locking_enabled? [:status, self.class.locking_column] else [:status] end updated_status, updated_lock_version = self.class.uncached do self.class.where(id: id).pluck(*columns_to_reload).first end self.status = updated_status if updated_lock_version self[self.class.locking_column] = updated_lock_version end clear_attribute_changes(columns_to_reload) self end
Refreshes the status and lock version attributes on the Active Record object, and ensures ActiveModel::Dirty doesn't mark the object as changed. This allows us to get the Run's most up-to-date status without needing to reload the entire record. @return [MaintenanceTasks::Run] the Run record with its updated status.
reload_status
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def stopped? completed? || paused? end
Returns whether the Run is stopped, which is defined as having a status of paused, succeeded, cancelled, or errored. @return [Boolean] whether the Run is stopped.
stopped?
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def time_to_completion return if completed? || tick_count == 0 || tick_total.to_i == 0 processed_per_second = (tick_count.to_f / time_running) ticks_left = (tick_total - tick_count) seconds_to_finished = ticks_left / processed_per_second seconds_to_finished.seconds end
Returns the duration left for the Run to finish based on the number of ticks left and the average time needed to process a tick. Returns nil if the Run is completed, or if tick_count or tick_total is zero. @return [ActiveSupport::Duration] the estimated duration left for the Run to finish.
time_to_completion
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def running if locking_enabled? begin running! unless stopping? rescue ActiveRecord::StaleObjectError reload_status retry end else # Preserve swap-and-replace solution for data races until users # run migration to upgrade to optimistic locking solution return if stopping? updated = self.class.where(id: id).where.not(status: STOPPING_STATUSES) .update_all(status: :running, updated_at: Time.now) > 0 if updated self.status = :running clear_attribute_changes([:status]) else reload_status end end end
Marks a Run as running. If the run is stopping already, it will not transition to running. Rescues and retries status transition if an ActiveRecord::StaleObjectError is encountered.
running
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def start(count) update!(started_at: Time.now, tick_total: count) task.run_callbacks(:start) rescue ActiveRecord::StaleObjectError reload_status retry end
Starts a Run, setting its started_at timestamp and tick_total. @param count [Integer] the total iterations to be performed, as specified by the Task.
start
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def job_shutdown if cancelling? self.status = :cancelled self.ended_at = Time.now elsif pausing? self.status = :paused elsif cancelled? else self.status = :interrupted end end
Handles transitioning the status on a Run when the job shuts down.
job_shutdown
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def complete self.status = :succeeded self.ended_at = Time.now end
Handles the completion of a Run, setting a status of succeeded and the ended_at timestamp.
complete
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def cancel if paused? || stuck? self.status = :cancelled self.ended_at = Time.now persist_transition else cancelling! end rescue ActiveRecord::StaleObjectError reload_status retry end
Cancels a Run. If the Run is paused, it will transition directly to cancelled, since the Task is not being performed. In this case, the ended_at timestamp will be updated. If the Run is not paused, the Run will transition to cancelling. If the Run is already cancelling, and has last been updated more than 5 minutes ago, it will transition to cancelled, and the ended_at timestamp will be updated.
cancel
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def pause if stuck? self.status = :paused persist_transition else pausing! end rescue ActiveRecord::StaleObjectError reload_status retry end
Marks a Run as pausing. If the Run has been stuck on pausing for more than 5 minutes, it forces the transition to paused. The ended_at timestamp will be updated. Rescues and retries status transition if an ActiveRecord::StaleObjectError is encountered.
pause
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT
def stuck? (cancelling? || pausing?) && updated_at <= MaintenanceTasks.stuck_task_duration.ago end
Returns whether a Run is stuck, which is defined as having a status of cancelling or pausing, and not having been updated in the last 5 minutes. @return [Boolean] whether the Run is stuck.
stuck?
ruby
Shopify/maintenance_tasks
app/models/maintenance_tasks/run.rb
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
MIT