HTTPAuth
provides both basic and digest authentication.
To enable authentication for requests in WEBrick
you will need a user database and an authenticator. To start, here’s an Htpasswd
database for use with a DigestAuth
authenticator:
config = { :Realm => 'DigestAuth example realm' } htpasswd = WEBrick::HTTPAuth::Htpasswd.new 'my_password_file' htpasswd.auth_type = WEBrick::HTTPAuth::DigestAuth htpasswd.set_passwd config[:Realm], 'username', 'password' htpasswd.flush
The :Realm
is used to provide different access to different groups across several resources on a server. Typically you’ll need only one realm for a server.
This database can be used to create an authenticator:
config[:UserDB] = htpasswd digest_auth = WEBrick::HTTPAuth::DigestAuth.new config
To authenticate a request call authenticate with a request and response object in a servlet:
def do_GET req, res @authenticator.authenticate req, res end
For digest authentication the authenticator must not be created every request, it must be passed in as an option via WEBrick::HTTPServer#mount
.
Numeric
is the class from which all higher-level numeric classes should inherit.
Numeric
allows instantiation of heap-allocated objects. Other core numeric classes such as Integer
are implemented as immediates, which means that each Integer
is a single immutable object which is always passed by value.
a = 1 puts 1.object_id == a.object_id #=> true
There can only ever be one instance of the integer 1
, for example. Ruby ensures this by preventing instantiation and duplication.
Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class 1.dup #=> TypeError: can't dup Fixnum
For this reason, Numeric
should be used when defining other numeric classes.
Classes which inherit from Numeric
must implement coerce
, which returns a two-member Array containing an object that has been coerced into an instance of the new class and self
(see coerce
).
Inheriting classes should also implement arithmetic operator methods (+
, -
, *
and /
) and the <=>
operator (see Comparable
). These methods may rely on coerce
to ensure interoperability with instances of other numeric classes.
class Tally < Numeric def initialize(string) @string = string end def to_s @string end def to_i @string.size end def coerce(other) [self.class.new('|' * other.to_i), self] end def <=>(other) to_i <=> other.to_i end def +(other) self.class.new('|' * (to_i + other.to_i)) end def -(other) self.class.new('|' * (to_i - other.to_i)) end def *(other) self.class.new('|' * (to_i * other.to_i)) end def /(other) self.class.new('|' * (to_i / other.to_i)) end end tally = Tally.new('||') puts tally * 2 #=> "||||" puts tally > 1 #=> true
BigDecimal
extends the native Float
class to provide the to_d
method.
When you require BigDecimal
in your application, this method will be available on Float
objects.
Float
objects represent inexact real numbers using the native architecture’s double-precision floating point representation.
Floating point has a different arithmetic and is an inexact number. So you should know its esoteric system. see following:
Continuation
objects are generated by Kernel#callcc
, after having +require+d continuation. They hold a return address and execution context, allowing a nonlocal return to the end of the callcc
block from anywhere within a program. Continuations are somewhat analogous to a structured version of C’s setjmp/longjmp
(although they contain more state, so you might consider them closer to threads).
For instance:
require "continuation" arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ] callcc{|cc| $cc = cc} puts(message = arr.shift) $cc.call unless message =~ /Max/
produces:
Freddie Herbie Ron Max
Also you can call callcc in other methods:
require "continuation" def g arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ] cc = callcc { |cc| cc } puts arr.shift return cc, arr.size end def f c, size = g c.call(c) if size > 1 end f
This (somewhat contrived) example allows the inner loop to abandon processing early:
require "continuation" callcc {|cont| for i in 0..4 print "\n#{i}: " for j in i*5...(i+1)*5 cont.call() if j == 17 printf "%3d", j end end } puts
produces:
0: 0 1 2 3 4 1: 5 6 7 8 9 2: 10 11 12 13 14 3: 15 16
Raised to stop the iteration, in particular by Enumerator#next
. It is rescued by Kernel#loop
.
loop do puts "Hello" raise StopIteration puts "World" end puts "Done!"
produces:
Hello Done!
Raised by exit
to initiate the termination of the script.
fatal is an Exception
that is raised when ruby has encountered a fatal error and must exit. You are not able to rescue fatal.
Raised when a signal is received.
begin Process.kill('HUP',Process.pid) sleep # wait for receiver to handle signal sent by Process.kill rescue SignalException => e puts "received Exception #{e}" end
produces:
received Exception SIGHUP
Raised when the arguments are wrong and there isn’t a more specific Exception
class.
Ex: passing the wrong number of arguments
[1, 2, 3].first(4, 5)
raises the exception:
ArgumentError: wrong number of arguments (given 2, expected 1)
Ex: passing an argument that is not acceptable:
[1, 2, 3].first(-4)
raises the exception:
ArgumentError: negative array size
Raised when a feature is not implemented on the current platform. For example, methods depending on the fsync
or fork
system calls may raise this exception if the underlying operating system or Ruby runtime does not support them.
Note that if fork
raises a NotImplementedError
, then respond_to?(:fork)
returns false
.
A generic error class raised when an invalid operation is attempted.
[1, 2, 3].freeze << 4
raises the exception:
RuntimeError: can't modify frozen Array
Kernel.raise
will raise a RuntimeError
if no Exception
class is specified.
raise "ouch"
raises the exception:
RuntimeError: ouch
Raised when memory allocation fails.
date and datetime class - Tadayoshi Funaba 1998-2011
‘date’ provides two classes Date
and DateTime
.
Some terms and definitions are based on ISO 8601 and JIS X 0301.
The calendar date is a particular day of a calendar year, identified by its ordinal number within a calendar month within that year.
In those classes, this is so-called “civil”.
The ordinal date is a particular day of a calendar year identified by its ordinal number within the year.
In those classes, this is so-called “ordinal”.
The week date is a date identified by calendar week and day numbers.
The calendar week is a seven day period within a calendar year, starting on a Monday and identified by its ordinal number within the year; the first calendar week of the year is the one that includes the first Thursday of that year. In the Gregorian calendar, this is equivalent to the week which includes January 4.
In those classes, this so-called “commercial”.
The Julian day number is in elapsed days since noon (Greenwich mean time) on January 1, 4713 BCE (in the Julian calendar).
In this document, the astronomical Julian day number is same as the original Julian day number. And the chronological Julian day number is a variation of the Julian day number. Its days begin at midnight on local time.
In this document, when the term “Julian day number” simply appears, it just refers to “chronological Julian day number”, not the original.
In those classes, those are so-called “ajd” and “jd”.
The modified Julian day number is in elapsed days since midnight (Coordinated universal time) on November 17, 1858 CE (in the Gregorian calendar).
In this document, the astronomical modified Julian day number is same as the original modified Julian day number. And the chronological modified Julian day number is a variation of the modified Julian day number. Its days begin at midnight on local time.
In this document, when the term “modified Julian day number” simply appears, it just refers to “chronological modified Julian day number”, not the original.
In those classes, this is so-called “mjd”.
Date
A subclass of Object
that includes Comparable
module and easily handles date.
Date
object is created with Date::new
, Date::jd
, Date::ordinal
, Date::commercial
, Date::parse
, Date::strptime
, Date::today
, Time#to_date
or etc.
require 'date' Date.new(2001,2,3) #=> #<Date: 2001-02-03 ...> Date.jd(2451944) #=> #<Date: 2001-02-03 ...> Date.ordinal(2001,34) #=> #<Date: 2001-02-03 ...> Date.commercial(2001,5,6) #=> #<Date: 2001-02-03 ...> Date.parse('2001-02-03') #=> #<Date: 2001-02-03 ...> Date.strptime('03-02-2001', '%d-%m-%Y') #=> #<Date: 2001-02-03 ...> Time.new(2001,2,3).to_date #=> #<Date: 2001-02-03 ...>
All date objects are immutable; hence cannot modify themselves.
The concept of this date object can be represented as a tuple of the day count, the offset and the day of calendar reform.
The day count denotes the absolute position of a temporal dimension. The offset is relative adjustment, which determines decoded local time with the day count. The day of calendar reform denotes the start day of the new style. The old style of the West is the Julian calendar which was adopted by Caesar. The new style is the Gregorian calendar, which is the current civil calendar of many countries.
The day count is virtually the astronomical Julian day number. The offset in this class is usually zero, and cannot be specified directly.
An optional argument the day of calendar reform (start) as a Julian day number, which should be 2298874 to 2426355 or -/+oo. The default value is Date::ITALY
(2299161=1582-10-15). See also sample/cal.rb.
$ ruby sample/cal.rb -c it 10 1582 October 1582 S M Tu W Th F S 1 2 3 4 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 $ ruby sample/cal.rb -c gb 9 1752 September 1752 S M Tu W Th F S 1 2 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Date
object has various methods. See each reference.
d = Date.parse('3rd Feb 2001') #=> #<Date: 2001-02-03 ...> d.year #=> 2001 d.mon #=> 2 d.mday #=> 3 d.wday #=> 6 d += 1 #=> #<Date: 2001-02-04 ...> d.strftime('%a %d %b %Y') #=> "Sun 04 Feb 2001"
When ‘time’ is required, Time
is extended with additional methods for parsing and converting Times.
This library extends the Time
class with the following conversions between date strings and Time
objects:
date-time defined by RFC 2822
HTTP-date defined by RFC 2616
various formats handled by Date._parse
custom formats handled by Date._strptime
All examples assume you have loaded Time
with:
require 'time'
All of these examples were done using the EST timezone which is GMT-5.
t = Time.now t.iso8601 # => "2011-10-05T22:26:12-04:00" t.rfc2822 # => "Wed, 05 Oct 2011 22:26:12 -0400" t.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"
Time.parse
parse takes a string representation of a Time
and attempts to parse it using a heuristic.
Time.parse("2010-10-31") #=> 2010-10-31 00:00:00 -0500
Any missing pieces of the date are inferred based on the current date.
# assuming the current date is "2011-10-31" Time.parse("12:00") #=> 2011-10-31 12:00:00 -0500
We can change the date used to infer our missing elements by passing a second object that responds to mon
, day
and year
, such as Date
, Time
or DateTime
. We can also use our own object.
class MyDate attr_reader :mon, :day, :year def initialize(mon, day, year) @mon, @day, @year = mon, day, year end end d = Date.parse("2010-10-28") t = Time.parse("2010-10-29") dt = DateTime.parse("2010-10-30") md = MyDate.new(10,31,2010) Time.parse("12:00", d) #=> 2010-10-28 12:00:00 -0500 Time.parse("12:00", t) #=> 2010-10-29 12:00:00 -0500 Time.parse("12:00", dt) #=> 2010-10-30 12:00:00 -0500 Time.parse("12:00", md) #=> 2010-10-31 12:00:00 -0500
parse also accepts an optional block. You can use this block to specify how to handle the year component of the date. This is specifically designed for handling two digit years. For example, if you wanted to treat all two digit years prior to 70 as the year 2000+ you could write this:
Time.parse("01-10-31") {|year| year + (year < 70 ? 2000 : 1900)} #=> 2001-10-31 00:00:00 -0500 Time.parse("70-10-31") {|year| year + (year < 70 ? 2000 : 1900)} #=> 1970-10-31 00:00:00 -0500
Time.strptime
strptime works similar to parse
except that instead of using a heuristic to detect the format of the input string, you provide a second argument that describes the format of the string. For example:
Time.strptime("2000-10-31", "%Y-%m-%d") #=> 2000-10-31 00:00:00 -0500
Time
is an abstraction of dates and times. Time
is stored internally as the number of seconds with fraction since the Epoch, January 1, 1970 00:00 UTC. Also see the library module Date
. The Time
class treats GMT (Greenwich Mean Time
) and UTC (Coordinated Universal Time
) as equivalent. GMT is the older way of referring to these baseline times but persists in the names of calls on POSIX systems.
All times may have fraction. Be aware of this fact when comparing times with each other – times that are apparently equal when displayed may be different when compared.
Since Ruby 1.9.2, Time
implementation uses a signed 63 bit integer, Bignum
or Rational
. The integer is a number of nanoseconds since the Epoch which can represent 1823-11-12 to 2116-02-20. When Bignum
or Rational
is used (before 1823, after 2116, under nanosecond), Time
works slower as when integer is used.
All of these examples were done using the EST timezone which is GMT-5.
Time
instance You can create a new instance of Time
with Time::new
. This will use the current system time. Time::now
is an alias for this. You can also pass parts of the time to Time::new
such as year, month, minute, etc. When you want to construct a time this way you must pass at least a year. If you pass the year with nothing else time will default to January 1 of that year at 00:00:00 with the current system timezone. Here are some examples:
Time.new(2002) #=> 2002-01-01 00:00:00 -0500 Time.new(2002, 10) #=> 2002-10-01 00:00:00 -0500 Time.new(2002, 10, 31) #=> 2002-10-31 00:00:00 -0500 Time.new(2002, 10, 31, 2, 2, 2, "+02:00") #=> 2002-10-31 02:02:02 +0200
You can also use gm
, local and utc
to infer GMT, local and UTC timezones instead of using the current system setting.
You can also create a new time using Time::at
which takes the number of seconds (or fraction of seconds) since the Unix Epoch.
Time.at(628232400) #=> 1989-11-28 00:00:00 -0500
Time
Once you have an instance of Time
there is a multitude of things you can do with it. Below are some examples. For all of the following examples, we will work on the assumption that you have done the following:
t = Time.new(1993, 02, 24, 12, 0, 0, "+09:00")
Was that a monday?
t.monday? #=> false
What year was that again?
t.year #=> 1993
Was is daylight savings at the time?
t.dst? #=> false
What’s the day a year later?
t + (60*60*24*365) #=> 1994-02-24 12:00:00 +0900
How many seconds was that since the Unix Epoch?
t.to_i #=> 730522800
You can also do standard functions like compare two times.
t1 = Time.new(2010) t2 = Time.new(2011) t1 == t2 #=> false t1 == t1 #=> true t1 < t2 #=> true t1 > t2 #=> false Time.new(2010,10,31).between?(t1, t2) #=> true
Raised when OLE processing failed.
EX:
obj = WIN32OLE.new("NonExistProgID")
raises the exception:
WIN32OLERuntimeError: unknown OLE server: `NonExistProgID' HRESULT error code:0x800401f3 Invalid class string
This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator
. Pass an object to the constructor and all methods supported by the object will be delegated. This object can be changed later.
Going a step further, the top level DelegateClass method allows you to easily setup delegation through class inheritance. This is considerably more flexible and thus probably the most common use for this library.
Finally, if you need full control over the delegation scheme, you can inherit from the abstract class Delegator
and customize as needed. (If you find yourself needing this control, have a look at Forwardable
which is also in the standard library. It may suit your needs better.)
SimpleDelegator’s implementation serves as a nice example of the use of Delegator:
class SimpleDelegator < Delegator def __getobj__ @delegate_sd_obj # return object we are delegating to, required end def __setobj__(obj) @delegate_sd_obj = obj # change delegation object, # a feature we're providing end end
Be advised, RDoc
will not detect delegated methods.
A concrete implementation of Delegator
, this class provides the means to delegate all supported method calls to the object passed into the constructor and even to change the object being delegated to at a later time with __setobj__
.
class User def born_on Date.new(1989, 9, 10) end end class UserDecorator < SimpleDelegator def birth_year born_on.year end end decorated_user = UserDecorator.new(User.new) decorated_user.birth_year #=> 1989 decorated_user.__getobj__ #=> #<User: ...>
A SimpleDelegator
instance can take advantage of the fact that SimpleDelegator
is a subclass of Delegator
to call super
to have methods called on the object being delegated to.
class SuperArray < SimpleDelegator def [](*args) super + 1 end end SuperArray.new([1])[0] #=> 2
Here’s a simple example that takes advantage of the fact that SimpleDelegator’s delegation object can be changed at any time.
class Stats def initialize @source = SimpleDelegator.new([]) end def stats(records) @source.__setobj__(records) "Elements: #{@source.size}\n" + " Non-Nil: #{@source.compact.size}\n" + " Unique: #{@source.uniq.size}\n" end end s = Stats.new puts s.stats(%w{James Edward Gray II}) puts puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
Prints:
Elements: 4 Non-Nil: 4 Unique: 4 Elements: 8 Non-Nil: 7 Unique: 6
IPAddr
provides a set of methods to manipulate an IP address. Both IPv4 and IPv6 are supported.
require 'ipaddr' ipaddr1 = IPAddr.new "3ffe:505:2::1" p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff> p ipaddr1.to_s #=> "3ffe:505:2::1" ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000> p ipaddr2.to_s #=> "3ffe:505:2::" ipaddr3 = IPAddr.new "192.168.2.0/24" p ipaddr3 #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>
The Matrix
class represents a mathematical matrix. It provides methods for creating matrices, operating on them arithmetically and algebraically, and determining their mathematical properties (trace, rank, inverse, determinant).
Method
Catalogue To create a matrix:
Matrix.rows
(rows, copy = true)
Matrix.build
(row_count
, column_count
, &block)
To access Matrix
elements/columns/rows/submatrices/properties:
laplace_expansion
(row_or_column: num)
cofactor_expansion
(row_or_column: num)
Properties of a matrix:
Matrix
arithmetic:
Matrix
functions:
Matrix
decompositions:
Complex
arithmetic:
conj
conjugate
imag
imaginary
real
rect
rectangular
Conversion to other data types:
String representations:
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:
bash-3.2$ ruby optparse-test.rb -r optparse-test.rb:9:in `<main>': missing argument: -r (OptionParser::MissingArgument) bash-3.2$ 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 soon.
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:
bash-3.2$ ruby optparse-test.rb -t nonsense ... invalid argument: -t nonsense (OptionParser::InvalidArgument) from ... time.rb:5:in `block in <top (required)>' from optparse-test.rb:31:in `<main>' bash-3.2$ ruby optparse-test.rb -t 10-11-12 2010-11-12 00:00:00 -0500 bash-3.2$ 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!
output:
bash-3.2$ ruby optparse-test.rb --user 1 #<struct User id=1, name="Sam"> bash-3.2$ ruby optparse-test.rb --user 2 #<struct User id=2, name="Gandalf"> bash-3.2$ ruby optparse-test.rb --user 3 optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError)
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
Shell
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.
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:
bash-3.2$ ruby optparse-test.rb -r optparse-test.rb:9:in `<main>': missing argument: -r (OptionParser::MissingArgument) bash-3.2$ 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 soon.
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:
bash-3.2$ ruby optparse-test.rb -t nonsense ... invalid argument: -t nonsense (OptionParser::InvalidArgument) from ... time.rb:5:in `block in <top (required)>' from optparse-test.rb:31:in `<main>' bash-3.2$ ruby optparse-test.rb -t 10-11-12 2010-11-12 00:00:00 -0500 bash-3.2$ 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!
output:
bash-3.2$ ruby optparse-test.rb --user 1 #<struct User id=1, name="Sam"> bash-3.2$ ruby optparse-test.rb --user 2 #<struct User id=2, name="Gandalf"> bash-3.2$ ruby optparse-test.rb --user 3 optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError)
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
Shell
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.