SingleForwardable
can be used to setup delegation at the object level as well.
printer = String.new printer.extend SingleForwardable # prepare object for delegation printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts() printer.puts "Howdy!"
Also, SingleForwardable
can be used to set up delegation for a Class
or Module
.
class Implementation def self.service puts "serviced!" end end module Facade extend SingleForwardable def_delegator :Implementation, :service end Facade.service #=> serviced!
If you want to use both Forwardable and SingleForwardable
, you can use methods def_instance_delegator and def_single_delegator
, etc.
The Singleton
module implements the Singleton
pattern.
To use Singleton
, include the module in your class.
class Klass include Singleton # ... end
This ensures that only one instance of Klass can be created.
a,b = Klass.instance, Klass.instance a == b # => true Klass.new # => NoMethodError - new is private ...
The instance is created at upon the first call of Klass.instance().
class OtherKlass include Singleton # ... end ObjectSpace.each_object(OtherKlass){} # => 0 OtherKlass.instance ObjectSpace.each_object(OtherKlass){} # => 1
This behavior is preserved under inheritance and cloning.
This above is achieved by:
Making Klass.new and Klass.allocate private.
Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the Singleton
properties are kept when inherited and cloned.
Providing the Klass.instance() method that returns the same object each time it is called.
Overriding Klass._load(str) to call Klass.instance().
Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent cloning or duping.
Singleton
and Marshal
By default Singleton’s _dump(depth)
returns the empty string. Marshalling by default will strip state information, e.g. instance variables from the instance. Classes using Singleton
can provide custom _load(str) and _dump(depth) methods to retain some of the previous state of the instance.
require 'singleton' class Example include Singleton attr_accessor :keep, :strip def _dump(depth) # this strips the @strip information from the instance Marshal.dump(@keep, depth) end def self._load(str) instance.keep = Marshal.load(str) instance end end a = Example.instance a.keep = "keep this" a.strip = "get rid of this" stored_state = Marshal.dump(a) a.keep = nil a.strip = nil b = Marshal.load(stored_state) p a == b # => true p a.keep # => "keep this" p a.strip # => nil
TSort
implements topological sorting using Tarjan’s algorithm for strongly connected components.
TSort
is designed to be able to be used with any object which can be interpreted as a directed graph.
TSort
requires two methods to interpret an object as a graph, tsort_each_node
and tsort_each_child.
tsort_each_node
is used to iterate for all nodes over a graph.
tsort_each_child
is used to iterate for child nodes of a given node.
The equality of nodes are defined by eql? and hash since TSort
uses Hash
internally.
The following example demonstrates how to mix the TSort
module into an existing class (in this case, Hash
). Here, we’re treating each key in the hash as a node in the graph, and so we simply alias the required tsort_each_node
method to Hash’s each_key method. For each key in the hash, the associated value is an array of the node’s child nodes. This choice in turn leads to our implementation of the required tsort_each_child
method, which fetches the array of child nodes and then iterates over that array using the user-supplied block.
require 'tsort' class Hash include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort #=> [3, 2, 1, 4] {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components #=> [[4], [2, 3], [1]]
A very simple ‘make’ like tool can be implemented as follows:
require 'tsort' class Make def initialize @dep = {} @dep.default = [] end def rule(outputs, inputs=[], &block) triple = [outputs, inputs, block] outputs.each {|f| @dep[f] = [triple]} @dep[triple] = inputs end def build(target) each_strongly_connected_component_from(target) {|ns| if ns.length != 1 fs = ns.delete_if {|n| Array === n} raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}") end n = ns.first if Array === n outputs, inputs, block = n inputs_time = inputs.map {|f| File.mtime f}.max begin outputs_time = outputs.map {|f| File.mtime f}.min rescue Errno::ENOENT outputs_time = nil end if outputs_time == nil || inputs_time != nil && outputs_time <= inputs_time sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i block.call end end } end def tsort_each_child(node, &block) @dep[node].each(&block) end include TSort end def command(arg) print arg, "\n" system arg end m = Make.new m.rule(%w[t1]) { command 'date > t1' } m.rule(%w[t2]) { command 'date > t2' } m.rule(%w[t3]) { command 'date > t3' } m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' } m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' } m.build('t5')
‘tsort.rb’ is wrong name because this library uses Tarjan’s algorithm for strongly connected components. Although ‘strongly_connected_components.rb’ is correct but too long.
Tarjan, “Depth First Search and Linear Graph Algorithms”,
SIAM Journal on Computing, Vol. 1, No. 2, pp. 146-160, June 1972.
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.
Specifies a Specification object that should be activated. Also contains a dependency that was used to introduce this activation.
Switch
that can omit argument.
A GitSpecification
represents a gem that is sourced from a git repository and is being loaded through a gem dependencies file through the git:
option.
Class
that parses String’s into URI’s.
It contains a Hash
set of patterns and Regexp’s that match and validate.
Configuration options for dumping YAML
.
See Net::HTTPGenericRequest
for attributes and methods.
Represents a specification retrieved via the rubygems.org API.
This is used to avoid loading the full Specification object when all we need is the name, version, and dependencies.
Represents a possible Specification object returned from IndexSet. Used to delay needed to download full Specification objects when only the name
and version
are needed.
An InstalledSpecification
represents a gem that is already installed locally.
A LocalSpecification
comes from a .gem file on the local filesystem.
The LockSpecification
comes from a lockfile (Gem::RequestSet::Lockfile
).
A LockSpecification’s dependency information is pre-filled from the lockfile.
The Resolver::SpecSpecification contains common functionality for Resolver specifications that are backed by a Gem::Specification
.
A Resolver::Specification contains a subset of the information contained in a Gem::Specification
. Only the information necessary for dependency resolution in the resolver is included.
A VendorSpecification
represents a gem that has been unpacked into a project and is being loaded through a gem dependencies file through the path:
option.