Raised in case of a stack overflow.
def me_myself_and_i me_myself_and_i end me_myself_and_i
raises the exception:
SystemStackError: stack level too deep
Mixin methods for local and remote Gem::Command
options.
Coverage
provides coverage measurement feature for Ruby. This feature is experimental, so these APIs may be changed in future.
Caveat: Currently, only process-global coverage measurement is supported. You cannot measure per-thread coverage.
require “coverage”
require or load Ruby source file
Coverage.result
will return a hash that contains filename as key and coverage array as value. A coverage array gives, for each line, the number of line execution by the interpreter. A nil
value means coverage is disabled for this line (lines like else
and end
).
[foo.rb] s = 0 10.times do |x| s += x end if s == 45 p :ok else p :ng end [EOF] require "coverage" Coverage.start require "foo.rb" p Coverage.result #=> {"foo.rb"=>[1, 1, 10, nil, nil, 1, 1, nil, 0, nil]}
Coverage
If a coverage mode is not explicitly specified when starting coverage, lines coverage is what will run. It reports the number of line executions for each line.
require "coverage" Coverage.start(lines: true) require "foo.rb" p Coverage.result #=> {"foo.rb"=>{:lines=>[1, 1, 10, nil, nil, 1, 1, nil, 0, nil]}}
The value of the lines coverage result is an array containing how many times each line was executed. Order in this array is important. For example, the first item in this array, at index 0, reports how many times line 1 of this file was executed while coverage was run (which, in this example, is one time).
A nil
value means coverage is disabled for this line (lines like else
and end
).
Coverage
Oneshot lines coverage tracks and reports on the executed lines while coverage is running. It will not report how many times a line was executed, only that it was executed.
require "coverage" Coverage.start(oneshot_lines: true) require "foo.rb" p Coverage.result #=> {"foo.rb"=>{:oneshot_lines=>[1, 2, 3, 6, 7]}}
The value of the oneshot lines coverage result is an array containing the line numbers that were executed.
Coverage
Branches coverage reports how many times each branch within each conditional was executed.
require "coverage" Coverage.start(branches: true) require "foo.rb" p Coverage.result #=> {"foo.rb"=>{:branches=>{[:if, 0, 6, 0, 10, 3]=>{[:then, 1, 7, 2, 7, 7]=>1, [:else, 2, 9, 2, 9, 7]=>0}}}}
Each entry within the branches hash is a conditional, the value of which is another hash where each entry is a branch in that conditional. The values are the number of times the method was executed, and the keys are identifying information about the branch.
The information that makes up each key identifying branches or conditionals is the following, from left to right:
A label for the type of branch or conditional.
A unique identifier.
The starting line number it appears on in the file.
The starting column number it appears on in the file.
The ending line number it appears on in the file.
The ending column number it appears on in the file.
Coverage
Methods coverage reports how many times each method was executed.
[foo_method.rb] class Greeter def greet "welcome!" end end def hello "Hi" end hello() Greeter.new.greet() [EOF] require "coverage" Coverage.start(methods: true) require "foo_method.rb" p Coverage.result #=> {"foo_method.rb"=>{:methods=>{[Object, :hello, 7, 0, 9, 3]=>1, [Greeter, :greet, 2, 2, 4, 5]=>1}}}
Each entry within the methods hash represents a method. The values in this hash are the number of times the method was executed, and the keys are identifying information about the method.
The information that makes up each key identifying a method is the following, from left to right:
The class.
The method name.
The starting line number the method appears on in the file.
The starting column number the method appears on in the file.
The ending line number the method appears on in the file.
The ending column number the method appears on in the file.
Coverage
Modes You can also run all modes of coverage simultaneously with this shortcut. Note that running all coverage modes does not run both lines and oneshot lines. Those modes cannot be run simultaneously. Lines coverage is run in this case, because you can still use it to determine whether or not a line was executed.
require "coverage" Coverage.start(:all) require "foo.rb" p Coverage.result #=> {"foo.rb"=>{:lines=>[1, 1, 10, nil, nil, 1, 1, nil, 0, nil], :branches=>{[:if, 0, 6, 0, 10, 3]=>{[:then, 1, 7, 2, 7, 7]=>1, [:else, 2, 9, 2, 9, 7]=>0}}, :methods=>{}}}
Response class for Precondition Failed
responses (status code 412).
The server does not meet one of the preconditions specified in the request headers. See 412 Precondition Failed.
Turns a “invalid block(s)” into useful context
There are three main phases in the algorithm:
Sanitize/format input source
Search for invalid blocks
Format invalid blocks into something meaninful
This class handles the third part.
The algorithm is very good at capturing all of a syntax error in a single block in number 2, however the results can contain ambiguities. Humans are good at pattern matching and filtering and can mentally remove extraneous data, but they can’t add extra data that’s not present.
In the case of known ambiguious cases, this class adds context back to the ambiguitiy so the programmer has full information.
Beyond handling these ambiguities, it also captures surrounding code context information:
puts block.to_s # => "def bark" context = CaptureCodeContext.new( blocks: block, code_lines: code_lines ) lines = context.call.map(&:original) puts lines.join # => class Dog def bark end
Represents an error communicating via HTTP.
Raised by exit
to initiate the termination of the script.
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
Use the Monitor
class when you want to have a lock object for blocks with mutual exclusion.
require 'monitor' lock = Monitor.new lock.synchronize do # exclusive access end
PStore implements a file based persistence mechanism based on a Hash
. User code can store hierarchies of Ruby objects (values) into the data store 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.
There are three important concepts here (details at the links):
Store: a store is an instance of PStore.
Entries: the store is hash-like; each entry is the key for a stored object.
Transactions: each transaction is a collection of prospective changes to the store; a transaction is defined in the block given with a call to PStore#transaction
.
Examples on this page need a store that has known properties. They can get a new (and populated) store by calling thus:
example_store do |store| # Example code using store goes here. end
All we really need to know about example_store
is that it yields a fresh store with a known population of entries; its implementation:
require 'pstore' require 'tempfile' # Yield a pristine store for use in examples. def example_store # Create the store in a temporary file. Tempfile.create do |file| store = PStore.new(file) # Populate the store. store.transaction do store[:foo] = 0 store[:bar] = 1 store[:baz] = 2 end yield store end end
The contents of the store are maintained in a file whose path is specified when the store is created (see PStore.new
). The objects are stored and retrieved using module Marshal
, which means that certain objects cannot be added to the store; see Marshal::dump.
A store may have any number of entries. Each entry has a key and a value, just as in a hash:
Key: as in a hash, the key can be (almost) any object; see Hash Keys. You may find it convenient to keep it simple by using only symbols or strings as keys.
Value: the value may be any object that can be marshalled by Marshal (see Marshal::dump) and in fact may be a collection (e.g., an array, a hash, a set, a range, etc). That collection may in turn contain nested objects, including collections, to any depth; those objects must also be Marshal-able. See Hierarchical Values.
The block given with a call to method transaction
# contains a transaction, which consists of calls to PStore methods that read from or write to the store (that is, all PStore methods except transaction
itself, path
, and Pstore.new):
example_store do |store| store.transaction do store.keys # => [:foo, :bar, :baz] store[:bat] = 3 store.keys # => [:foo, :bar, :baz, :bat] end end
Execution of the transaction is deferred until the block exits, and is executed atomically (all-or-nothing): either all transaction calls are executed, or none are. This maintains the integrity of the store.
Other code in the block (including even calls to path
and PStore.new
) is executed immediately, not deferred.
The transaction block:
May not contain a nested call to transaction
.
Is the only context where methods that read from or write to the store are allowed.
As seen above, changes in a transaction are made automatically when the block exits. The block may be exited early by calling method commit
or abort
.
Method
commit
triggers the update to the store and exits the block:
example_store do |store| store.transaction do store.keys # => [:foo, :bar, :baz] store[:bat] = 3 store.commit fail 'Cannot get here' end store.transaction do # Update was completed. store.keys # => [:foo, :bar, :baz, :bat] end end
Method
abort
discards the update to the store and exits the block:
example_store do |store| store.transaction do store.keys # => [:foo, :bar, :baz] store[:bat] = 3 store.abort fail 'Cannot get here' end store.transaction do # Update was not completed. store.keys # => [:foo, :bar, :baz] end end
By default, a transaction allows both reading from and writing to the store:
store.transaction do # Read-write transaction. # Any code except a call to #transaction is allowed here. end
If argument read_only
is passed as true
, only reading is allowed:
store.transaction(true) do # Read-only transaction: # Calls to #transaction, #[]=, and #delete are not allowed here. end
The value for an entry may be a simple object (as seen above). It may also be a hierarchy of objects nested to any depth:
deep_store = PStore.new('deep.store') deep_store.transaction do array_of_hashes = [{}, {}, {}] deep_store[:array_of_hashes] = array_of_hashes deep_store[:array_of_hashes] # => [{}, {}, {}] hash_of_arrays = {foo: [], bar: [], baz: []} deep_store[:hash_of_arrays] = hash_of_arrays deep_store[:hash_of_arrays] # => {:foo=>[], :bar=>[], :baz=>[]} deep_store[:hash_of_arrays][:foo].push(:bat) deep_store[:hash_of_arrays] # => {:foo=>[:bat], :bar=>[], :baz=>[]} end
And recall that you can use dig methods in a returned hierarchy of objects.
Use method PStore.new
to create a store. The new store creates or opens its containing file:
store = PStore.new('t.store')
Use method []=
to update or create an entry:
example_store do |store| store.transaction do store[:foo] = 1 # Update. store[:bam] = 1 # Create. end end
Use method delete
to remove an entry:
example_store do |store| store.transaction do store.delete(:foo) store[:foo] # => nil end end
Use method fetch
(allows default) or []
(defaults to nil
) to retrieve an entry:
example_store do |store| store.transaction do store[:foo] # => 0 store[:nope] # => nil store.fetch(:baz) # => 2 store.fetch(:nope, nil) # => nil store.fetch(:nope) # Raises exception. end end
Use method key?
to determine whether a given key exists:
example_store do |store| store.transaction do store.key?(:foo) # => true end end
Use method keys
to retrieve keys:
example_store do |store| store.transaction do store.keys # => [:foo, :bar, :baz] end end
Use method path
to retrieve the path to the store’s underlying file; this method may be called from outside a transaction block:
store = PStore.new('t.store') store.path # => "t.store"
For transaction safety, see:
Optional argument thread_safe
at method PStore.new
.
Attribute ultra_safe
.
Needless to say, if you’re storing valuable data with PStore, then you should backup the PStore file from time to time.
require "pstore" # A mock wiki object. class WikiPage attr_reader :page_name def initialize(page_name, author, contents) @page_name = page_name @revisions = Array.new add_revision(author, contents) end 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 wiki page. home_page = WikiPage.new("HomePage", "James Edward Gray II", "A page about the JoysOfDocumentation..." ) wiki = PStore.new("wiki_pages.pstore") # Update page data and the index together, or not at all. wiki.transaction do # Store page. wiki[home_page.page_name] = home_page # Create page index. wiki[:wiki_index] ||= Array.new # Update wiki index. wiki[:wiki_index].push(*home_page.wiki_page_references) end # Read wiki data, setting argument read_only to true. wiki.transaction(true) do wiki.keys.each do |key| puts key puts wiki[key] end end
Note: Don’t use this class directly. This is an internal class.
This class is the base class for Net::HTTP request classes.
Method Net::HTTP.get_response
returns an instance of one of the subclasses of Net::HTTPResponse:
Net::HTTP.get_response(uri) # => #<Net::HTTPOK 200 OK readbody=true> Net::HTTP.get_response(hostname, '/nosuch') # => #<Net::HTTPNotFound 404 Not Found readbody=true>
As does method Net::HTTP#request
:
req = Net::HTTP::Get.new(uri) Net::HTTP.start(hostname) do |http| http.request(req) end # => #<Net::HTTPOK 200 OK readbody=true>
Class Net::HTTPResponse includes module Net::HTTPHeader
, which provides access to response header values via (among others):
Hash-like method []
.
Specific reader methods, such as content_type
.
Examples:
res = Net::HTTP.get_response(uri) # => #<Net::HTTPOK 200 OK readbody=true> res['Content-Type'] # => "text/html; charset=UTF-8" res.content_type # => "text/html"
Class Net::HTTPResponse has a subclass for each HTTP status code. You can look up the response class for a given code:
Net::HTTPResponse::CODE_TO_OBJ['200'] # => Net::HTTPOK Net::HTTPResponse::CODE_TO_OBJ['400'] # => Net::HTTPBadRequest Net::HTTPResponse::CODE_TO_OBJ['404'] # => Net::HTTPNotFound
And you can retrieve the status code for a response object:
Net::HTTP.get_response(uri).code # => "200" Net::HTTP.get_response(hostname, '/nosuch').code # => "404"
The response subclasses (indentation shows class hierarchy):
Net::HTTPUnknownResponse
(for unhandled HTTP extensions).
Net::HTTPContinue
(100)
Net::HTTPSwitchProtocol
(101)
Net::HTTPProcessing
(102)
Net::HTTPEarlyHints
(103)
Net::HTTPOK
(200)
Net::HTTPCreated
(201)
Net::HTTPAccepted
(202)
Net::HTTPNoContent
(204)
Net::HTTPResetContent
(205)
Net::HTTPPartialContent
(206)
Net::HTTPMultiStatus
(207)
Net::HTTPAlreadyReported
(208)
Net::HTTPIMUsed
(226)
Net::HTTPMultipleChoices
(300)
Net::HTTPFound
(302)
Net::HTTPSeeOther
(303)
Net::HTTPNotModified
(304)
Net::HTTPUseProxy
(305)
Net::HTTPBadRequest
(400)
Net::HTTPUnauthorized
(401)
Net::HTTPPaymentRequired
(402)
Net::HTTPForbidden
(403)
Net::HTTPNotFound
(404)
Net::HTTPNotAcceptable
(406)
Net::HTTPRequestTimeOut
(408)
Net::HTTPConflict
(409)
Net::HTTPGone
(410)
Net::HTTPLengthRequired
(411)
Net::HTTPLocked
(423)
Net::HTTPUpgradeRequired
(426)
Net::HTTPTooManyRequests
(429)
Net::HTTPNotImplemented
(501)
Net::HTTPBadGateway
(502)
Net::HTTPGatewayTimeOut
(504)
Net::HTTPLoopDetected
(508)
Net::HTTPNotExtended
(510)
There is also the Net::HTTPBadResponse exception which is raised when there is a protocol error.
Response class for Non-Authoritative Information
responses (status code 203).
The Non-Authoritative Information
response indicates that the server is a transforming proxy (such as a Web accelerator) that received a 200 OK response from its origin, and is returning a modified version of the origin’s response. See 203 Non-Authoritative Information.
Response class for Reset Content
responses (status code 205).
The Reset Content
response indicates that the server successfully processed the request, asks that the client reset its document view, and is not returning any content. See 205 Reset Content.
Response class for URI Too Long
responses (status code 414).
The URI
provided was too long for the server to process. See 414 URI Too Long.
Response class for Request Header Fields Too Large
responses (status code 431).
An individual header field is too large, or all the header fields collectively, are too large. See 431 Request Header Fields Too Large.
Response class for Unavailable For Legal Reasons
responses (status code 451).
A server operator has received a legal demand to deny access to a resource or to a set of resources that includes the requested resource. See 451 Unavailable For Legal Reasons.