OptionParser
OptionParser
is a class for command-line option analysis. It is much more advanced, yet also easier to use, than GetoptLong
, and is a more Ruby-oriented solution.
The argument specification and the code to handle it are written in the same place.
It can output an option summary; you don’t need to maintain this string separately.
Optional and mandatory arguments are specified very gracefully.
Arguments can be automatically converted to a specified class.
Arguments can be restricted to a certain set.
All of these features are demonstrated in the examples below. See make_switch
for full documentation.
require 'optparse' options = {} OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| options[:verbose] = v end end.parse! p options p ARGV
OptionParser
can be used to automatically generate help for the commands you write:
require 'optparse' Options = Struct.new(:name) class Parser def self.parse(options) args = Options.new("world") opt_parser = OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("-nNAME", "--name=NAME", "Name to say hello to") do |n| args.name = n end opts.on("-h", "--help", "Prints this help") do puts opts exit end end opt_parser.parse!(options) return args end end options = Parser.parse %w[--help] #=> # Usage: example.rb [options] # -n, --name=NAME Name to say hello to # -h, --help Prints this help
For options that require an argument, option specification strings may include an option name in all caps. If an option is used without the required argument, an exception will be raised.
require 'optparse' options = {} OptionParser.new do |parser| parser.on("-r", "--require LIBRARY", "Require the LIBRARY before executing your script") do |lib| puts "You required #{lib}!" end end.parse!
Used:
$ ruby optparse-test.rb -r optparse-test.rb:9:in `<main>': missing argument: -r (OptionParser::MissingArgument) $ ruby optparse-test.rb -r my-library You required my-library!
OptionParser
supports the ability to coerce command line arguments into objects for us.
OptionParser
comes with a few ready-to-use kinds of type coercion. They are:
Date
– Anything accepted by Date.parse
DateTime
– Anything accepted by DateTime.parse
Time
– Anything accepted by Time.httpdate
or Time.parse
URI
– Anything accepted by URI.parse
Shellwords
– Anything accepted by Shellwords.shellwords
String
– Any non-empty string
Integer
– Any integer. Will convert octal. (e.g. 124, -3, 040)
Float
– Any float. (e.g. 10, 3.14, -100E+13)
Numeric
– Any integer, float, or rational (1, 3.4, 1/3)
DecimalInteger
– Like Integer
, but no octal format.
OctalInteger
– Like Integer
, but no decimal format.
DecimalNumeric
– Decimal integer or float.
TrueClass
– Accepts ‘+, yes, true, -, no, false’ and defaults as true
FalseClass
– Same as TrueClass
, but defaults to false
Array
– Strings separated by ‘,’ (e.g. 1,2,3)
Regexp
– Regular expressions. Also includes options.
We can also add our own coercions, which we will cover below.
As an example, the built-in Time
conversion is used. The other built-in conversions behave in the same way. OptionParser
will attempt to parse the argument as a Time
. If it succeeds, that time will be passed to the handler block. Otherwise, an exception will be raised.
require 'optparse' require 'optparse/time' OptionParser.new do |parser| parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| p time end end.parse!
Used:
$ ruby optparse-test.rb -t nonsense ... invalid argument: -t nonsense (OptionParser::InvalidArgument) $ ruby optparse-test.rb -t 10-11-12 2010-11-12 00:00:00 -0500 $ ruby optparse-test.rb -t 9:30 2014-08-13 09:30:00 -0400
The accept
method on OptionParser
may be used to create converters. It specifies which conversion block to call whenever a class is specified. The example below uses it to fetch a User
object before the on
handler receives it.
require 'optparse' User = Struct.new(:id, :name) def find_user id not_found = ->{ raise "No User Found for id #{id}" } [ User.new(1, "Sam"), User.new(2, "Gandalf") ].find(not_found) do |u| u.id == id end end op = OptionParser.new op.accept(User) do |user_id| find_user user_id.to_i end op.on("--user ID", User) do |user| puts user end op.parse!
Used:
$ ruby optparse-test.rb --user 1 #<struct User id=1, name="Sam"> $ ruby optparse-test.rb --user 2 #<struct User id=2, name="Gandalf"> $ ruby optparse-test.rb --user 3 optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError)
Hash
The into
option of order
, parse
and so on methods stores command line options into a Hash
.
require 'optparse' params = {} OptionParser.new do |opts| opts.on('-a') opts.on('-b NUM', Integer) opts.on('-v', '--verbose') end.parse!(into: params) p params
Used:
$ ruby optparse-test.rb -a {:a=>true} $ ruby optparse-test.rb -a -v {:a=>true, :verbose=>true} $ ruby optparse-test.rb -a -b 100 {:a=>true, :b=>100}
The following example is a complete Ruby program. You can run it and see the effect of specifying various options. This is probably the best way to learn the features of optparse
.
require 'optparse' require 'optparse/time' require 'ostruct' require 'pp' class OptparseExample Version = '1.0.0' CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary] CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } class ScriptOptions attr_accessor :library, :inplace, :encoding, :transfer_type, :verbose, :extension, :delay, :time, :record_separator, :list def initialize self.library = [] self.inplace = false self.encoding = "utf8" self.transfer_type = :auto self.verbose = false end def define_options(parser) parser.banner = "Usage: example.rb [options]" parser.separator "" parser.separator "Specific options:" # add additional options perform_inplace_option(parser) delay_execution_option(parser) execute_at_time_option(parser) specify_record_separator_option(parser) list_example_option(parser) specify_encoding_option(parser) optional_option_argument_with_keyword_completion_option(parser) boolean_verbose_option(parser) parser.separator "" parser.separator "Common options:" # No argument, shows at tail. This will print an options summary. # Try it and see! parser.on_tail("-h", "--help", "Show this message") do puts parser exit end # Another typical switch to print the version. parser.on_tail("--version", "Show version") do puts Version exit end end def perform_inplace_option(parser) # Specifies an optional option argument parser.on("-i", "--inplace [EXTENSION]", "Edit ARGV files in place", "(make backup if EXTENSION supplied)") do |ext| self.inplace = true self.extension = ext || '' self.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot. end end def delay_execution_option(parser) # Cast 'delay' argument to a Float. parser.on("--delay N", Float, "Delay N seconds before executing") do |n| self.delay = n end end def execute_at_time_option(parser) # Cast 'time' argument to a Time object. parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| self.time = time end end def specify_record_separator_option(parser) # Cast to octal integer. parser.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger, "Specify record separator (default \\0)") do |rs| self.record_separator = rs end end def list_example_option(parser) # List of arguments. parser.on("--list x,y,z", Array, "Example 'list' of arguments") do |list| self.list = list end end def specify_encoding_option(parser) # Keyword completion. We are specifying a specific set of arguments (CODES # and CODE_ALIASES - notice the latter is a Hash), and the user may provide # the shortest unambiguous text. code_list = (CODE_ALIASES.keys + CODES).join(', ') parser.on("--code CODE", CODES, CODE_ALIASES, "Select encoding", "(#{code_list})") do |encoding| self.encoding = encoding end end def optional_option_argument_with_keyword_completion_option(parser) # Optional '--type' option argument with keyword completion. parser.on("--type [TYPE]", [:text, :binary, :auto], "Select transfer type (text, binary, auto)") do |t| self.transfer_type = t end end def boolean_verbose_option(parser) # Boolean switch. parser.on("-v", "--[no-]verbose", "Run verbosely") do |v| self.verbose = v end end end # # Return a structure describing the options. # def parse(args) # The options specified on the command line will be collected in # *options*. @options = ScriptOptions.new @args = OptionParser.new do |parser| @options.define_options(parser) parser.parse!(args) end @options end attr_reader :parser, :options end # class OptparseExample example = OptparseExample.new options = example.parse(ARGV) pp options # example.options pp ARGV
Completion
For modern shells (e.g. bash, zsh, etc.), you can use shell completion for command line options.
The above examples should be enough to learn how to use this class. If you have any questions, file a ticket at bugs.ruby-lang.org.
Raised in case of a stack overflow.
def me_myself_and_i me_myself_and_i end me_myself_and_i
raises the exception:
SystemStackError: stack level too deep
Raised when an invalid operation is attempted on a thread.
For example, when no other thread has been started:
Thread.stop
This will raises the following exception:
ThreadError: stopping only thread note: use sleep to stop forever
Raised when throw
is called with a tag which does not have corresponding catch
block.
throw "foo", "bar"
raises the exception:
UncaughtThrowError: uncaught throw "foo"
RubyGems adds the gem
method to allow activation of specific gem versions and overrides the require
method on Kernel
to make gems appear as if they live on the $LOAD_PATH
. See the documentation of these methods for further detail.
The Kernel
module is included by class Object
, so its methods are available in every Ruby object.
The Kernel
instance methods are documented in class Object
while the module methods are documented here. These methods are called without a receiver and thus can be called in functional form:
sprintf "%.1f", 1.234 #=> "1.2"
fronzen-string-literal: true
The Enumerable
mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection. If Enumerable#max
, min
, or sort
is used, the objects in the collection must also implement a meaningful <=>
operator, as these methods rely on an ordering between members of the collection.
Ruby exception objects are subclasses of Exception
. However, operating systems typically report errors using plain integers. Module
Errno
is created dynamically to map these operating system errors to Ruby classes, with each error number generating its own subclass of SystemCallError
. As the subclass is created in module Errno
, its name will start Errno::
.
The names of the Errno::
classes depend on the environment in which Ruby runs. On a typical Unix or Windows platform, there are Errno
classes such as Errno::EACCES, Errno::EAGAIN, Errno::EINTR, and so on.
The integer operating system error number corresponding to a particular error is available as the class constant Errno::
error::Errno
.
Errno::EACCES::Errno #=> 13 Errno::EAGAIN::Errno #=> 11 Errno::EINTR::Errno #=> 4
The full list of operating system errors on your particular platform are available as the constants of Errno
.
Errno.constants #=> :E2BIG, :EACCES, :EADDRINUSE, :EADDRNOTAVAIL, ...
System call error module used by webrick for cross platform compatibility.
EPROTO
protocol error
ECONNRESET
remote host reset the connection request
ECONNABORTED
Client sent TCP reset (RST) before server has accepted the connection requested by client.
This module provides a framework for message digest libraries.
You may want to look at OpenSSL::Digest
as it supports more algorithms.
A cryptographic hash function is a procedure that takes data and returns a fixed bit string: the hash value, also known as digest. Hash
functions are also called one-way functions, it is easy to compute a digest from a message, but it is infeasible to generate a message from a digest.
require 'digest' # Compute a complete digest Digest::SHA256.digest 'message' #=> "\xABS\n\x13\xE4Y..." sha256 = Digest::SHA256.new sha256.digest 'message' #=> "\xABS\n\x13\xE4Y..." # Other encoding formats Digest::SHA256.hexdigest 'message' #=> "ab530a13e459..." Digest::SHA256.base64digest 'message' #=> "q1MKE+RZFJgr..." # Compute digest by chunks md5 = Digest::MD5.new md5.update 'message1' md5 << 'message2' # << is an alias for update md5.hexdigest #=> "94af09c09bb9..." # Compute digest for a file sha256 = Digest::SHA256.file 'testfile' sha256.hexdigest
Additionally digests can be encoded in “bubble babble” format as a sequence of consonants and vowels which is more recognizable and comparable than a hexadecimal digest.
require 'digest/bubblebabble' Digest::SHA256.bubblebabble 'message' #=> "xopoh-fedac-fenyh-..."
See the bubble babble specification at web.mit.edu/kenta/www/one/bubblebabble/spec/jrtrjwzi/draft-huima-01.txt.
Digest
algorithms Different digest algorithms (or hash functions) are available:
MD5
See RFC 1321 The MD5
Message-Digest Algorithm
As Digest::RMD160
. See homes.esat.kuleuven.be/~bosselae/ripemd160.html.
SHA1
See FIPS 180 Secure Hash
Standard.
See FIPS 180 Secure Hash
Standard which defines the following algorithms:
SHA512
SHA384
SHA256
The latest versions of the FIPS publications can be found here: csrc.nist.gov/publications/PubsFIPS.html.
RubyGems is the Ruby standard for publishing and managing third party libraries.
For user documentation, see:
gem help
and gem help [command]
For gem developer documentation see:
Gem::Version
for version dependency notes
Further RubyGems documentation can be found at:
RubyGems API (also available from gem server
)
As of RubyGems 1.3.2, RubyGems will load plugins installed in gems or $LOAD_PATH. Plugins must be named ‘rubygems_plugin’ (.rb, .so, etc) and placed at the root of your gem’s require_path. Plugins are discovered via Gem::find_files
and then loaded.
For an example plugin, see the Graph gem which adds a ‘gem graph` command.
RubyGems defaults are stored in lib/rubygems/defaults.rb. If you’re packaging RubyGems or implementing Ruby you can change RubyGems’ defaults.
For RubyGems packagers, provide lib/rubygems/defaults/operating_system.rb and override any defaults from lib/rubygems/defaults.rb.
For Ruby implementers, provide lib/rubygems/defaults/#{RUBY_ENGINE}.rb and override any defaults from lib/rubygems/defaults.rb.
If you need RubyGems to perform extra work on install or uninstall, your defaults override file can set pre/post install and uninstall hooks. See Gem::pre_install
, Gem::pre_uninstall
, Gem::post_install
, Gem::post_uninstall
.
You can submit bugs to the RubyGems bug tracker on GitHub
RubyGems is currently maintained by Eric Hodel.
RubyGems was originally developed at RubyConf 2003 by:
Rich Kilmer – rich(at)infoether.com
Chad Fowler – chad(at)chadfowler.com
David Black – dblack(at)wobblini.net
Paul Brannan – paul(at)atdesk.com
Jim Weirich – jim(at)weirichhouse.org
Contributors:
Gavin Sinclair – gsinclair(at)soyabean.com.au
George Marrows – george.marrows(at)ntlworld.com
Dick Davies – rasputnik(at)hellooperator.net
Mauricio Fernandez – batsman.geo(at)yahoo.com
Simon Strandgaard – neoneye(at)adslhome.dk
Dave Glasser – glasser(at)mit.edu
Paul Duncan – pabs(at)pablotron.org
Ville Aine – vaine(at)cs.helsinki.fi
Eric Hodel – drbrain(at)segment7.net
Daniel Berger – djberg96(at)gmail.com
Phil Hagelberg – technomancy(at)gmail.com
Ryan Davis – ryand-ruby(at)zenspider.com
Evan Phoenix – evan(at)fallingsnow.net
Steve Klabnik – steve(at)steveklabnik.com
(If your name is missing, PLEASE let us know!)
See LICENSE.txt for permissions.
Thanks!
-The RubyGems Team
The Observer pattern (also known as publish/subscribe) provides a simple mechanism for one object to inform a set of interested third-party objects when its state changes.
The notifying class mixes in the Observable
module, which provides the methods for managing the associated observer objects.
The observable object must:
assert that it has #changed
call #notify_observers
An observer subscribes to updates using Observable#add_observer
, which also specifies the method called via notify_observers
. The default method for notify_observers
is update.
The following example demonstrates this nicely. A Ticker
, when run, continually receives the stock Price
for its @symbol
. A Warner
is a general observer of the price, and two warners are demonstrated, a WarnLow
and a WarnHigh
, which print a warning if the price is below or above their set limits, respectively.
The update
callback allows the warners to run without being explicitly called. The system is set up with the Ticker
and several observers, and the observers do their duty without the top-level code having to interfere.
Note that the contract between publisher and subscriber (observable and observer) is not declared or enforced. The Ticker
publishes a time and a price, and the warners receive that. But if you don’t ensure that your contracts are correct, nothing else can warn you.
require "observer" class Ticker ### Periodically fetch a stock price. include Observable def initialize(symbol) @symbol = symbol end def run last_price = nil loop do price = Price.fetch(@symbol) print "Current price: #{price}\n" if price != last_price changed # notify observers last_price = price notify_observers(Time.now, price) end sleep 1 end end end class Price ### A mock class to fetch a stock price (60 - 140). def self.fetch(symbol) 60 + rand(80) end end class Warner ### An abstract observer of Ticker objects. def initialize(ticker, limit) @limit = limit ticker.add_observer(self) end end class WarnLow < Warner def update(time, price) # callback for observer if price < @limit print "--- #{time.to_s}: Price below #@limit: #{price}\n" end end end class WarnHigh < Warner def update(time, price) # callback for observer if price > @limit print "+++ #{time.to_s}: Price above #@limit: #{price}\n" end end end ticker = Ticker.new("MSFT") WarnLow.new(ticker, 80) WarnHigh.new(ticker, 120) ticker.run
Produces:
Current price: 83 Current price: 75 --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75 Current price: 90 Current price: 134 +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134 Current price: 134 Current price: 112 Current price: 79 --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79
This library is an interface to secure random number generators which are suitable for generating session keys in HTTP cookies, etc.
You can use this library in your application by requiring it:
require 'securerandom'
It supports the following secure random number generators:
openssl
/dev/urandom
Win32
SecureRandom
is extended by the Random::Formatter
module which defines the following methods:
alphanumeric
base64
choose
hex
rand
random_bytes
random_number
urlsafe_base64
uuid
These methods are usable as class methods of SecureRandom
such as ‘SecureRandom.hex`.
Generate random hexadecimal strings:
require 'securerandom' SecureRandom.hex(10) #=> "52750b30ffbc7de3b362" SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559" SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
Generate random base64 strings:
SecureRandom.base64(10) #=> "EcmTPZwWRAozdA==" SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg==" SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
Generate random binary strings:
SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301" SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
Generate alphanumeric strings:
SecureRandom.alphanumeric(10) #=> "S8baxMJnPl" SecureRandom.alphanumeric(10) #=> "aOxAg8BAJe"
Generate UUIDs:
SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594" SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
This exception is raised if a parser error occurs.
This exception is raised if the nesting of parsed data structures is too deep.
This exception is raised if a generator or unparser error occurs.
General error for openssl library configuration files. Including formatting, parsing errors, etc.
Subclass of Zlib::Error
When zlib returns a Z_VERSION_ERROR, usually if the zlib library version is incompatible with the version assumed by the caller.
Subclass of Zlib::Error
. This error is raised when the zlib stream is currently in progress.
For example:
inflater = Zlib::Inflate.new inflater.inflate(compressed) do inflater.inflate(compressed) # Raises Zlib::InProgressError end
Note: Don’t use this class directly. This is an internal class.