Raised when an IO
operation fails.
File.open("/etc/hosts") {|f| f << "example"} #=> IOError: not opened for writing File.open("/etc/hosts") {|f| f.close; f.read } #=> IOError: closed stream
Note that some IO
failures raise SystemCallError
s and these are not subclasses of IOError:
File.open("does/not/exist") #=> Errno::ENOENT: No such file or directory - does/not/exist
Raised by some IO
operations when reaching the end of file. Many IO
methods exist in two forms,
one that returns nil
when the end of file is reached, the other raises EOFError
.
EOFError
is a subclass of IOError
.
file = File.open("/etc/hosts") file.read file.gets #=> nil file.readline #=> EOFError: end of file reached
Outputs a source level execution trace of a Ruby program.
It does this by registering an event handler with Kernel#set_trace_func
for processing incoming events. It also provides methods for filtering unwanted trace output (see Tracer.add_filter
, Tracer.on
, and Tracer.off
).
Consider the following Ruby script
class A def square(a) return a*a end end a = A.new a.square(5)
Running the above script using ruby -r tracer example.rb
will output the following trace to STDOUT (Note you can also explicitly require 'tracer'
)
#0:<internal:lib/rubygems/custom_require>:38:Kernel:<: - #0:example.rb:3::-: class A #0:example.rb:3::C: class A #0:example.rb:4::-: def square(a) #0:example.rb:7::E: end #0:example.rb:9::-: a = A.new #0:example.rb:10::-: a.square(5) #0:example.rb:4:A:>: def square(a) #0:example.rb:5:A:-: return a*a #0:example.rb:6:A:<: end | | | | | | | | | ---------------------+ event | | | ------------------------+ class | | --------------------------+ line | ------------------------------------+ filename ---------------------------------------+ thread
Symbol
table used for displaying incoming events:
call a C-language routine
return from a C-language routine
call a Ruby method
C
start a class or module definition
E
finish a class or module definition
-
execute code on a new line
raise an exception
return from a Ruby method
by Keiju ISHITSUKA(keiju@ishitsuka.com)
ERB
– Ruby Templating ERB
provides an easy to use but powerful templating system for Ruby. Using ERB
, actual Ruby code can be added to any plain text document for the purposes of generating document information details and/or flow control.
A very simple example is this:
require 'erb' x = 42 template = ERB.new <<-EOF The value of x is: <%= x %> EOF puts template.result(binding)
Prints: The value of x is: 42
More complex examples are given below.
ERB
recognizes certain tags in the provided template and converts them based on the rules below:
<% Ruby code -- inline with output %> <%= Ruby expression -- replace with result %> <%# comment -- ignored -- useful in testing %> % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new) %% replaced with % if first thing on a line and % processing is used <%% or %%> -- replace with <% or %> respectively
All other text is passed through ERB
filtering unchanged.
There are several settings you can change when you use ERB:
the nature of the tags that are recognized;
the value of $SAFE
under which the template is run;
the binding used to resolve local variables in the template.
See the ERB.new
and ERB#result
methods for more detail.
ERB
(or Ruby code generated by ERB
) returns a string in the same character encoding as the input string. When the input string has a magic comment, however, it returns a string in the encoding specified by the magic comment.
# -*- coding: utf-8 -*- require 'erb' template = ERB.new <<EOF <%#-*- coding: Big5 -*-%> \_\_ENCODING\_\_ is <%= \_\_ENCODING\_\_ %>. EOF puts template.result
Prints: _ENCODING_ is Big5.
ERB
is useful for any generic templating situation. Note that in this example, we use the convenient “% at start of line” tag, and we quote the template literally with %q{...}
to avoid trouble with the backslash.
require "erb" # Create template. template = %q{ From: James Edward Gray II <james@grayproductions.net> To: <%= to %> Subject: Addressing Needs <%= to[/\w+/] %>: Just wanted to send a quick note assuring that your needs are being addressed. I want you to know that my team will keep working on the issues, especially: <%# ignore numerous minor requests -- focus on priorities %> % priorities.each do |priority| * <%= priority %> % end Thanks for your patience. James Edward Gray II }.gsub(/^ /, '') message = ERB.new(template, 0, "%<>") # Set up template data. to = "Community Spokesman <spokesman@ruby_community.org>" priorities = [ "Run Ruby Quiz", "Document Modules", "Answer Questions on Ruby Talk" ] # Produce result. email = message.result puts email
Generates:
From: James Edward Gray II <james@grayproductions.net> To: Community Spokesman <spokesman@ruby_community.org> Subject: Addressing Needs Community: Just wanted to send a quick note assuring that your needs are being addressed. I want you to know that my team will keep working on the issues, especially: * Run Ruby Quiz * Document Modules * Answer Questions on Ruby Talk Thanks for your patience. James Edward Gray II
ERB
is often used in .rhtml
files (HTML with embedded Ruby). Notice the need in this example to provide a special binding when the template is run, so that the instance variables in the Product object can be resolved.
require "erb" # Build template data class. class Product def initialize( code, name, desc, cost ) @code = code @name = name @desc = desc @cost = cost @features = [ ] end def add_feature( feature ) @features << feature end # Support templating of member data. def get_binding binding end # ... end # Create template. template = %{ <html> <head><title>Ruby Toys -- <%= @name %></title></head> <body> <h1><%= @name %> (<%= @code %>)</h1> <p><%= @desc %></p> <ul> <% @features.each do |f| %> <li><b><%= f %></b></li> <% end %> </ul> <p> <% if @cost < 10 %> <b>Only <%= @cost %>!!!</b> <% else %> Call for a price, today! <% end %> </p> </body> </html> }.gsub(/^ /, '') rhtml = ERB.new(template) # Set up template data. toy = Product.new( "TZ-1002", "Rubysapien", "Geek's Best Friend! Responds to Ruby commands...", 999.95 ) toy.add_feature("Listens for verbal commands in the Ruby language!") toy.add_feature("Ignores Perl, Java, and all C variants.") toy.add_feature("Karate-Chop Action!!!") toy.add_feature("Matz signature on left leg.") toy.add_feature("Gem studded eyes... Rubies, of course!") # Produce result. rhtml.run(toy.get_binding)
Generates (some blank lines removed):
<html> <head><title>Ruby Toys -- Rubysapien</title></head> <body> <h1>Rubysapien (TZ-1002)</h1> <p>Geek's Best Friend! Responds to Ruby commands...</p> <ul> <li><b>Listens for verbal commands in the Ruby language!</b></li> <li><b>Ignores Perl, Java, and all C variants.</b></li> <li><b>Karate-Chop Action!!!</b></li> <li><b>Matz signature on left leg.</b></li> <li><b>Gem studded eyes... Rubies, of course!</b></li> </ul> <p> Call for a price, today! </p> </body> </html>
There are a variety of templating solutions available in various Ruby projects:
ERB’s big brother, eRuby, works the same but is written in C for speed;
Amrita (smart at producing HTML/XML);
cs/Template (written in C for speed);
RDoc
, distributed with Ruby, uses its own template engine, which can be reused elsewhere;
and others; search RubyGems.org or The Ruby Toolbox.
Rails, the web application framework, uses ERB
to create views.
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.
A class that provides two-phase lock with a counter. See Sync_m
for details.
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"
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.
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
Profile provides a way to Profile your Ruby application.
Profiling your program is a way of determining which methods are called and how long each method takes to complete. This way you can detect which methods are possible bottlenecks.
Profiling your program will slow down your execution time considerably, so activate it only when you need it. Don’t confuse benchmarking with profiling.
There are two ways to activate Profiling:
Run your Ruby script with -rprofile
:
ruby -rprofile example.rb
If you’re profiling an executable in your $PATH
you can use ruby -S
:
ruby -rprofile -S some_executable
Just require ‘profile’:
require 'profile' def slow_method 5000.times do 9999999999999999*999999999 end end def fast_method 5000.times do 9999999999999999+999999999 end end slow_method fast_method
The output in both cases is a report when the execution is over:
ruby -rprofile example.rb % cumulative self self total time seconds seconds calls ms/call ms/call name 68.42 0.13 0.13 2 65.00 95.00 Integer#times 15.79 0.16 0.03 5000 0.01 0.01 Fixnum#* 15.79 0.19 0.03 5000 0.01 0.01 Fixnum#+ 0.00 0.19 0.00 2 0.00 0.00 IO#set_encoding 0.00 0.19 0.00 1 0.00 100.00 Object#slow_method 0.00 0.19 0.00 2 0.00 0.00 Module#method_added 0.00 0.19 0.00 1 0.00 90.00 Object#fast_method 0.00 0.19 0.00 1 0.00 190.00 #toplevel
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
then loaded. Take care when implementing a plugin as your plugin file may be loaded multiple times if multiple versions of your gem are installed.
For an example plugin, see the graph gem which adds a ‘gem graph` command.
RubyGems defaults are stored in 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 and 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
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
Generate random hexadecimal strings:
require 'securerandom' p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362" p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559" p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
Generate random base64 strings:
p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA==" p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg==" p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
Generate random binary strings:
p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301" p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
Generate UUIDs:
p SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594" p SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
A module that provides a two-phase lock with a counter.
A module that provides a two-phase lock with a counter.
Raised if a parameter such as %e, %i, %o or %n is used without fetching a specific field.
A progress reporter that prints out messages about the current progress.