The Version
class processes string versions into comparable values. A version string should normally be a series of numbers separated by periods. Each part (digits separated by periods) is considered its own number, and these are used for sorting. So for instance, 3.10 sorts higher than 3.2 because ten is greater than two.
If any part contains letters (currently only a-z are supported) then that version is considered prerelease. Versions with a prerelease part in the Nth part sort less than versions with N-1 parts. Prerelease parts are sorted alphabetically using the normal Ruby string sorting rules. If a prerelease part contains both letters and numbers, it will be broken into multiple parts to provide expected sort behavior (1.0.a10 becomes 1.0.a.10, and is greater than 1.0.a9).
Prereleases sort between real releases (newest to oldest):
1.0
1.0.b1
1.0.a.2
0.9
If you want to specify a version restriction that includes both prereleases and regular releases of the 1.x series this is the best way:
s.add_dependency 'example', '>= 1.0.0.a', '< 2.0.0'
Users expect to be able to specify a version constraint that gives them some reasonable expectation that new versions of a library will work with their software if the version constraint is true, and not work with their software if the version constraint is false. In other words, the perfect system will accept all compatible versions of the library and reject all incompatible versions.
Libraries change in 3 ways (well, more than 3, but stay focused here!).
The change may be an implementation detail only and have no effect on the client software.
The change may add new features, but do so in a way that client software written to an earlier version is still compatible.
The change may change the public interface of the library in such a way that old software is no longer compatible.
Some examples are appropriate at this point. Suppose I have a Stack class that supports a push
and a pop
method.
Switch from an array based implementation to a linked-list based implementation.
Provide an automatic (and transparent) backing store for large stacks.
Add a depth
method to return the current depth of the stack.
Add a top
method that returns the current top of stack (without changing the stack).
Change push
so that it returns the item pushed (previously it had no usable return value).
Changes pop
so that it no longer returns a value (you must use top
to get the top of the stack).
Rename the methods to push_item
and pop_item
.
Rational
Versioning Versions shall be represented by three non-negative integers, separated by periods (e.g. 3.1.4). The first integers is the “major” version number, the second integer is the “minor” version number, and the third integer is the “build” number.
A category 1 change (implementation detail) will increment the build number.
A category 2 change (backwards compatible) will increment the minor version number and reset the build number.
A category 3 change (incompatible) will increment the major build number and reset the minor and build numbers.
Any “public” release of a gem should have a different version. Normally that means incrementing the build number. This means a developer can generate builds all day long, but as soon as they make a public release, the version must be updated.
Let’s work through a project lifecycle using our Stack example from above.
Version
0.0.1
The initial Stack class is release.
Version
0.0.2
Switched to a linked=list implementation because it is cooler.
Version
0.1.0
Added a depth
method.
Version
1.0.0
Added top
and made pop
return nil (pop
used to return the old top item).
Version
1.1.0
push
now returns the value pushed (it used it return nil).
Version
1.1.1
Fixed a bug in the linked list implementation.
Version
1.1.2
Fixed a bug introduced in the last fix.
Client A needs a stack with basic push/pop capability. They write to the original interface (no top
), so their version constraint looks like:
gem 'stack', '>= 0.0'
Essentially, any version is OK with Client A. An incompatible change to the library will cause them grief, but they are willing to take the chance (we call Client A optimistic).
Client B is just like Client A except for two things: (1) They use the depth
method and (2) they are worried about future incompatibilities, so they write their version constraint like this:
gem 'stack', '~> 0.1'
The depth
method was introduced in version 0.1.0, so that version or anything later is fine, as long as the version stays below version 1.0 where incompatibilities are introduced. We call Client B pessimistic because they are worried about incompatible future changes (it is OK to be pessimistic!).
Version
Catastrophe: From: blog.zenspider.com/2008/10/rubygems-howto-preventing-cata.html
Let’s say you’re depending on the fnord gem version 2.y.z. If you specify your dependency as “>= 2.0.0” then, you’re good, right? What happens if fnord 3.0 comes out and it isn’t backwards compatible with 2.y.z? Your stuff will break as a result of using “>=”. The better route is to specify your dependency with an “approximate” version specifier (“~>”). They’re a tad confusing, so here is how the dependency specifiers work:
Specification From ... To (exclusive) ">= 3.0" 3.0 ... ∞ "~> 3.0" 3.0 ... 4.0 "~> 3.0.0" 3.0.0 ... 3.1 "~> 3.5" 3.5 ... 4.0 "~> 3.5.0" 3.5.0 ... 3.6 "~> 3" 3.0 ... 4.0
For the last example, single-digit versions are automatically extended with a zero to give a sensible result.
Represents an HTTP protocol version
Raised by transcoding methods when a named encoding does not correspond with a known converter.
Mixin module that provides the following:
Access to the CGI
environment variables as methods. See documentation to the CGI
class for a list of these variables. The methods are exposed by removing the leading HTTP_
(if it exists) and downcasing the name. For example, auth_type
will return the environment variable AUTH_TYPE
, and accept
will return the value for HTTP_ACCEPT
.
Access to cookies, including the cookies attribute.
Access to parameters, including the params attribute, and overloading []
to perform parameter value lookup by key.
The initialize_query
method, for initializing the above mechanisms, handling multipart forms, and allowing the class to be used in “offline” mode.
This is a set of entity constants – the ones defined in the XML
specification. These are gt
, lt
, amp
, quot
and apos
. CAUTION: these entities does not have parent and document
Utility methods for using the RubyGems API.
! –
\private Initializes the world of objects and classes. At first, the function bootstraps the class hierarchy. It initializes the most fundamental classes and their metaclasses. - \c BasicObject - \c Object - \c Module - \c Class After the bootstrap step, the class hierarchy becomes as the following diagram. \image html boottime-classes.png Then, the function defines classes, modules and methods as usual. \ingroup class
++
DateTime
A subclass of Date
that easily handles date, hour, minute, second, and offset.
DateTime
does not consider any leap seconds, does not track any summer time rules.
A DateTime
object is created with DateTime::new
, DateTime::jd
, DateTime::ordinal
, DateTime::commercial
, DateTime::parse
, DateTime::strptime
, DateTime::now
, Time#to_datetime
, etc.
require 'date' DateTime.new(2001,2,3,4,5,6) #=> #<DateTime: 2001-02-03T04:05:06+00:00 ...>
The last element of day, hour, minute, or second can be a fractional number. The fractional number’s precision is assumed at most nanosecond.
DateTime.new(2001,2,3.5) #=> #<DateTime: 2001-02-03T12:00:00+00:00 ...>
An optional argument, the offset, indicates the difference between the local time and UTC. For example, Rational(3,24)
represents ahead of 3 hours of UTC, Rational(-5,24)
represents behind of 5 hours of UTC. The offset should be -1 to +1, and its precision is assumed at most second. The default value is zero (equals to UTC).
DateTime.new(2001,2,3,4,5,6,Rational(3,24)) #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>
The offset also accepts string form:
DateTime.new(2001,2,3,4,5,6,'+03:00') #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>
An optional argument, the day of calendar reform (start
), denotes a Julian day number, which should be 2298874 to 2426355 or negative/positive infinity. The default value is Date::ITALY
(2299161=1582-10-15).
A DateTime
object has various methods. See each reference.
d = DateTime.parse('3rd Feb 2001 04:05:06+03:30') #=> #<DateTime: 2001-02-03T04:05:06+03:30 ...> d.hour #=> 4 d.min #=> 5 d.sec #=> 6 d.offset #=> (7/48) d.zone #=> "+03:30" d += Rational('1.5') #=> #<DateTime: 2001-02-04%16:05:06+03:30 ...> d = d.new_offset('+09:00') #=> #<DateTime: 2001-02-04%21:35:06+09:00 ...> d.strftime('%I:%M:%S %p') #=> "09:35:06 PM" d > DateTime.new(1999) #=> true
DateTime
and when should you use Time
? It’s a common misconception that William Shakespeare and Miguel de Cervantes died on the same day in history - so much so that UNESCO named April 23 as World Book Day because of this fact. However, because England hadn’t yet adopted the Gregorian Calendar Reform (and wouldn’t until 1752) their deaths are actually 10 days apart. Since Ruby’s Time
class implements a proleptic Gregorian calendar and has no concept of calendar reform there’s no way to express this with Time
objects. This is where DateTime
steps in:
shakespeare = DateTime.iso8601('1616-04-23', Date::ENGLAND) #=> Tue, 23 Apr 1616 00:00:00 +0000 cervantes = DateTime.iso8601('1616-04-23', Date::ITALY) #=> Sat, 23 Apr 1616 00:00:00 +0000
Already you can see something is weird - the days of the week are different. Taking this further:
cervantes == shakespeare #=> false (shakespeare - cervantes).to_i #=> 10
This shows that in fact they died 10 days apart (in reality 11 days since Cervantes died a day earlier but was buried on the 23rd). We can see the actual date of Shakespeare’s death by using the gregorian
method to convert it:
shakespeare.gregorian #=> Tue, 03 May 1616 00:00:00 +0000
So there’s an argument that all the celebrations that take place on the 23rd April in Stratford-upon-Avon are actually the wrong date since England is now using the Gregorian calendar. You can see why when we transition across the reform date boundary:
# start off with the anniversary of Shakespeare's birth in 1751 shakespeare = DateTime.iso8601('1751-04-23', Date::ENGLAND) #=> Tue, 23 Apr 1751 00:00:00 +0000 # add 366 days since 1752 is a leap year and April 23 is after February 29 shakespeare + 366 #=> Thu, 23 Apr 1752 00:00:00 +0000 # add another 365 days to take us to the anniversary in 1753 shakespeare + 366 + 365 #=> Fri, 04 May 1753 00:00:00 +0000
As you can see, if we’re accurately tracking the number of solar years since Shakespeare’s birthday then the correct anniversary date would be the 4th May and not the 23rd April.
So when should you use DateTime
in Ruby and when should you use Time
? Almost certainly you’ll want to use Time
since your app is probably dealing with current dates and times. However, if you need to deal with dates and times in a historical context you’ll want to use DateTime
to avoid making the same mistakes as UNESCO. If you also have to deal with timezones then best of luck - just bear in mind that you’ll probably be dealing with local solar times, since it wasn’t until the 19th century that the introduction of the railways necessitated the need for Standard Time and eventually timezones.
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
You can pass a UTC offset:
Time.new(2002, 10, 31, 2, 2, 2, "+02:00") #=> 2002-10-31 02:02:02 +0200
Or a timezone object:
tz = timezone("Europe/Athens") # Eastern European Time, UTC+2 Time.new(2002, 10, 31, 2, 2, 2, tz) #=> 2002-10-31 02:02:02 +0200
You can also use Time::gm
, Time::local
and Time::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 it 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
A timezone argument must have local_to_utc
and utc_to_local
methods, and may have name
, abbr
, and dst?
methods.
The local_to_utc
method should convert a Time-like object from the timezone to UTC, and utc_to_local
is the opposite. The result also should be a Time
or Time-like object (not necessary to be the same class). The zone
of the result is just ignored. Time-like argument to these methods is similar to a Time
object in UTC without sub-second; it has attribute readers for the parts, e.g. year
, month
, and so on, and epoch time readers, to_i
. The sub-second attributes are fixed as 0, and utc_offset
, zone
, isdst
, and their aliases are same as a Time
object in UTC. Also to_time
, +
, and -
methods are defined.
The name
method is used for marshaling. If this method is not defined on a timezone object, Time
objects using that timezone object can not be dumped by Marshal
.
The abbr
method is used by ‘%Z’ in strftime
.
The dst?
method is called with a Time
value and should return whether the Time
value is in daylight savings time in the zone.
At loading marshaled data, a timezone name will be converted to a timezone object by find_timezone
class method, if the method is defined.
Similarly, that class method will be called when a timezone argument does not have the necessary methods mentioned above.
A Struct
is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.
The Struct
class generates new subclasses that hold a set of members and their values. For each member a reader and writer method is created similar to Module#attr_accessor
.
Customer = Struct.new(:name, :address) do def greeting "Hello #{name}!" end end dave = Customer.new("Dave", "123 Main") dave.name #=> "Dave" dave.greeting #=> "Hello Dave!"
See Struct::new
for further examples of creating struct subclasses and instances.
In the method descriptions that follow, a “member” parameter refers to a struct member which is either a quoted string ("name"
) or a Symbol
(:name
).
Expect library adds the IO
instance method expect
, which does similar act to tcl’s expect extension.
In order to use this method, you must require expect:
require 'expect'
Please see expect
for usage.
The IO
class is the basis for all input and output in Ruby. An I/O stream may be duplexed (that is, bidirectional), and so may use more than one native operating system stream.
Many of the examples in this section use the File
class, the only standard subclass of IO
. The two classes are closely associated. Like the File
class, the Socket
library subclasses from IO
(such as TCPSocket
or UDPSocket
).
The Kernel#open
method can create an IO
(or File
) object for these types of arguments:
A plain string represents a filename suitable for the underlying operating system.
A string starting with "|"
indicates a subprocess. The remainder of the string following the "|"
is invoked as a process with appropriate input/output channels connected to it.
A string equal to "|-"
will create another Ruby instance as a subprocess.
The IO
may be opened with different file modes (read-only, write-only) and encodings for proper conversion. See IO.new
for these options. See Kernel#open
for details of the various command formats described above.
IO.popen
, the Open3
library, or Process#spawn may also be used to communicate with subprocesses through an IO
.
Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename "/gumby/ruby/test.rb"
will be opened as "\gumby\ruby\test.rb"
. When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:
"C:\\gumby\\ruby\\test.rb"
Our examples here will use the Unix-style forward slashes; File::ALT_SEPARATOR can be used to get the platform-specific separator character.
The global constant ARGF
(also accessible as $<
) provides an IO-like stream which allows access to all files mentioned on the command line (or STDIN if no files are mentioned). ARGF#path
and its alias ARGF#filename
are provided to access the name of the file currently being read.
The io/console extension provides methods for interacting with the console. The console can be accessed from IO.console
or the standard input/output/error IO
objects.
Requiring io/console adds the following methods:
Example:
require 'io/console' rows, columns = $stdout.winsize puts "Your screen is #{columns} wide and #{rows} tall"
UNIXServer
represents a UNIX domain stream server socket.
UNIXSocket
represents a UNIX domain stream client socket.
Pseudo I/O on String
object, with interface corresponding to IO
.
Commonly used to simulate $stdio
or $stderr
require 'stringio' # Writing stream emulation io = StringIO.new io.puts "Hello World" io.string #=> "Hello World\n" # Reading stream emulation io = StringIO.new "first\nsecond\nlast\n" io.getc #=> "f" io.gets #=> "irst\n" io.read #=> "second\nlast\n"
BasicObject
is the parent class of all classes in Ruby. It’s an explicit blank class.
BasicObject
can be used for creating object hierarchies independent of Ruby’s object hierarchy, proxy objects like the Delegator
class, or other uses where namespace pollution from Ruby’s methods and classes must be avoided.
To avoid polluting BasicObject
for other users an appropriately named subclass of BasicObject
should be created instead of directly modifying BasicObject:
class MyObjectSystem < BasicObject end
BasicObject
does not include Kernel
(for methods like puts
) and BasicObject
is outside of the namespace of the standard library so common classes will not be found without using a full class path.
A variety of strategies can be used to provide useful portions of the standard library to subclasses of BasicObject
. A subclass could include Kernel
to obtain puts
, exit
, etc. A custom Kernel-like module could be created and included or delegation can be used via method_missing
:
class MyObjectSystem < BasicObject DELEGATE = [:puts, :p] def method_missing(name, *args, &block) return super unless DELEGATE.include? name ::Kernel.send(name, *args, &block) end def respond_to_missing?(name, include_private = false) DELEGATE.include?(name) or super end end
Access to classes and modules from the Ruby standard library can be obtained in a BasicObject
subclass by referencing the desired constant from the root like ::File
or ::Enumerator
. Like method_missing
, const_missing can be used to delegate constant lookup to Object
:
class MyObjectSystem < BasicObject def self.const_missing(name) ::Object.const_get(name) end end
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 when a command was not found.
Raised when a command was not found.
The GetoptLong
class allows you to parse command line options similarly to the GNU getopt_long() C library call. Note, however, that GetoptLong
is a pure Ruby implementation.
GetoptLong
allows for POSIX-style options like --file
as well as single letter options like -f
The empty option --
(two minus symbols) is used to end option processing. This can be particularly important if options have optional arguments.
Here is a simple example of usage:
require 'getoptlong' opts = GetoptLong.new( [ '--help', '-h', GetoptLong::NO_ARGUMENT ], [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ], [ '--name', GetoptLong::OPTIONAL_ARGUMENT ] ) dir = nil name = nil repetitions = 1 opts.each do |opt, arg| case opt when '--help' puts <<-EOF hello [OPTION] ... DIR -h, --help: show help --repeat x, -n x: repeat x times --name [name]: greet user by name, if name not supplied default is John DIR: The directory in which to issue the greeting. EOF when '--repeat' repetitions = arg.to_i when '--name' if arg == '' name = 'John' else name = arg end end end if ARGV.length != 1 puts "Missing dir argument (try --help)" exit 0 end dir = ARGV.shift Dir.chdir(dir) for i in (1..repetitions) print "Hello" if name print ", #{name}" end puts end
Example command line:
hello -n 6 --name -- /tmp