Skip to content

Commit

Permalink
Merge pull request #147 from OSC/refactor_array_ids
Browse files Browse the repository at this point in the history
Refactor array ids parsing with regex
  • Loading branch information
MorganRodgers authored Dec 12, 2019
2 parents 5daaa82 + dc8cad3 commit 8b345e7
Showing 1 changed file with 18 additions and 53 deletions.
71 changes: 18 additions & 53 deletions lib/ood_core/job/array_ids.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,68 +10,33 @@
module OodCore
module Job
class ArrayIds
class Error < StandardError ; end
attr_reader :spec_string

attr_reader :ids
def initialize(spec_string)
@ids = []
begin
parse_spec_string(spec_string) if spec_string
rescue Error
end
end

protected
def parse_spec_string(spec_string)
@ids = get_components(spec_string).map{
|component| process_component(component)
}.reduce(:+).sort
@spec_string = spec_string
end

def get_components(spec_string)
base = discard_percent_modifier(spec_string)
raise Error unless base
base.split(',')
def ids
@ids ||= parse_spec_string(spec_string)
end

# A few adapters use percent to define an arrays maximum number of
# simultaneous tasks. The percent is expected to come at the end.
def discard_percent_modifier(spec_string)
spec_string.split('%').first
end
protected

def process_component(component)
if is_range?(component)
get_range(component)
elsif numbers_valid?([component])
[ component.to_i ]
else
raise Error
def parse_spec_string(spec_string)
return [] unless spec_string

rx = /^(\d+)-?(\d+)?:?(\d+)?%?\d*$/
spec_string.split(',').reduce([]) do |ids, spec|
if rx =~ spec
start = ($1 || 1).to_i
finish = ($2 || start).to_i
step = ($3 || 1).to_i
ids.concat (start..finish).step(step).to_a
end

ids
end
end

def get_range(component)
raw_range, raw_step = component.split(':')
start, stop = raw_range.split('-')
raise Error unless numbers_valid?(
# Only include Step if it is not nil
[start, stop].tap { |a| a << raw_step if raw_step }
)
range = Range.new(start.to_i, stop.to_i)
step = raw_step.to_i
step = 1 if step == 0

range.step(step).to_a
end

def is_range?(component)
component.include?('-')
end

# Protect against Ruby's String#to_i returning 0 for arbitrary strings
def numbers_valid?(numbers)
numbers.all? { |str| /^[0-9]+$/ =~ str }
end
end
end
end

0 comments on commit 8b345e7

Please sign in to comment.