TCPSocket
represents a TCP/IP client socket.
A simple client may look like:
require 'socket' s = TCPSocket.new 'localhost', 2000 while line = s.gets # Read lines from socket puts line # and print them end s.close # close socket when done
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:
require 'delegate' 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 require 'delegate' 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
Class Data provides a convenient way to define simple classes for value-alike objects.
The simplest example of usage:
Measure = Data.define(:amount, :unit) # Positional arguments constructor is provided distance = Measure.new(100, 'km') #=> #<data Measure amount=100, unit="km"> # Keyword arguments constructor is provided weight = Measure.new(amount: 50, unit: 'kg') #=> #<data Measure amount=50, unit="kg"> # Alternative form to construct an object: speed = Measure[10, 'mPh'] #=> #<data Measure amount=10, unit="mPh"> # Works with keyword arguments, too: area = Measure[amount: 1.5, unit: 'm^2'] #=> #<data Measure amount=1.5, unit="m^2"> # Argument accessors are provided: distance.amount #=> 100 distance.unit #=> "km"
Constructed object also has a reasonable definitions of ==
operator, to_h
hash conversion, and deconstruct
/ deconstruct_keys
to be used in pattern matching.
::define
method accepts an optional block and evaluates it in the context of the newly defined class. That allows to define additional methods:
Measure = Data.define(:amount, :unit) do def <=>(other) return unless other.is_a?(self.class) && other.unit == unit amount <=> other.amount end include Comparable end Measure[3, 'm'] < Measure[5, 'm'] #=> true Measure[3, 'm'] < Measure[5, 'kg'] # comparison of Measure with Measure failed (ArgumentError)
Data
provides no member writers, or enumerators: it is meant to be a storage for immutable atomic values. But note that if some of data members is of a mutable class, Data
does no additional immutability enforcement:
Event = Data.define(:time, :weekdays) event = Event.new('18:00', %w[Tue Wed Fri]) #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri"]> # There is no #time= or #weekdays= accessors, but changes are # still possible: event.weekdays << 'Sat' event #=> #<data Event time="18:00", weekdays=["Tue", "Wed", "Fri", "Sat"]>
See also Struct
, which is a similar concept, but has more container-alike API, allowing to change contents of the object and enumerate it.
The Etc
module provides access to information typically stored in files in the /etc
directory on Unix systems.
The information accessible consists of the information found in the /etc/passwd
and /etc/group
files, plus information about the system’s temporary directory (/tmp
) and configuration directory (/etc
).
The Etc
module provides a more reliable way to access information about the logged in user than environment variables such as +$USER+.
Example:
require 'etc' login = Etc.getlogin info = Etc.getpwnam(login) username = info.gecos.split(/,/).first puts "Hello #{username}, I see your login name is #{login}"
Note that the methods provided by this module are not always secure. It should be used for informational purposes, and not for security.
All operations defined in this module are class methods, so that you can include the Etc
module into your class.
Psych
is a YAML
parser and emitter. Psych
leverages libyaml [Home page: pyyaml.org/wiki/LibYAML] or [git repo: github.com/yaml/libyaml] for its YAML
parsing and emitting capabilities. In addition to wrapping libyaml, Psych
also knows how to serialize and de-serialize most Ruby objects to and from the YAML
format.
YAML
RIGHT NOW! # Parse some YAML Psych.load("--- foo") # => "foo" # Emit some YAML Psych.dump("foo") # => "--- foo\n...\n" { :a => 'b'}.to_yaml # => "---\n:a: b\n"
Got more time on your hands? Keep on reading!
YAML
Parsing Psych
provides a range of interfaces for parsing a YAML
document ranging from low level to high level, depending on your parsing needs. At the lowest level, is an event based parser. Mid level is access to the raw YAML
AST, and at the highest level is the ability to unmarshal YAML
to Ruby objects.
YAML
Emitting Psych
provides a range of interfaces ranging from low to high level for producing YAML
documents. Very similar to the YAML
parsing interfaces, Psych
provides at the lowest level, an event based system, mid-level is building a YAML
AST, and the highest level is converting a Ruby object straight to a YAML
document.
The high level YAML
parser provided by Psych
simply takes YAML
as input and returns a Ruby data structure. For information on using the high level parser see Psych.load
Psych.safe_load("--- a") # => 'a' Psych.safe_load("---\n - a\n - b") # => ['a', 'b'] # From a trusted string: Psych.load("--- !ruby/range\nbegin: 0\nend: 42\nexcl: false\n") # => 0..42
Psych.safe_load_file("data.yml", permitted_classes: [Date]) Psych.load_file("trusted_database.yml")
Exception
handling begin # The second argument changes only the exception contents Psych.parse("--- `", "file.txt") rescue Psych::SyntaxError => ex ex.file # => 'file.txt' ex.message # => "(file.txt): found character that cannot start any token" end
The high level emitter has the easiest interface. Psych
simply takes a Ruby data structure and converts it to a YAML
document. See Psych.dump
for more information on dumping a Ruby data structure.
# Dump an array, get back a YAML string Psych.dump(['a', 'b']) # => "---\n- a\n- b\n" # Dump an array to an IO object Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890> # Dump an array with indentation set Psych.dump(['a', ['b']], :indentation => 3) # => "---\n- a\n- - b\n" # Dump an array to an IO with indentation set Psych.dump(['a', ['b']], StringIO.new, :indentation => 3)
Currently there is no direct API for dumping Ruby structure to file:
File.open('database.yml', 'w') do |file| file.write(Psych.dump(['a', 'b'])) end
Psych
provides access to an AST produced from parsing a YAML
document. This tree is built using the Psych::Parser
and Psych::TreeBuilder
. The AST can be examined and manipulated freely. Please see Psych::parse_stream
, Psych::Nodes
, and Psych::Nodes::Node
for more information on dealing with YAML
syntax trees.
# Returns Psych::Nodes::Stream Psych.parse_stream("---\n - a\n - b") # Returns Psych::Nodes::Document Psych.parse("---\n - a\n - b")
# Returns Psych::Nodes::Stream Psych.parse_stream(File.read('database.yml')) # Returns Psych::Nodes::Document Psych.parse_file('database.yml')
Exception
handling begin # The second argument changes only the exception contents Psych.parse("--- `", "file.txt") rescue Psych::SyntaxError => ex ex.file # => 'file.txt' ex.message # => "(file.txt): found character that cannot start any token" end
At the mid level is building an AST. This AST is exactly the same as the AST used when parsing a YAML
document. Users can build an AST by hand and the AST knows how to emit itself as a YAML
document. See Psych::Nodes
, Psych::Nodes::Node
, and Psych::TreeBuilder
for more information on building a YAML
AST.
# We need Psych::Nodes::Stream (not Psych::Nodes::Document) stream = Psych.parse_stream("---\n - a\n - b") stream.to_yaml # => "---\n- a\n- b\n"
# We need Psych::Nodes::Stream (not Psych::Nodes::Document) stream = Psych.parse_stream(File.read('database.yml')) File.open('database.yml', 'w') do |file| file.write(stream.to_yaml) end
The lowest level parser should be used when the YAML
input is already known, and the developer does not want to pay the price of building an AST or automatic detection and conversion to Ruby objects. See Psych::Parser
for more information on using the event based parser.
Psych::Nodes::Stream
structure parser = Psych::Parser.new(TreeBuilder.new) # => #<Psych::Parser> parser = Psych.parser # it's an alias for the above parser.parse("---\n - a\n - b") # => #<Psych::Parser> parser.handler # => #<Psych::TreeBuilder> parser.handler.root # => #<Psych::Nodes::Stream>
recorder = Psych::Handlers::Recorder.new parser = Psych::Parser.new(recorder) parser.parse("---\n - a\n - b") recorder.events # => [list of [event, args] lists] # event is one of: Psych::Handler::EVENTS # args are the arguments passed to the event
The lowest level emitter is an event based system. Events are sent to a Psych::Emitter
object. That object knows how to convert the events to a YAML
document. This interface should be used when document format is known in advance or speed is a concern. See Psych::Emitter
for more information.
Psych.parser.parse("--- a") # => #<Psych::Parser> parser.handler.first # => #<Psych::Nodes::Stream> parser.handler.first.to_ruby # => ["a"] parser.handler.root.first # => #<Psych::Nodes::Document> parser.handler.root.first.to_ruby # => "a" # You can instantiate an Emitter manually Psych::Visitors::ToRuby.new.accept(parser.handler.root.first) # => "a"
define UnicodeNormalize module here so that we don’t have to look it up
The marshaling library converts collections of Ruby objects into a byte stream, allowing them to be stored outside the currently active script. This data may subsequently be read and the original objects reconstituted.
Marshaled data has major and minor version numbers stored along with the object information. In normal use, marshaling can only load data written with the same major version number and an equal or lower minor version number. If Ruby’s “verbose” flag is set (normally using -d, -v, -w, or –verbose) the major and minor numbers must match exactly. Marshal
versioning is independent of Ruby’s version numbers. You can extract the version by reading the first two bytes of marshaled data.
str = Marshal.dump("thing") RUBY_VERSION #=> "1.9.0" str[0].ord #=> 4 str[1].ord #=> 8
Some objects cannot be dumped: if the objects to be dumped include bindings, procedure or method objects, instances of class IO
, or singleton objects, a TypeError
will be raised.
If your class has special serialization needs (for example, if you want to serialize in some specific format), or if it contains objects that would otherwise not be serializable, you can implement your own serialization strategy.
There are two methods of doing this, your object can define either marshal_dump and marshal_load or _dump and _load. marshal_dump will take precedence over _dump if both are defined. marshal_dump may result in smaller Marshal
strings.
By design, Marshal.load
can deserialize almost any class loaded into the Ruby process. In many cases this can lead to remote code execution if the Marshal
data is loaded from an untrusted source.
As a result, Marshal.load
is not suitable as a general purpose serialization format and you should never unmarshal user supplied input or other untrusted data.
If you need to deserialize untrusted data, use JSON
or another serialization format that is only able to load simple, ‘primitive’ types such as String
, Array
, Hash
, etc. Never allow user input to specify arbitrary types to deserialize into.
When dumping an object the method marshal_dump will be called. marshal_dump must return a result containing the information necessary for marshal_load to reconstitute the object. The result can be any object.
When loading an object dumped using marshal_dump the object is first allocated then marshal_load is called with the result from marshal_dump. marshal_load must recreate the object from the information in the result.
Example:
class MyObj def initialize name, version, data @name = name @version = version @data = data end def marshal_dump [@name, @version] end def marshal_load array @name, @version = array end end
Use _dump and _load when you need to allocate the object you’re restoring yourself.
When dumping an object the instance method _dump is called with an Integer
which indicates the maximum depth of objects to dump (a value of -1 implies that you should disable depth checking). _dump must return a String
containing the information necessary to reconstitute the object.
The class method _load should take a String
and use it to return an object of the same class.
Example:
class MyObj def initialize name, version, data @name = name @version = version @data = data end def _dump level [@name, @version].join ':' end def self._load args new(*args.split(':')) end end
Since Marshal.dump
outputs a string you can have _dump return a Marshal
string which is Marshal.loaded in _load for complex objects.
The DidYouMean::Formatter
is the basic, default formatter for the gem. The formatter responds to the message_for
method and it returns a human readable string.
The DidYouMean::Formatter
is the basic, default formatter for the gem. The formatter responds to the message_for
method and it returns a human readable string.
The DidYouMean::Formatter
is the basic, default formatter for the gem. The formatter responds to the message_for
method and it returns a human readable string.
Default formatter for log messages.
Parent class for informational (1xx) HTTP
response classes.
An informational response indicates that the request was received and understood.
References:
Response class for Switching Protocol
responses (status code 101).
The <tt>Switching Protocol<tt> response indicates that the server has received a request to switch protocols, and has agreed to do so.
References:
Map from option/keyword string to object with completion.
Individual switch class. Not important to the user.
Defined within Switch
are several Switch-derived classes: NoArgument
, RequiredArgument
, etc.
The command manager registers and installs all the individual sub-commands supported by the gem command.
Extra commands can be provided by writing a rubygems_plugin.rb file in an installed gem. You should register your command against the Gem::CommandManager
instance, like this:
# file rubygems_plugin.rb require 'rubygems/command_manager' Gem::CommandManager.instance.register_command :edit
You should put the implementation of your command in rubygems/commands.
# file rubygems/commands/edit_command.rb class Gem::Commands::EditCommand < Gem::Command # ... end
See Gem::Command
for instructions on writing gem commands.
An error that indicates we weren’t able to fetch some data from a source
Used to raise parsing and loading errors
RemoteFetcher
handles the details of fetching gems and gem information from a remote source.
SpecFetcher
handles metadata updates from remote gem repositories.