Results for: "match"

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.

Etc

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.

Overview

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.

I NEED TO PARSE OR EMIT 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.

High-level API

Parsing

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

Reading from a string

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

Reading from a file

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

Emitting

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.

Writing to a string

# 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)

Writing to a file

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

Mid-level API

Parsing

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.

Reading from a string

# Returns Psych::Nodes::Stream
Psych.parse_stream("---\n - a\n - b")

# Returns Psych::Nodes::Document
Psych.parse("---\n - a\n - b")

Reading from a file

# 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

Emitting

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.

Writing to a string

# 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"

Writing to a file

# 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

Low-level API

Parsing

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.

Reading to 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>

Receiving an events 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

Emitting

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.

Writing to a Ruby structure

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.

Security considerations

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.

marshal_dump and marshal_load

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

_dump and _load

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.

No documentation available
No documentation available
No documentation available

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:

Individual switch class. Not important to the user.

Defined within Switch are several Switch-derived classes: NoArgument, RequiredArgument, etc.

Represents an alternation pattern in pattern matching.

foo => bar | baz
       ^^^^^^^^^

Represents assigning to a constant path using an operator that isn’t ‘=`.

Parent::Child += value
^^^^^^^^^^^^^^^^^^^^^^

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.

No documentation available

The UriFormatter handles URIs from user-input and escaping.

uf = Gem::UriFormatter.new 'example.com'

p uf.normalize #=> 'http://example.com'

Random number formatter.

Formats generated random numbers in many manners. When 'random/formatter' is required, several methods are added to empty core module Random::Formatter, making them available as Random’s instance and module methods.

Standard library SecureRandom is also extended with the module, and the methods described below are available as a module methods in it.

Examples

Generate random hexadecimal strings:

require 'random/formatter'

prng = Random.new
prng.hex(10) #=> "52750b30ffbc7de3b362"
prng.hex(10) #=> "92b15d6c8dc4beb5f559"
prng.hex(13) #=> "39b290146bea6ce975c37cfc23"
# or just
Random.hex #=> "1aed0c631e41be7f77365415541052ee"

Generate random base64 strings:

prng.base64(10) #=> "EcmTPZwWRAozdA=="
prng.base64(10) #=> "KO1nIU+p9DKxGg=="
prng.base64(12) #=> "7kJSM/MzBJI+75j8"
Random.base64(4) #=> "bsQ3fQ=="

Generate random binary strings:

prng.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
prng.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
Random.random_bytes(6) #=> "\xA1\xE6Lr\xC43"

Generate alphanumeric strings:

prng.alphanumeric(10) #=> "S8baxMJnPl"
prng.alphanumeric(10) #=> "aOxAg8BAJe"
Random.alphanumeric #=> "TmP9OsJHJLtaZYhP"

Generate UUIDs:

prng.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
prng.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
Random.uuid #=> "f14e0271-de96-45cc-8911-8910292a42cd"

All methods are available in the standard library SecureRandom, too:

SecureRandom.hex #=> "05b45376a30c67238eb93b16499e50cf"

Generate a random number in the given range as Random does

prng.random_number       #=> 0.5816771641321361
prng.random_number(1000) #=> 485
prng.random_number(1..6) #=> 3
prng.rand                #=> 0.5816771641321361
prng.rand(1000)          #=> 485
prng.rand(1..6)          #=> 3
Search took: 7ms  ·  Total Results: 2422