I am writing a script to interact with a GitHub environment. For certain use cases, I need to limit my script's scope to a list of users, which I store in a newline-delimited file. I want to pass the user list's filename as an argument to the script and store the string of the filename in a variable, then use the variable to open/process the user list file by its filename later on in the script.

My issue is strictly with correctly inputting and storing the filename. Let's say the user list is in a file called "user-list" and it contains the following text:

user1
user2
user3

I want to store the filename ("user-list") in a variable but what I am actually storing is a list of users ([ "user1", "user2", "user3" ]).

I feel like I am missing something very obvious here, but I have been unable to find anything pertinent in the documentation for OptionParser or any of the other Ruby documentation. I am also a fairly new Ruby user and am working with an existing codebase, so if there is a better way to do this, I am not already aware of it.

Here's a snippet of the code I am working with:

# Initialize options OpenStruct
options = OpenStruct.new

...

# Parse arguments
option_parser = OptionParser.new do |opts|

...

    opts.on("-u", "--user-file USER_FILE", String,
        "Read users from a file. File should be newline separated.") do |user_file|
        # FIXME: This doesn't work
        # Check if the file exists
        #unless File.exist?(user_file)
        #    puts "File not found: #{user_file}"
        #    exit
        #end
        options.user_file = user_file
        
        # FIXME: Testing what was stored
        puts options.user_file
    end

...

option_parser.parse!(ARGV)

Here is what I pass into the script:

./my_script -u user-file

The file "user-file" exists with contents:

user1
user2
user3

I am trying to store the string "user-file" in the variable user_file , but what I am actually storing is the list [ "user1", "user2", "user3" ].

2

There are 2 answers

5
rna On

This is the same code you mentioned, which worked for me.

require 'optparse'
require 'ostruct'

options = OpenStruct.new

option_parser = OptionParser.new do |opts|
  opts.on('-u', '--user-file USER_FILE', String,
          'Read users from a file. File should be newline separated.') do |user_file|
    options.user_file = user_file
    puts options.user_file
  end
end
option_parser.parse!(ARGV)
0
DoctorMarmalade On

After more digging, I found that my issue was unrelated to OptionParser or anything to do with Ruby. The problem was actually with the file being evaluated by a wrapper script.