Results for: "strip"

SystemCallError is the base class for all low-level platform-dependent errors.

The errors available on the current platform are subclasses of SystemCallError and are defined in the Errno module.

File.open("does/not/exist")

raises the exception:

Errno::ENOENT: No such file or directory - does/not/exist

IPSocket is the super class of TCPSocket and UDPSocket.

The Addrinfo class maps struct addrinfo to ruby. This structure identifies an Internet host and a service.

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

Example

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)

IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and IPv6 are supported.

Example

require 'ipaddr'

ipaddr1 = IPAddr.new "3ffe:505:2::1"

p ipaddr1                   #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>

p ipaddr1.to_s              #=> "3ffe:505:2::1"

ipaddr2 = ipaddr1.mask(48)  #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>

p ipaddr2.to_s              #=> "3ffe:505:2::"

ipaddr3 = IPAddr.new "192.168.2.0/24"

p ipaddr3                   #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>
No documentation available
No documentation available
No documentation available
No documentation available
No documentation available

This class implements a pretty printing algorithm. It finds line breaks and nice indentations for grouped structure.

By default, the class assumes that primitive elements are strings and each byte in the strings have single column in width. But it can be used for other situations by giving suitable arguments for some methods:

There are several candidate uses:

Bugs

Report any bugs at bugs.ruby-lang.org

References

Christian Lindig, Strictly Pretty, March 2000, www.st.cs.uni-sb.de/~lindig/papers/#pretty

Philip Wadler, A prettier printer, March 1998, homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier

Author

Tanaka Akira <akr@fsij.org>

The set of all prime numbers.

Example

Prime.each(100) do |prime|
  p prime  #=> 2, 3, 5, 7, 11, ...., 97
end

Prime is Enumerable:

Prime.first 5 # => [2, 3, 5, 7, 11]

Retrieving the instance

For convenience, each instance method of Prime.instance can be accessed as a class method of Prime.

e.g.

Prime.instance.prime?(2)  #=> true
Prime.prime?(2)           #=> true

Generators

A “generator” provides an implementation of enumerating pseudo-prime numbers and it remembers the position of enumeration and upper bound. Furthermore, it is an external iterator of prime enumeration which is compatible with an Enumerator.

Prime::PseudoPrimeGenerator is the base class for generators. There are few implementations of generator.

Prime::EratosthenesGenerator

Uses eratosthenes’ sieve.

Prime::TrialDivisionGenerator

Uses the trial division method.

Prime::Generator23

Generates all positive integers which are not divisible by either 2 or 3. This sequence is very bad as a pseudo-prime sequence. But this is faster and uses much less memory than the other generators. So, it is suitable for factorizing an integer which is not large but has many prime factors. e.g. for Prime#prime? .

PStore implements a file based persistence mechanism based on a Hash. User code can store hierarchies of Ruby objects (values) into the data store file by name (keys). An object hierarchy may be just a single object. User code may later read values back from the data store or even update data, as needed.

The transactional behavior ensures that any changes succeed or fail together. This can be used to ensure that the data store is not left in a transitory state, where some values were updated but others were not.

Behind the scenes, Ruby objects are stored to the data store file with Marshal. That carries the usual limitations. Proc objects cannot be marshalled, for example.

Usage example:

require "pstore"

# a mock wiki object...
class WikiPage
  def initialize( page_name, author, contents )
    @page_name = page_name
    @revisions = Array.new

    add_revision(author, contents)
  end

  attr_reader :page_name

  def add_revision( author, contents )
    @revisions << { :created  => Time.now,
                    :author   => author,
                    :contents => contents }
  end

  def wiki_page_references
    [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/)
  end

  # ...
end

# create a new page...
home_page = WikiPage.new( "HomePage", "James Edward Gray II",
                          "A page about the JoysOfDocumentation..." )

# then we want to update page data and the index together, or not at all...
wiki = PStore.new("wiki_pages.pstore")
wiki.transaction do  # begin transaction; do all of this or none of it
  # store page...
  wiki[home_page.page_name] = home_page
  # ensure that an index has been created...
  wiki[:wiki_index] ||= Array.new
  # update wiki index...
  wiki[:wiki_index].push(*home_page.wiki_page_references)
end                   # commit changes to wiki data store file

### Some time later... ###

# read wiki data...
wiki.transaction(true) do  # begin read-only transaction, no changes allowed
  wiki.roots.each do |data_root_name|
    p data_root_name
    p wiki[data_root_name]
  end
end

Transaction modes

By default, file integrity is only ensured as long as the operating system (and the underlying hardware) doesn’t raise any unexpected I/O errors. If an I/O error occurs while PStore is writing to its file, then the file will become corrupted.

You can prevent this by setting pstore.ultra_safe = true. However, this results in a minor performance loss, and only works on platforms that support atomic file renames. Please consult the documentation for ultra_safe for details.

Needless to say, if you’re storing valuable data with PStore, then you should backup the PStore files from time to time.

The global value true is the only instance of class TrueClass and represents a logically true value in boolean expressions. The class provides operators allowing true to be used in logical expressions.

A class that provides the functionality of Kernel#set_trace_func in a nice Object-Oriented API.

Example

We can use TracePoint to gather information specifically for exceptions:

trace = TracePoint.new(:raise) do |tp|
    p [tp.lineno, tp.event, tp.raised_exception]
end
#=> #<TracePoint:disabled>

trace.enable
#=> false

0 / 0
#=> [5, :raise, #<ZeroDivisionError: divided by 0>]

Events

If you don’t specify the type of events you want to listen for, TracePoint will include all available events.

Note do not depend on current event set, as this list is subject to change. Instead, it is recommended you specify the type of events you want to use.

To filter what is traced, you can pass any of the following as events:

:line

execute code on a new line

:class

start a class or module definition

:end

finish a class or module definition

:call

call a Ruby method

:return

return from a Ruby method

:c_call

call a C-language routine

:c_return

return from a C-language routine

:raise

raise an exception

:b_call

event hook at block entry

:b_return

event hook at block ending

:thread_begin

event hook at thread beginning

:thread_end

event hook at thread ending

:fiber_switch

event hook at fiber switch

ConditionVariable objects augment class Mutex. Using condition variables, it is possible to suspend while in the middle of a critical section until a resource becomes available.

Example:

mutex = Mutex.new
resource = ConditionVariable.new

a = Thread.new {
   mutex.synchronize {
     # Thread 'a' now needs the resource
     resource.wait(mutex)
     # 'a' can now have the resource
   }
}

b = Thread.new {
   mutex.synchronize {
     # Thread 'b' has finished using the resource
     resource.signal
   }
}

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.

Examples

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

RIPEMD-160

As Digest::RMD160. See homes.esat.kuleuven.be/~bosselae/ripemd160.html.

SHA1

See FIPS 180 Secure Hash Standard.

SHA2 family

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.

FileTest implements file test operations similar to those used in File::Stat. It exists as a standalone module, and its methods are also insinuated into the File class. (Note that this is not done by inclusion: the interpreter cheats).

URI

URI is a module providing classes to handle Uniform Resource Identifiers (RFC2396).

Features

Basic example

require 'uri'

uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
#=> #<URI::HTTP http://foo.com/posts?id=30&limit=5#time=1305298413>

uri.scheme    #=> "http"
uri.host      #=> "foo.com"
uri.path      #=> "/posts"
uri.query     #=> "id=30&limit=5"
uri.fragment  #=> "time=1305298413"

uri.to_s      #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"

Adding custom URIs

module URI
  class RSYNC < Generic
    DEFAULT_PORT = 873
  end
  @@schemes['RSYNC'] = RSYNC
end
#=> URI::RSYNC

URI.scheme_list
#=> {"FILE"=>URI::File, "FTP"=>URI::FTP, "HTTP"=>URI::HTTP,
#    "HTTPS"=>URI::HTTPS, "LDAP"=>URI::LDAP, "LDAPS"=>URI::LDAPS,
#    "MAILTO"=>URI::MailTo, "RSYNC"=>URI::RSYNC}

uri = URI("rsync://rsync.foo.com")
#=> #<URI::RSYNC rsync://rsync.foo.com>

RFC References

A good place to view an RFC spec is www.ietf.org/rfc.html.

Here is a list of all related RFC’s:

Class tree

Copyright Info

Author

Akira Yamada <akira@ruby-lang.org>

Documentation

Akira Yamada <akira@ruby-lang.org> Dmitry V. Sabanin <sdmitry@lrn.ru> Vincent Batts <vbatts@hashbangbash.com>

License

Copyright © 2001 akira yamada <akira@ruby-lang.org> You can redistribute it and/or modify it under the same term as Ruby.

Revision

$Id: uri.rb 63228 2018-04-21 20:04:05Z stomar $

OpenURI is an easy-to-use wrapper for Net::HTTP, Net::HTTPS and Net::FTP.

Example

It is possible to open an http, https or ftp URL as though it were a file:

open("http://www.ruby-lang.org/") {|f|
  f.each_line {|line| p line}
}

The opened file has several getter methods for its meta-information, as follows, since it is extended by OpenURI::Meta.

open("http://www.ruby-lang.org/en") {|f|
  f.each_line {|line| p line}
  p f.base_uri         # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/>
  p f.content_type     # "text/html"
  p f.charset          # "iso-8859-1"
  p f.content_encoding # []
  p f.last_modified    # Thu Dec 05 02:45:02 UTC 2002
}

Additional header fields can be specified by an optional hash argument.

open("http://www.ruby-lang.org/en/",
  "User-Agent" => "Ruby/#{RUBY_VERSION}",
  "From" => "foo@bar.invalid",
  "Referer" => "http://www.ruby-lang.org/") {|f|
  # ...
}

The environment variables such as http_proxy, https_proxy and ftp_proxy are in effect by default. Here we disable proxy:

open("http://www.ruby-lang.org/en/", :proxy => nil) {|f|
  # ...
}

See OpenURI::OpenRead.open and Kernel#open for more on available options.

URI objects can be opened in a similar way.

uri = URI.parse("http://www.ruby-lang.org/en/")
uri.open {|f|
  # ...
}

URI objects can be read directly. The returned string is also extended by OpenURI::Meta.

str = uri.read
p str.base_uri
Author

Tanaka Akira <akr@m17n.org>

A module to implement the Linda distributed computing paradigm in Ruby.

Rinda is part of DRb (dRuby).

Example(s)

See the sample/drb/ directory in the Ruby distribution, from 1.8.2 onwards.

WEB server toolkit.

WEBrick is an HTTP server toolkit that can be configured as an HTTPS server, a proxy server, and a virtual-host server. WEBrick features complete logging of both server operations and HTTP access. WEBrick supports both basic and digest authentication in addition to algorithms not in RFC 2617.

A WEBrick server can be composed of multiple WEBrick servers or servlets to provide differing behavior on a per-host or per-path basis. WEBrick includes servlets for handling CGI scripts, ERB pages, Ruby blocks and directory listings.

WEBrick also includes tools for daemonizing a process and starting a process at a higher privilege level and dropping permissions.

Starting an HTTP server

To create a new WEBrick::HTTPServer that will listen to connections on port 8000 and serve documents from the current user’s public_html folder:

require 'webrick'

root = File.expand_path '~/public_html'
server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => root

To run the server you will need to provide a suitable shutdown hook as starting the server blocks the current thread:

trap 'INT' do server.shutdown end

server.start

Custom Behavior

The easiest way to have a server perform custom operations is through WEBrick::HTTPServer#mount_proc. The block given will be called with a WEBrick::HTTPRequest with request info and a WEBrick::HTTPResponse which must be filled in appropriately:

server.mount_proc '/' do |req, res|
  res.body = 'Hello, world!'
end

Remember that server.mount_proc must precede server.start.

Servlets

Advanced custom behavior can be obtained through mounting a subclass of WEBrick::HTTPServlet::AbstractServlet. Servlets provide more modularity when writing an HTTP server than mount_proc allows. Here is a simple servlet:

class Simple < WEBrick::HTTPServlet::AbstractServlet
  def do_GET request, response
    status, content_type, body = do_stuff_with request

    response.status = 200
    response['Content-Type'] = 'text/plain'
    response.body = 'Hello, World!'
  end
end

To initialize the servlet you mount it on the server:

server.mount '/simple', Simple

See WEBrick::HTTPServlet::AbstractServlet for more details.

Virtual Hosts

A server can act as a virtual host for multiple host names. After creating the listening host, additional hosts that do not listen can be created and attached as virtual hosts:

server = WEBrick::HTTPServer.new # ...

vhost = WEBrick::HTTPServer.new :ServerName => 'vhost.example',
                                :DoNotListen => true, # ...
vhost.mount '/', ...

server.virtual_host vhost

If no :DocumentRoot is provided and no servlets or procs are mounted on the main server it will return 404 for all URLs.

HTTPS

To create an HTTPS server you only need to enable SSL and provide an SSL certificate name:

require 'webrick'
require 'webrick/https'

cert_name = [
  %w[CN localhost],
]

server = WEBrick::HTTPServer.new(:Port => 8000,
                                 :SSLEnable => true,
                                 :SSLCertName => cert_name)

This will start the server with a self-generated self-signed certificate. The certificate will be changed every time the server is restarted.

To create a server with a pre-determined key and certificate you can provide them:

require 'webrick'
require 'webrick/https'
require 'openssl'

cert = OpenSSL::X509::Certificate.new File.read '/path/to/cert.pem'
pkey = OpenSSL::PKey::RSA.new File.read '/path/to/pkey.pem'

server = WEBrick::HTTPServer.new(:Port => 8000,
                                 :SSLEnable => true,
                                 :SSLCertificate => cert,
                                 :SSLPrivateKey => pkey)

Proxy Server

WEBrick can act as a proxy server:

require 'webrick'
require 'webrick/httpproxy'

proxy = WEBrick::HTTPProxyServer.new :Port => 8000

trap 'INT' do proxy.shutdown end

See WEBrick::HTTPProxy for further details including modifying proxied responses.

Basic and Digest authentication

WEBrick provides both Basic and Digest authentication for regular and proxy servers. See WEBrick::HTTPAuth, WEBrick::HTTPAuth::BasicAuth and WEBrick::HTTPAuth::DigestAuth.

WEBrick as a Production Web Server

WEBrick can be run as a production server for small loads.

Daemonizing

To start a WEBrick server as a daemon simple run WEBrick::Daemon.start before starting the server.

Dropping Permissions

WEBrick can be started as one user to gain permission to bind to port 80 or 443 for serving HTTP or HTTPS traffic then can drop these permissions for regular operation. To listen on all interfaces for HTTP traffic:

sockets = WEBrick::Utils.create_listeners nil, 80

Then drop privileges:

WEBrick::Utils.su 'www'

Then create a server that does not listen by default:

server = WEBrick::HTTPServer.new :DoNotListen => true, # ...

Then overwrite the listening sockets with the port 80 sockets:

server.listeners.replace sockets

Logging

WEBrick can separately log server operations and end-user access. For server operations:

log_file = File.open '/var/log/webrick.log', 'a+'
log = WEBrick::Log.new log_file

For user access logging:

access_log = [
  [log_file, WEBrick::AccessLog::COMBINED_LOG_FORMAT],
]

server = WEBrick::HTTPServer.new :Logger => log, :AccessLog => access_log

See WEBrick::AccessLog for further log formats.

Log Rotation

To rotate logs in WEBrick on a HUP signal (like syslogd can send), open the log file in ‘a+’ mode (as above) and trap ‘HUP’ to reopen the log file:

trap 'HUP' do log_file.reopen '/path/to/webrick.log', 'a+'

Author: IPR – Internet Programming with Ruby – writers

Copyright © 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU Copyright © 2002 Internet Programming with Ruby writers. All rights reserved.

No documentation available
No documentation available
No documentation available
Search took: 8ms  ·  Total Results: 1841