Ruby script starts with a specific line or method

Let's say I have a script:

!#usr/bin/ruby

# step 1
puts "That first"
# some code

#step 2
puts "That second"
# some code

Is there a way to pass ARGV to a script that starts execution from a specific line (or step, or class, or something else)? For example, execution $ ruby script.rb -s 2will begin with the second step.

I was thinking about parsing the argument with if\else, but in this case, the script will become much more complicated, not DRY at all.

Any ideas?

+4
source share
3 answers

, max , . , , goto Ruby. , BASIC? , .

Ruby , ,

def print_a
  puts "a"
end

, , "puts a"

print_a

, - .

:

if condition
  require ./mycode_only_to be_executed_in_this_case.rb'
end

, .

op

, , , , . . https://en.wikipedia.org/wiki/Don 't_repeat_yourself DRY

, , , , : . , DRY.

require 'watir'

def goto_site site
  a = Watir::Browser.new :chrome
  a.goto site
  # a lot of code down here
  a.close
end

goto_site 'site.com'
+3

run_from_line.rb, : , . -1.

#/usr/bin/env ruby

path = ARGV.shift
program_text = File.readlines(path)
start_line = ARGV.shift.to_i;
end_line = ARGV.shift || '-1'
end_line = end_line.to_i

selected_code = program_text[start_line..end_line].join
eval selected_code

script test.rb:

puts "line 0"
puts "line 1"
puts "line 2"

:

> ruby run_from_line.rb test.rb 1
line 1
line 2

> ruby run_from_line.rb test.rb 1 1
line 1

script, chmod a+x run_from_line.rb, sudo mv run_from_line.rb /usr/local/sbin

+4

, GOTO.

, :

'define_steps.rb':

# define_steps.rb
#####################################################
@steps = []

def step(i, &block)
  @steps[i] = block
end

def launch_steps!(min = 0, max = @steps.size - 1)
  @steps[min..max].each.with_index(min) do |block, i|
    if block
      puts "Launching step #{i}"
      block.call
    end
  end
end
#####################################################

step 1 do
  puts 'Step 1 with lots of code'
end

step 2 do
  puts 'Step 2 with lots of code'
end

step 3 do
  puts 'Step 3 with lots of code'
end

step 4 do
  puts 'Step 4 with lots of code'
end

Run them separately with launch_steps.rb:

# launch_steps.rb
require_relative 'define_steps'

launch_steps!
puts "-----------------"
launch_steps!(2,3)

It outputs:

Launching step 1
Step 1 with lots of code
Launching step 2
Step 2 with lots of code
Launching step 3
Step 3 with lots of code
Launching step 4
Step 4 with lots of code
-----------------
Launching step 2
Step 2 with lots of code
Launching step 3
Step 3 with lots of code

launch_steps!without parameters, each specific step is launch_steps!(min,max)performed , performs each step between minand max, launch_steps!(min)performs a step, minand every step after.

+4
source

Source: https://habr.com/ru/post/1662736/


All Articles