repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal-builder.rb | stdlib/opal-builder.rb | require 'opal/builder'
require 'opal/builder/processor'
require 'corelib/string/unpack'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/json.rb | stdlib/json.rb | # backtick_javascript: true
module JSON
class JSONError < StandardError
end
class ParserError < JSONError
end
%x{
var $hasOwn = Opal.hasOwnProperty;
function $parse(source) {
try {
return JSON.parse(source);
} catch (e) {
#{raise JSON::ParserError, `e.message`};
}
};
function to_opal(value, options) {
var klass, arr, hash, i, ii, k;
switch (typeof value) {
case 'string':
return value;
case 'number':
return value;
case 'boolean':
return !!value;
case 'undefined':
return nil;
case 'object':
if (!value) return nil;
if (value.$$is_array) {
arr = #{`Opal.hash_get(options, 'array_class')`.new};
for (i = 0, ii = value.length; i < ii; i++) {
#{`arr`.push(`to_opal(value[i], options)`)};
}
return arr;
}
else {
hash = #{`Opal.hash_get(options, 'object_class')`.new};
for (k in value) {
if ($hasOwn.call(value, k)) {
#{`hash`[`k`] = `to_opal(value[k], options)`};
}
}
if (!Opal.hash_get(options, 'parse') && (klass = #{`hash`[JSON.create_id]}) != nil) {
return #{::Object.const_get(`klass`).json_create(`hash`)};
}
else {
return hash;
}
}
}
};
}
class << self
attr_accessor :create_id
end
self.create_id = :json_class
def self.[](value, options = {})
if String === value
parse(value, options)
else
generate(value, options)
end
end
def self.parse(source, options = {})
from_object(`$parse(source)`, options.merge(parse: true))
end
def self.parse!(source, options = {})
parse(source, options)
end
def self.load(source, options = {})
from_object(`$parse(source)`, options)
end
# Raw js object => opal object
def self.from_object(js_object, options = {})
options[:object_class] ||= Hash
options[:array_class] ||= Array
`to_opal(js_object, options)`
end
def self.generate(obj, options = {})
obj.to_json(options)
end
def self.dump(obj, io = nil, limit = nil)
string = generate(obj)
if io
io = io.to_io if io.responds_to? :to_io
io.write string
io
else
string
end
end
end
class Object
def to_json
to_s.to_json
end
end
# BUG: Enumerable must come before Array, otherwise it overrides #to_json
# this is due to how modules are implemented.
module Enumerable
def to_json
to_a.to_json
end
end
class Array
def to_json
%x{
var result = [];
for (var i = 0, length = #{self}.length; i < length; i++) {
result.push(#{`self[i]`.to_json});
}
return '[' + result.join(',') + ']';
}
end
end
class Boolean
def to_json
`(self == true) ? 'true' : 'false'`
end
end
class Hash
def to_json
%x{
var result = [];
Opal.hash_each(self, false, function(key, value) {
result.push(#{`key`.to_s.to_json} + ':' + #{`value`.to_json});
return [false, false];
});
return '{' + result.join(',') + '}';
}
end
end
class NilClass
def to_json
'null'
end
end
class Numeric
def to_json
`self.toString()`
end
end
class String
def to_json
`JSON.stringify(self)`
end
end
class Time
def to_json
strftime('%FT%T%z').to_json
end
end
class Date
def to_json
to_s.to_json
end
def as_json
to_s
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/strscan.rb | stdlib/strscan.rb | # backtick_javascript: true
class StringScanner
attr_reader :pos, :matched
def initialize(string)
@string = string
@pos = 0
@matched = nil
@working = string
@match = []
end
attr_reader :string
def beginning_of_line?
`#{@pos} === 0 || #{@string}.charAt(#{@pos} - 1) === "\n"`
end
def scan(pattern)
pattern = anchor(pattern)
%x{
var result = pattern.exec(#{@working});
if (result == null) {
return #{@matched} = nil;
}
#{@prev_pos} = #{@pos};
#{@pos} += result[0].length;
#{@working} = #{@working}.substring(result[0].length);
#{@matched} = result[0];
#{@match} = result;
return result[0];
}
end
def scan_until(pattern)
pattern = anchor(pattern)
%x{
var working = #{@working}
for(var i = 0; working.length != i; ++i) {
var result = pattern.exec(working.substr(i));
if (result !== null) {
var matched_size = i + result[0].length
var matched = working.substr(0, matched_size)
#{@matched} = result[0]
#{@match} = result
#{@prev_pos} = #{@pos} + i; // Position of first character of matched
#{@pos} += matched_size // Position one after last character of matched
#{@working} = working.substr(matched_size)
return matched
}
}
return #{@matched} = nil;
}
end
def [](idx)
if @match.empty?
return nil
end
case idx
when Symbol
idx = idx.to_s
when String
# noop
else
idx = ::Opal.coerce_to!(idx, Integer, :to_int)
end
%x{
var match = #{@match};
if (idx < 0) {
idx += match.length;
}
if (idx < 0 || idx >= match.length) {
return nil;
}
if (match[idx] == null) {
return nil;
}
return match[idx];
}
end
def check(pattern)
pattern = anchor(pattern)
%x{
var result = pattern.exec(#{@working});
if (result == null) {
return #{@matched} = nil;
}
return #{@matched} = result[0];
}
end
def check_until(pattern)
%x{
var old_prev_pos = #{@prev_pos};
var old_pos = #{@pos};
var old_working = #{@working};
var result = #{scan_until(pattern)};
#{@prev_pos} = old_prev_pos;
#{@pos} = old_pos;
#{@working} = old_working;
return result;
}
end
def peek(length)
`#{@working}.substring(0, length)`
end
def eos?
`#{@working}.length === 0`
end
def exist?(pattern)
%x{
var result = pattern.exec(#{@working});
if (result == null) {
return nil;
}
else if (result.index == 0) {
return 0;
}
else {
return result.index + 1;
}
}
end
def skip(pattern)
pattern = anchor(pattern)
%x{
var result = pattern.exec(#{@working});
if (result == null) {
#{@match} = [];
return #{@matched} = nil;
}
else {
var match_str = result[0];
var match_len = match_str.length;
#{@matched} = match_str;
#{@match} = result;
#{@prev_pos} = #{@pos};
#{@pos} += match_len;
#{@working} = #{@working}.substring(match_len);
return match_len;
}
}
end
def skip_until(pattern)
%x{
var result = #{scan_until(pattern)};
if (result === nil) {
return nil;
}
else {
#{@matched} = result.substr(-1);
return result.length;
}
}
end
def get_byte
%x{
var result = nil;
if (#{@pos} < #{@string}.length) {
#{@prev_pos} = #{@pos};
#{@pos} += 1;
result = #{@matched} = #{@working}.substring(0, 1);
#{@working} = #{@working}.substring(1);
}
else {
#{@matched} = nil;
}
return result;
}
end
def match?(pattern)
pattern = anchor(pattern)
%x{
var result = pattern.exec(#{@working});
if (result == null) {
return nil;
}
else {
#{@prev_pos} = #{@pos};
return result[0].length;
}
}
end
def pos=(pos)
%x{
if (pos < 0) {
pos += #{@string.length};
}
}
@pos = pos
@working = `#{@string}.slice(pos)`
end
def matched_size
%x{
if (#{@matched} === nil) {
return nil;
}
return #{@matched}.length
}
end
def post_match
%x{
if (#{@matched} === nil) {
return nil;
}
return #{@string}.substr(#{@pos});
}
end
def pre_match
%x{
if (#{@matched} === nil) {
return nil;
}
return #{@string}.substr(0, #{@prev_pos});
}
end
def reset
@working = @string
@matched = nil
@pos = 0
end
def rest
@working
end
def rest?
`#{@working}.length !== 0`
end
def rest_size
rest.size
end
def terminate
@match = nil
self.pos = @string.length
end
def unscan
@pos = @prev_pos
@prev_pos = nil
@match = nil
self
end
alias bol? beginning_of_line?
alias getch get_byte # not exactly the same, but for now...
private
def anchor(pattern)
%x{
var flags = pattern.toString().match(/\/([^\/]+)$/);
flags = flags ? flags[1] : undefined;
return new RegExp('^(?:' + pattern.source + ')', flags);
}
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/encoding.rb | stdlib/encoding.rb | warn 'DEPRECATION: encoding is now part of the core library, requiring it is deprecated'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/base64.rb | stdlib/base64.rb | # backtick_javascript: true
module Base64
# FROM https://github.com/davidchambers/Base64.js/blob/69262ec7e1fa4541de5700a1b0b03b0de0e3f5aa/base64.js
%x{
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var encode, decode;
// encoder
// [https://gist.github.com/999166] by [https://github.com/nignag]
encode = function (input) {
var str = String(input);
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars, output = '';
// if the next str index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
str.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = str.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
#{raise ArgumentError, 'invalid character (failed: The string to be encoded contains characters outside of the Latin1 range.)'};
}
block = block << 8 | charCode;
}
return output;
};
// decoder
// [https://gist.github.com/1020396] by [https://github.com/atk]
decode = function (input) {
var str = String(input).replace(/=+$/, '');
if (str.length % 4 == 1) {
#{raise ArgumentError, 'invalid base64 (failed: The string to be decoded is not correctly encoded.)'};
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
};
}
def self.decode64(string)
`decode(string.replace(/\r?\n/g, ''))`
end
def self.encode64(string)
`encode(string).replace(/(.{60})/g, "$1\n").replace(/([^\n])$/g, "$1\n")`
end
def self.strict_decode64(string)
`decode(string)`
end
def self.strict_encode64(string)
`encode(string)`
end
def self.urlsafe_decode64(string)
`decode(string.replace(/\-/g, '+').replace(/_/g, '/'))`
end
def self.urlsafe_encode64(string, padding: true)
str = `encode(string).replace(/\+/g, '-').replace(/\//g, '_')`
str = str.delete('=') unless padding
str
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/enumerator.rb | stdlib/enumerator.rb | # stub
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/dir.rb | stdlib/dir.rb | warn "Dir is already part of corelib now, you don't need to require it anymore."
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/uri.rb | stdlib/uri.rb | # backtick_javascript: true
# frozen_string_literal: true
module URI
def self.decode_www_form(str, enc = undefined, separator: '&', use__charset_: false, isindex: false)
raise ArgumentError, "the input of #{name}.#{__method__} must be ASCII only string" unless str.ascii_only?
%x{
var ary = [], key, val;
if (str.length == 0)
return ary;
if (enc)
#{enc = Encoding.find(enc)};
var parts = str.split(#{separator});
for (var i = 0; i < parts.length; i++) {
var string = parts[i];
var splitIndex = string.indexOf('=')
if (splitIndex >= 0) {
key = string.substr(0, splitIndex);
val = string.substr(splitIndex + 1);
} else {
key = string;
val = '';
}
if (isindex) {
if (splitIndex < 0) {
key = '';
val = string;
}
isindex = false;
}
key = decodeURIComponent(key.replace(/\+/g, ' '));
if (val) {
val = decodeURIComponent(val.replace(/\+/g, ' '));
} else {
val = '';
}
if (enc) {
key = #{`key`.force_encoding(enc)}
val = #{`val`.force_encoding(enc)}
}
ary.push([key, val]);
}
return ary;
}
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs.rb | stdlib/nodejs.rb | require 'nodejs/base'
require 'nodejs/kernel'
require 'nodejs/process'
require 'nodejs/file'
require 'nodejs/dir'
require 'nodejs/io'
require 'nodejs/argf'
require 'nodejs/open-uri'
require 'nodejs/pathname'
require 'nodejs/env'
require 'nodejs/opal-paths'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/headless_browser.rb | stdlib/headless_browser.rb | # frozen_string_literal: true
# backtick_javascript: true
require 'headless_browser/base'
require 'headless_browser/file'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/matrix.rb | stdlib/matrix.rb | # encoding: utf-8
# frozen_string_literal: false
#
# = matrix.rb
#
# An implementation of Matrix and Vector classes.
#
# See classes Matrix and Vector for documentation.
#
# Current Maintainer:: Marc-André Lafortune
# Original Author:: Keiju ISHITSUKA
# Original Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly))
##
require "e2mmap.rb"
module ExceptionForMatrix # :nodoc:
extend Exception2MessageMapper
def_e2message(TypeError, "wrong argument type %s (expected %s)")
def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
def_exception("ErrNotRegular", "Not Regular Matrix")
def_exception("ErrOperationNotDefined", "Operation(%s) can\\'t be defined: %s op %s")
def_exception("ErrOperationNotImplemented", "Sorry, Operation(%s) not implemented: %s op %s")
end
#
# The +Matrix+ class represents a mathematical matrix. It provides methods for creating
# matrices, operating on them arithmetically and algebraically,
# and determining their mathematical properties such as trace, rank, inverse, determinant,
# or eigensystem.
#
class Matrix
include Enumerable
include ExceptionForMatrix
autoload :EigenvalueDecomposition, "matrix/eigenvalue_decomposition"
autoload :LUPDecomposition, "matrix/lup_decomposition"
# instance creations
private_class_method :new
attr_reader :rows
protected :rows
#
# Creates a matrix where each argument is a row.
# Matrix[ [25, 93], [-1, 66] ]
# => 25 93
# -1 66
#
def Matrix.[](*rows)
rows(rows, false)
end
#
# Creates a matrix where +rows+ is an array of arrays, each of which is a row
# of the matrix. If the optional argument +copy+ is false, use the given
# arrays as the internal structure of the matrix without copying.
# Matrix.rows([[25, 93], [-1, 66]])
# => 25 93
# -1 66
#
def Matrix.rows(rows, copy = true)
rows = convert_to_array(rows, copy)
rows.map! do |row|
convert_to_array(row, copy)
end
size = (rows[0] || []).size
rows.each do |row|
raise ErrDimensionMismatch, "row size differs (#{row.size} should be #{size})" unless row.size == size
end
new rows, size
end
#
# Creates a matrix using +columns+ as an array of column vectors.
# Matrix.columns([[25, 93], [-1, 66]])
# => 25 -1
# 93 66
#
def Matrix.columns(columns)
rows(columns, false).transpose
end
#
# Creates a matrix of size +row_count+ x +column_count+.
# It fills the values by calling the given block,
# passing the current row and column.
# Returns an enumerator if no block is given.
#
# m = Matrix.build(2, 4) {|row, col| col - row }
# => Matrix[[0, 1, 2, 3], [-1, 0, 1, 2]]
# m = Matrix.build(3) { rand }
# => a 3x3 matrix with random elements
#
def Matrix.build(row_count, column_count = row_count)
row_count = CoercionHelper.coerce_to_int(row_count)
column_count = CoercionHelper.coerce_to_int(column_count)
raise ArgumentError if row_count < 0 || column_count < 0
return to_enum :build, row_count, column_count unless block_given?
rows = Array.new(row_count) do |i|
Array.new(column_count) do |j|
yield i, j
end
end
new rows, column_count
end
#
# Creates a matrix where the diagonal elements are composed of +values+.
# Matrix.diagonal(9, 5, -3)
# => 9 0 0
# 0 5 0
# 0 0 -3
#
def Matrix.diagonal(*values)
size = values.size
return Matrix.empty if size == 0
rows = Array.new(size) {|j|
row = Array.new(size, 0)
row[j] = values[j]
row
}
new rows
end
#
# Creates an +n+ by +n+ diagonal matrix where each diagonal element is
# +value+.
# Matrix.scalar(2, 5)
# => 5 0
# 0 5
#
def Matrix.scalar(n, value)
diagonal(*Array.new(n, value))
end
#
# Creates an +n+ by +n+ identity matrix.
# Matrix.identity(2)
# => 1 0
# 0 1
#
def Matrix.identity(n)
scalar(n, 1)
end
class << Matrix
alias unit identity
alias I identity
end
#
# Creates a zero matrix.
# Matrix.zero(2)
# => 0 0
# 0 0
#
def Matrix.zero(row_count, column_count = row_count)
rows = Array.new(row_count){Array.new(column_count, 0)}
new rows, column_count
end
#
# Creates a single-row matrix where the values of that row are as given in
# +row+.
# Matrix.row_vector([4,5,6])
# => 4 5 6
#
def Matrix.row_vector(row)
row = convert_to_array(row)
new [row]
end
#
# Creates a single-column matrix where the values of that column are as given
# in +column+.
# Matrix.column_vector([4,5,6])
# => 4
# 5
# 6
#
def Matrix.column_vector(column)
column = convert_to_array(column)
new [column].transpose, 1
end
#
# Creates a empty matrix of +row_count+ x +column_count+.
# At least one of +row_count+ or +column_count+ must be 0.
#
# m = Matrix.empty(2, 0)
# m == Matrix[ [], [] ]
# => true
# n = Matrix.empty(0, 3)
# n == Matrix.columns([ [], [], [] ])
# => true
# m * n
# => Matrix[[0, 0, 0], [0, 0, 0]]
#
def Matrix.empty(row_count = 0, column_count = 0)
raise ArgumentError, "One size must be 0" if column_count != 0 && row_count != 0
raise ArgumentError, "Negative size" if column_count < 0 || row_count < 0
new([[]]*row_count, column_count)
end
#
# Create a matrix by stacking matrices vertically
#
# x = Matrix[[1, 2], [3, 4]]
# y = Matrix[[5, 6], [7, 8]]
# Matrix.vstack(x, y) # => Matrix[[1, 2], [3, 4], [5, 6], [7, 8]]
#
def Matrix.vstack(x, *matrices)
x = CoercionHelper.coerce_to_matrix(x)
result = x.send(:rows).map(&:dup)
matrices.each do |m|
m = CoercionHelper.coerce_to_matrix(m)
if m.column_count != x.column_count
raise ErrDimensionMismatch, "The given matrices must have #{x.column_count} columns, but one has #{m.column_count}"
end
result.concat(m.send(:rows))
end
new result, x.column_count
end
#
# Create a matrix by stacking matrices horizontally
#
# x = Matrix[[1, 2], [3, 4]]
# y = Matrix[[5, 6], [7, 8]]
# Matrix.hstack(x, y) # => Matrix[[1, 2, 5, 6], [3, 4, 7, 8]]
#
def Matrix.hstack(x, *matrices)
x = CoercionHelper.coerce_to_matrix(x)
result = x.send(:rows).map(&:dup)
total_column_count = x.column_count
matrices.each do |m|
m = CoercionHelper.coerce_to_matrix(m)
if m.row_count != x.row_count
raise ErrDimensionMismatch, "The given matrices must have #{x.row_count} rows, but one has #{m.row_count}"
end
result.each_with_index do |row, i|
row.concat m.send(:rows)[i]
end
total_column_count += m.column_count
end
new result, total_column_count
end
#
# Create a matrix by combining matrices entrywise, using the given block
#
# x = Matrix[[6, 6], [4, 4]]
# y = Matrix[[1, 2], [3, 4]]
# Matrix.combine(x, y) {|a, b| a - b} # => Matrix[[5, 4], [1, 0]]
#
def Matrix.combine(*matrices)
return to_enum(__method__, *matrices) unless block_given?
return Matrix.empty if matrices.empty?
matrices.map!(&CoercionHelper.method(:coerce_to_matrix))
x = matrices.first
matrices.each do |m|
Matrix.Raise ErrDimensionMismatch unless x.row_count == m.row_count && x.column_count == m.column_count
end
rows = Array.new(x.row_count) do |i|
Array.new(x.column_count) do |j|
yield matrices.map{|m| m[i,j]}
end
end
new rows, x.column_count
end
def combine(*matrices, &block)
Matrix.combine(self, *matrices, &block)
end
#
# Matrix.new is private; use Matrix.rows, columns, [], etc... to create.
#
def initialize(rows, column_count = rows[0].size)
# No checking is done at this point. rows must be an Array of Arrays.
# column_count must be the size of the first row, if there is one,
# otherwise it *must* be specified and can be any integer >= 0
@rows = rows
@column_count = column_count
end
def new_matrix(rows, column_count = rows[0].size) # :nodoc:
self.class.send(:new, rows, column_count) # bypass privacy of Matrix.new
end
private :new_matrix
#
# Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
#
def [](i, j)
@rows.fetch(i){return nil}[j]
end
alias element []
alias component []
def []=(i, j, v)
@rows[i][j] = v
end
alias set_element []=
alias set_component []=
private :[]=, :set_element, :set_component
#
# Returns the number of rows.
#
def row_count
@rows.size
end
alias_method :row_size, :row_count
#
# Returns the number of columns.
#
attr_reader :column_count
alias_method :column_size, :column_count
#
# Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
# an array). When a block is given, the elements of that vector are iterated.
#
def row(i, &block) # :yield: e
if block_given?
@rows.fetch(i){return self}.each(&block)
self
else
Vector.elements(@rows.fetch(i){return nil})
end
end
#
# Returns column vector number +j+ of the matrix as a Vector (starting at 0
# like an array). When a block is given, the elements of that vector are
# iterated.
#
def column(j) # :yield: e
if block_given?
return self if j >= column_count || j < -column_count
row_count.times do |i|
yield @rows[i][j]
end
self
else
return nil if j >= column_count || j < -column_count
col = Array.new(row_count) {|i|
@rows[i][j]
}
Vector.elements(col, false)
end
end
#
# Returns a matrix that is the result of iteration of the given block over all
# elements of the matrix.
# Matrix[ [1,2], [3,4] ].collect { |e| e**2 }
# => 1 4
# 9 16
#
def collect(&block) # :yield: e
return to_enum(:collect) unless block_given?
rows = @rows.collect{|row| row.collect(&block)}
new_matrix rows, column_count
end
alias map collect
#
# Yields all elements of the matrix, starting with those of the first row,
# or returns an Enumerator if no block given.
# Elements can be restricted by passing an argument:
# * :all (default): yields all elements
# * :diagonal: yields only elements on the diagonal
# * :off_diagonal: yields all elements except on the diagonal
# * :lower: yields only elements on or below the diagonal
# * :strict_lower: yields only elements below the diagonal
# * :strict_upper: yields only elements above the diagonal
# * :upper: yields only elements on or above the diagonal
#
# Matrix[ [1,2], [3,4] ].each { |e| puts e }
# # => prints the numbers 1 to 4
# Matrix[ [1,2], [3,4] ].each(:strict_lower).to_a # => [3]
#
def each(which = :all) # :yield: e
return to_enum :each, which unless block_given?
last = column_count - 1
case which
when :all
block = Proc.new
@rows.each do |row|
row.each(&block)
end
when :diagonal
@rows.each_with_index do |row, row_index|
yield row.fetch(row_index){return self}
end
when :off_diagonal
@rows.each_with_index do |row, row_index|
column_count.times do |col_index|
yield row[col_index] unless row_index == col_index
end
end
when :lower
@rows.each_with_index do |row, row_index|
0.upto([row_index, last].min) do |col_index|
yield row[col_index]
end
end
when :strict_lower
@rows.each_with_index do |row, row_index|
[row_index, column_count].min.times do |col_index|
yield row[col_index]
end
end
when :strict_upper
@rows.each_with_index do |row, row_index|
(row_index+1).upto(last) do |col_index|
yield row[col_index]
end
end
when :upper
@rows.each_with_index do |row, row_index|
row_index.upto(last) do |col_index|
yield row[col_index]
end
end
else
raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
end
self
end
#
# Same as #each, but the row index and column index in addition to the element
#
# Matrix[ [1,2], [3,4] ].each_with_index do |e, row, col|
# puts "#{e} at #{row}, #{col}"
# end
# # => Prints:
# # 1 at 0, 0
# # 2 at 0, 1
# # 3 at 1, 0
# # 4 at 1, 1
#
def each_with_index(which = :all) # :yield: e, row, column
return to_enum :each_with_index, which unless block_given?
last = column_count - 1
case which
when :all
@rows.each_with_index do |row, row_index|
row.each_with_index do |e, col_index|
yield e, row_index, col_index
end
end
when :diagonal
@rows.each_with_index do |row, row_index|
yield row.fetch(row_index){return self}, row_index, row_index
end
when :off_diagonal
@rows.each_with_index do |row, row_index|
column_count.times do |col_index|
yield row[col_index], row_index, col_index unless row_index == col_index
end
end
when :lower
@rows.each_with_index do |row, row_index|
0.upto([row_index, last].min) do |col_index|
yield row[col_index], row_index, col_index
end
end
when :strict_lower
@rows.each_with_index do |row, row_index|
[row_index, column_count].min.times do |col_index|
yield row[col_index], row_index, col_index
end
end
when :strict_upper
@rows.each_with_index do |row, row_index|
(row_index+1).upto(last) do |col_index|
yield row[col_index], row_index, col_index
end
end
when :upper
@rows.each_with_index do |row, row_index|
row_index.upto(last) do |col_index|
yield row[col_index], row_index, col_index
end
end
else
raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
end
self
end
SELECTORS = {all: true, diagonal: true, off_diagonal: true, lower: true, strict_lower: true, strict_upper: true, upper: true}.freeze
#
# :call-seq:
# index(value, selector = :all) -> [row, column]
# index(selector = :all){ block } -> [row, column]
# index(selector = :all) -> an_enumerator
#
# The index method is specialized to return the index as [row, column]
# It also accepts an optional +selector+ argument, see #each for details.
#
# Matrix[ [1,2], [3,4] ].index(&:even?) # => [0, 1]
# Matrix[ [1,1], [1,1] ].index(1, :strict_lower) # => [1, 0]
#
def index(*args)
raise ArgumentError, "wrong number of arguments(#{args.size} for 0-2)" if args.size > 2
which = (args.size == 2 || SELECTORS.include?(args.last)) ? args.pop : :all
return to_enum :find_index, which, *args unless block_given? || args.size == 1
if args.size == 1
value = args.first
each_with_index(which) do |e, row_index, col_index|
return row_index, col_index if e == value
end
else
each_with_index(which) do |e, row_index, col_index|
return row_index, col_index if yield e
end
end
nil
end
alias_method :find_index, :index
#
# Returns a section of the matrix. The parameters are either:
# * start_row, nrows, start_col, ncols; OR
# * row_range, col_range
#
# Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
# => 9 0 0
# 0 5 0
#
# Like Array#[], negative indices count backward from the end of the
# row or column (-1 is the last element). Returns nil if the starting
# row or column is greater than row_count or column_count respectively.
#
def minor(*param)
case param.size
when 2
row_range, col_range = param
from_row = row_range.first
from_row += row_count if from_row < 0
to_row = row_range.end
to_row += row_count if to_row < 0
to_row += 1 unless row_range.exclude_end?
size_row = to_row - from_row
from_col = col_range.first
from_col += column_count if from_col < 0
to_col = col_range.end
to_col += column_count if to_col < 0
to_col += 1 unless col_range.exclude_end?
size_col = to_col - from_col
when 4
from_row, size_row, from_col, size_col = param
return nil if size_row < 0 || size_col < 0
from_row += row_count if from_row < 0
from_col += column_count if from_col < 0
else
raise ArgumentError, param.inspect
end
return nil if from_row > row_count || from_col > column_count || from_row < 0 || from_col < 0
rows = @rows[from_row, size_row].collect{|row|
row[from_col, size_col]
}
new_matrix rows, [column_count - from_col, size_col].min
end
#
# Returns the submatrix obtained by deleting the specified row and column.
#
# Matrix.diagonal(9, 5, -3, 4).first_minor(1, 2)
# => 9 0 0
# 0 0 0
# 0 0 4
#
def first_minor(row, column)
raise RuntimeError, "first_minor of empty matrix is not defined" if empty?
unless 0 <= row && row < row_count
raise ArgumentError, "invalid row (#{row.inspect} for 0..#{row_count - 1})"
end
unless 0 <= column && column < column_count
raise ArgumentError, "invalid column (#{column.inspect} for 0..#{column_count - 1})"
end
arrays = to_a
arrays.delete_at(row)
arrays.each do |array|
array.delete_at(column)
end
new_matrix arrays, column_count - 1
end
#
# Returns the (row, column) cofactor which is obtained by multiplying
# the first minor by (-1)**(row + column).
#
# Matrix.diagonal(9, 5, -3, 4).cofactor(1, 1)
# => -108
#
def cofactor(row, column)
raise RuntimeError, "cofactor of empty matrix is not defined" if empty?
Matrix.Raise ErrDimensionMismatch unless square?
det_of_minor = first_minor(row, column).determinant
det_of_minor * (-1) ** (row + column)
end
#
# Returns the adjugate of the matrix.
#
# Matrix[ [7,6],[3,9] ].adjugate
# => 9 -6
# -3 7
#
def adjugate
Matrix.Raise ErrDimensionMismatch unless square?
Matrix.build(row_count, column_count) do |row, column|
cofactor(column, row)
end
end
#
# Returns the Laplace expansion along given row or column.
#
# Matrix[[7,6], [3,9]].laplace_expansion(column: 1)
# => 45
#
# Matrix[[Vector[1, 0], Vector[0, 1]], [2, 3]].laplace_expansion(row: 0)
# => Vector[3, -2]
#
#
def laplace_expansion(row: nil, column: nil)
num = row || column
if !num || (row && column)
raise ArgumentError, "exactly one the row or column arguments must be specified"
end
Matrix.Raise ErrDimensionMismatch unless square?
raise RuntimeError, "laplace_expansion of empty matrix is not defined" if empty?
unless 0 <= num && num < row_count
raise ArgumentError, "invalid num (#{num.inspect} for 0..#{row_count - 1})"
end
send(row ? :row : :column, num).map.with_index { |e, k|
e * cofactor(*(row ? [num, k] : [k,num]))
}.inject(:+)
end
alias_method :cofactor_expansion, :laplace_expansion
#--
# TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns +true+ if this is a diagonal matrix.
# Raises an error if matrix is not square.
#
def diagonal?
Matrix.Raise ErrDimensionMismatch unless square?
each(:off_diagonal).all?(&:zero?)
end
#
# Returns +true+ if this is an empty matrix, i.e. if the number of rows
# or the number of columns is 0.
#
def empty?
column_count == 0 || row_count == 0
end
#
# Returns +true+ if this is an hermitian matrix.
# Raises an error if matrix is not square.
#
def hermitian?
Matrix.Raise ErrDimensionMismatch unless square?
each_with_index(:upper).all? do |e, row, col|
e == rows[col][row].conj
end
end
#
# Returns +true+ if this is a lower triangular matrix.
#
def lower_triangular?
each(:strict_upper).all?(&:zero?)
end
#
# Returns +true+ if this is a normal matrix.
# Raises an error if matrix is not square.
#
def normal?
Matrix.Raise ErrDimensionMismatch unless square?
rows.each_with_index do |row_i, i|
rows.each_with_index do |row_j, j|
s = 0
rows.each_with_index do |row_k, k|
s += row_i[k] * row_j[k].conj - row_k[i].conj * row_k[j]
end
return false unless s == 0
end
end
true
end
#
# Returns +true+ if this is an orthogonal matrix
# Raises an error if matrix is not square.
#
def orthogonal?
Matrix.Raise ErrDimensionMismatch unless square?
rows.each_with_index do |row, i|
column_count.times do |j|
s = 0
row_count.times do |k|
s += row[k] * rows[k][j]
end
return false unless s == (i == j ? 1 : 0)
end
end
true
end
#
# Returns +true+ if this is a permutation matrix
# Raises an error if matrix is not square.
#
def permutation?
Matrix.Raise ErrDimensionMismatch unless square?
cols = Array.new(column_count)
rows.each_with_index do |row, i|
found = false
row.each_with_index do |e, j|
if e == 1
return false if found || cols[j]
found = cols[j] = true
elsif e != 0
return false
end
end
return false unless found
end
true
end
#
# Returns +true+ if all entries of the matrix are real.
#
def real?
all?(&:real?)
end
#
# Returns +true+ if this is a regular (i.e. non-singular) matrix.
#
def regular?
not singular?
end
#
# Returns +true+ if this is a singular matrix.
#
def singular?
determinant == 0
end
#
# Returns +true+ if this is a square matrix.
#
def square?
column_count == row_count
end
#
# Returns +true+ if this is a symmetric matrix.
# Raises an error if matrix is not square.
#
def symmetric?
Matrix.Raise ErrDimensionMismatch unless square?
each_with_index(:strict_upper) do |e, row, col|
return false if e != rows[col][row]
end
true
end
#
# Returns +true+ if this is an antisymmetric matrix.
# Raises an error if matrix is not square.
#
def antisymmetric?
Matrix.Raise ErrDimensionMismatch unless square?
each_with_index(:upper) do |e, row, col|
return false unless e == -rows[col][row]
end
true
end
#
# Returns +true+ if this is a unitary matrix
# Raises an error if matrix is not square.
#
def unitary?
Matrix.Raise ErrDimensionMismatch unless square?
rows.each_with_index do |row, i|
column_count.times do |j|
s = 0
row_count.times do |k|
s += row[k].conj * rows[k][j]
end
return false unless s == (i == j ? 1 : 0)
end
end
true
end
#
# Returns +true+ if this is an upper triangular matrix.
#
def upper_triangular?
each(:strict_lower).all?(&:zero?)
end
#
# Returns +true+ if this is a matrix with only zero elements
#
def zero?
all?(&:zero?)
end
#--
# OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns +true+ if and only if the two matrices contain equal elements.
#
def ==(other)
return false unless Matrix === other &&
column_count == other.column_count # necessary for empty matrices
rows == other.rows
end
def eql?(other)
return false unless Matrix === other &&
column_count == other.column_count # necessary for empty matrices
rows.eql? other.rows
end
#
# Returns a clone of the matrix, so that the contents of each do not reference
# identical objects.
# There should be no good reason to do this since Matrices are immutable.
#
def clone
new_matrix @rows.map(&:dup), column_count
end
#
# Returns a hash-code for the matrix.
#
def hash
@rows.hash
end
#--
# ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Matrix multiplication.
# Matrix[[2,4], [6,8]] * Matrix.identity(2)
# => 2 4
# 6 8
#
def *(m) # m is matrix or vector or number
case(m)
when Numeric
rows = @rows.collect {|row|
row.collect {|e| e * m }
}
return new_matrix rows, column_count
when Vector
m = self.class.column_vector(m)
r = self * m
return r.column(0)
when Matrix
Matrix.Raise ErrDimensionMismatch if column_count != m.row_count
rows = Array.new(row_count) {|i|
Array.new(m.column_count) {|j|
(0 ... column_count).inject(0) do |vij, k|
vij + self[i, k] * m[k, j]
end
}
}
return new_matrix rows, m.column_count
else
return apply_through_coercion(m, __method__)
end
end
#
# Matrix addition.
# Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
# => 6 0
# -4 12
#
def +(m)
case m
when Numeric
Matrix.Raise ErrOperationNotDefined, "+", self.class, m.class
when Vector
m = self.class.column_vector(m)
when Matrix
else
return apply_through_coercion(m, __method__)
end
Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count && column_count == m.column_count
rows = Array.new(row_count) {|i|
Array.new(column_count) {|j|
self[i, j] + m[i, j]
}
}
new_matrix rows, column_count
end
#
# Matrix subtraction.
# Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
# => -8 2
# 8 1
#
def -(m)
case m
when Numeric
Matrix.Raise ErrOperationNotDefined, "-", self.class, m.class
when Vector
m = self.class.column_vector(m)
when Matrix
else
return apply_through_coercion(m, __method__)
end
Matrix.Raise ErrDimensionMismatch unless row_count == m.row_count && column_count == m.column_count
rows = Array.new(row_count) {|i|
Array.new(column_count) {|j|
self[i, j] - m[i, j]
}
}
new_matrix rows, column_count
end
#
# Matrix division (multiplication by the inverse).
# Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
# => -7 1
# -3 -6
#
def /(other)
case other
when Numeric
rows = @rows.collect {|row|
row.collect {|e| e / other }
}
return new_matrix rows, column_count
when Matrix
return self * other.inverse
else
return apply_through_coercion(other, __method__)
end
end
#
# Hadamard product
# Matrix[[1,2], [3,4]].hadamard_product(Matrix[[1,2], [3,2]])
# => 1 4
# 9 8
#
def hadamard_product(m)
combine(m){|a, b| a * b}
end
alias_method :entrywise_product, :hadamard_product
#
# Returns the inverse of the matrix.
# Matrix[[-1, -1], [0, -1]].inverse
# => -1 1
# 0 -1
#
def inverse
Matrix.Raise ErrDimensionMismatch unless square?
self.class.I(row_count).send(:inverse_from, self)
end
alias inv inverse
def inverse_from(src) # :nodoc:
last = row_count - 1
a = src.to_a
0.upto(last) do |k|
i = k
akk = a[k][k].abs
(k+1).upto(last) do |j|
v = a[j][k].abs
if v > akk
i = j
akk = v
end
end
Matrix.Raise ErrNotRegular if akk == 0
if i != k
a[i], a[k] = a[k], a[i]
@rows[i], @rows[k] = @rows[k], @rows[i]
end
akk = a[k][k]
0.upto(last) do |ii|
next if ii == k
q = a[ii][k].quo(akk)
a[ii][k] = 0
(k + 1).upto(last) do |j|
a[ii][j] -= a[k][j] * q
end
0.upto(last) do |j|
@rows[ii][j] -= @rows[k][j] * q
end
end
(k+1).upto(last) do |j|
a[k][j] = a[k][j].quo(akk)
end
0.upto(last) do |j|
@rows[k][j] = @rows[k][j].quo(akk)
end
end
self
end
private :inverse_from
#
# Matrix exponentiation.
# Equivalent to multiplying the matrix by itself N times.
# Non integer exponents will be handled by diagonalizing the matrix.
#
# Matrix[[7,6], [3,9]] ** 2
# => 67 96
# 48 99
#
def **(other)
case other
when Integer
x = self
if other <= 0
x = self.inverse
return self.class.identity(self.column_count) if other == 0
other = -other
end
z = nil
loop do
z = z ? z * x : x if other[0] == 1
return z if (other >>= 1).zero?
x *= x
end
when Numeric
v, d, v_inv = eigensystem
v * self.class.diagonal(*d.each(:diagonal).map{|e| e ** other}) * v_inv
else
Matrix.Raise ErrOperationNotDefined, "**", self.class, other.class
end
end
def +@
self
end
def -@
collect {|e| -e }
end
#--
# MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#++
#
# Returns the determinant of the matrix.
#
# Beware that using Float values can yield erroneous results
# because of their lack of precision.
# Consider using exact types like Rational or BigDecimal instead.
#
# Matrix[[7,6], [3,9]].determinant
# => 45
#
def determinant
Matrix.Raise ErrDimensionMismatch unless square?
m = @rows
case row_count
# Up to 4x4, give result using Laplacian expansion by minors.
# This will typically be faster, as well as giving good results
# in case of Floats
when 0
+1
when 1
+ m[0][0]
when 2
+ m[0][0] * m[1][1] - m[0][1] * m[1][0]
when 3
m0, m1, m2 = m
+ m0[0] * m1[1] * m2[2] - m0[0] * m1[2] * m2[1] \
- m0[1] * m1[0] * m2[2] + m0[1] * m1[2] * m2[0] \
+ m0[2] * m1[0] * m2[1] - m0[2] * m1[1] * m2[0]
when 4
m0, m1, m2, m3 = m
+ m0[0] * m1[1] * m2[2] * m3[3] - m0[0] * m1[1] * m2[3] * m3[2] \
- m0[0] * m1[2] * m2[1] * m3[3] + m0[0] * m1[2] * m2[3] * m3[1] \
+ m0[0] * m1[3] * m2[1] * m3[2] - m0[0] * m1[3] * m2[2] * m3[1] \
- m0[1] * m1[0] * m2[2] * m3[3] + m0[1] * m1[0] * m2[3] * m3[2] \
+ m0[1] * m1[2] * m2[0] * m3[3] - m0[1] * m1[2] * m2[3] * m3[0] \
- m0[1] * m1[3] * m2[0] * m3[2] + m0[1] * m1[3] * m2[2] * m3[0] \
+ m0[2] * m1[0] * m2[1] * m3[3] - m0[2] * m1[0] * m2[3] * m3[1] \
- m0[2] * m1[1] * m2[0] * m3[3] + m0[2] * m1[1] * m2[3] * m3[0] \
+ m0[2] * m1[3] * m2[0] * m3[1] - m0[2] * m1[3] * m2[1] * m3[0] \
- m0[3] * m1[0] * m2[1] * m3[2] + m0[3] * m1[0] * m2[2] * m3[1] \
+ m0[3] * m1[1] * m2[0] * m3[2] - m0[3] * m1[1] * m2[2] * m3[0] \
- m0[3] * m1[2] * m2[0] * m3[1] + m0[3] * m1[2] * m2[1] * m3[0]
else
# For bigger matrices, use an efficient and general algorithm.
# Currently, we use the Gauss-Bareiss algorithm
determinant_bareiss
end
end
alias_method :det, :determinant
#
# Private. Use Matrix#determinant
#
# Returns the determinant of the matrix, using
# Bareiss' multistep integer-preserving gaussian elimination.
# It has the same computational cost order O(n^3) as standard Gaussian elimination.
# Intermediate results are fraction free and of lower complexity.
# A matrix of Integers will have thus intermediate results that are also Integers,
# with smaller bignums (if any), while a matrix of Float will usually have
# intermediate results with better precision.
#
def determinant_bareiss
size = row_count
last = size - 1
a = to_a
no_pivot = Proc.new{ return 0 }
sign = +1
pivot = 1
size.times do |k|
previous_pivot = pivot
if (pivot = a[k][k]) == 0
switch = (k+1 ... size).find(no_pivot) {|row|
a[row][k] != 0
}
a[switch], a[k] = a[k], a[switch]
pivot = a[k][k]
sign = -sign
end
(k+1).upto(last) do |i|
ai = a[i]
(k+1).upto(last) do |j|
ai[j] = (pivot * ai[j] - ai[k] * a[k][j]) / previous_pivot
end
end
end
sign * pivot
end
private :determinant_bareiss
#
# deprecated; use Matrix#determinant
#
def determinant_e
warn "Matrix#determinant_e is deprecated; use #determinant", uplevel: 1
determinant
end
alias det_e determinant_e
#
# Returns a new matrix resulting by stacking horizontally
# the receiver with the given matrices
#
# x = Matrix[[1, 2], [3, 4]]
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | true |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/template.rb | stdlib/template.rb | class Template
@_cache = {}
def self.[](name)
@_cache[name] || @_cache["templates/#{name}"]
end
def self.[]=(name, instance)
@_cache[name] = instance
end
def self.paths
@_cache.keys
end
attr_reader :body
def initialize(name, &body)
@name, @body = name, body
Template[name] = self
end
def inspect
"#<Template: '#{@name}'>"
end
def render(ctx = self)
ctx.instance_exec(OutputBuffer.new, &@body)
end
class OutputBuffer
def initialize
@buffer = []
end
def append(str)
@buffer << str
end
def join
@buffer.join
end
alias append= append
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/forwardable.rb | stdlib/forwardable.rb | module Forwardable
def instance_delegate(hash)
hash.each do |methods, accessor|
methods = [methods] unless methods.respond_to? :each
methods.each do |method|
def_instance_delegator(accessor, method)
end
end
end
def def_instance_delegators(accessor, *methods)
methods.each do |method|
next if %w[__send__ __id__].include?(method)
def_instance_delegator(accessor, method)
end
end
def def_instance_delegator(accessor, method, ali = method)
if accessor.to_s.start_with? '@'
define_method ali do |*args, &block|
instance_variable_get(accessor).__send__(method, *args, &block)
end
else
define_method ali do |*args, &block|
__send__(accessor).__send__(method, *args, &block)
end
end
end
alias delegate instance_delegate
alias def_delegators def_instance_delegators
alias def_delegator def_instance_delegator
end
module SingleForwardable
def single_delegate(hash)
hash.each do |methods, accessor|
methods = [methods] unless methods.respond_to? :each
methods.each do |method|
def_single_delegator(accessor, method)
end
end
end
def def_single_delegators(accessor, *methods)
methods.each do |method|
next if %w[__send__ __id__].include? method
def_single_delegator(accessor, method)
end
end
def def_single_delegator(accessor, method, ali = method)
if accessor.to_s.start_with? '@'
define_singleton_method ali do |*args, &block|
instance_variable_get(accessor).__send__(method, *args, &block)
end
else
define_singleton_method ali do |*args, &block|
__send__(accessor).__send__(method, *args, &block)
end
end
end
alias delegate single_delegate
alias def_delegators def_single_delegators
alias def_delegator def_single_delegator
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/native.rb | stdlib/native.rb | # backtick_javascript: true
# helpers: hash_put
# Provides a complete set of tools to wrap native JavaScript
# into nice Ruby objects.
#
# @example
#
# $$.document.querySelector('p').classList.add('blue')
# # => adds "blue" class to <p>
#
# $$.location.href = 'https://google.com'
# # => changes page location
#
# do_later = $$[:setTimeout] # Accessing the "setTimeout" property
# do_later.call(->{ puts :hello}, 500)
#
# `$$` and `$global` wrap `Opal.global`, which the Opal JS runtime
# sets to the global `this` object.
#
module Native
def self.is_a?(object, klass)
%x{
try {
return #{object} instanceof #{try_convert(klass)};
}
catch {
return false;
}
}
end
def self.try_convert(value, default = nil)
%x{
if (#{native?(value)}) {
return #{value};
}
else if (#{value.respond_to? :to_n}) {
return #{value.to_n};
}
else {
return #{default};
}
}
end
def self.convert(value)
%x{
if (#{native?(value)}) {
return #{value};
}
else if (#{value.respond_to? :to_n}) {
return #{value.to_n};
}
else {
#{raise ArgumentError, "#{value.inspect} isn't native"};
}
}
end
def self.call(obj, key, *args, &block)
%x{
var prop = #{obj}[#{key}];
if (prop instanceof Function) {
var converted = new Array(args.length);
for (var i = 0, l = args.length; i < l; i++) {
var item = args[i],
conv = #{try_convert(`item`)};
converted[i] = conv === nil ? item : conv;
}
if (block !== nil) {
converted.push(block);
}
return #{Native(`prop.apply(#{obj}, converted)`)};
}
else {
return #{Native(`prop`)};
}
}
end
def self.proc(&block)
raise LocalJumpError, 'no block given' unless block
::Kernel.proc { |*args|
args.map! { |arg| Native(arg) }
instance = Native(`this`)
%x{
// if global is current scope, run the block in the scope it was defined
if (this === Opal.global) {
return block.apply(self, #{args});
}
var self_ = block.$$s;
block.$$s = null;
try {
return block.apply(#{instance}, #{args});
}
finally {
block.$$s = self_;
}
}
}
end
module Helpers
# Exposes a native JavaScript method to Ruby
#
#
# @param new [String]
# The name of the newly created method.
#
# @param old [String]
# The name of the native JavaScript method to be exposed.
# If the name ends with "=" (e.g. `foo=`) it will be interpreted as
# a property setter. (default: the value of "new")
#
# @param as [Class]
# If provided the values returned by the original method will be
# returned as instances of the passed class. The class passed to "as"
# is expected to accept a native JavaScript value.
#
# @example
#
# class Element
# extend Native::Helpers
#
# alias_native :add_class, :addClass
# alias_native :show
# alias_native :hide
#
# def initialize(selector)
# @native = `$(#{selector})`
# end
# end
#
# titles = Element.new('h1')
# titles.add_class :foo
# titles.hide
# titles.show
#
def alias_native(new, old = new, as: nil)
if old.end_with? '='
define_method new do |value|
`#{@native}[#{old[0..-2]}] = #{Native.convert(value)}`
value
end
elsif as
define_method new do |*args, &block|
value = Native.call(@native, old, *args, &block)
if value
as.new(value.to_n)
end
end
else
define_method new do |*args, &block|
Native.call(@native, old, *args, &block)
end
end
end
def native_reader(*names)
names.each do |name|
define_method name do
Native(`#{@native}[name]`)
end
end
end
def native_writer(*names)
names.each do |name|
define_method "#{name}=" do |value|
Native(`#{@native}[name] = value`)
end
end
end
def native_accessor(*names)
native_reader(*names)
native_writer(*names)
end
end
module Wrapper
def initialize(native)
unless ::Kernel.native?(native)
::Kernel.raise ArgumentError, "#{native.inspect} isn't native"
end
@native = native
end
# Returns the internal native JavaScript value
def to_n
@native
end
def self.included(klass)
klass.extend Helpers
end
end
def self.included(base)
warn 'Including ::Native is deprecated. Please include Native::Wrapper instead.'
base.include Wrapper
end
end
module Kernel
def native?(value)
# Opal is now both a Ruby module and a Opal runtime constant.
# Let's keep it as if it was native for compatibility.
`value === Opal || value == null || !value.$$class`
end
# Wraps a native JavaScript with `Native::Object.new`
#
# @return [Native::Object] The wrapped object if it is native
# @return [nil] for `null` and `undefined`
# @return [obj] The object itself if it's not native
def Native(obj)
if `#{obj} == null`
nil
elsif native?(obj)
Native::Object.new(obj)
elsif obj.is_a?(Array)
obj.map do |o|
Native(o)
end
elsif obj.is_a?(Proc)
proc do |*args, &block|
Native(obj.call(*args, &block))
end
else
obj
end
end
alias _Array Array
# Wraps array-like JavaScript objects in Native::Array
def Array(object, *args, &block)
if native?(object)
return Native::Array.new(object, *args, &block).to_a
end
_Array(object)
end
end
class Native::Object < BasicObject
include ::Native::Wrapper
def ==(other)
`#{@native} === #{::Native.try_convert(other)}`
end
def has_key?(name)
`Opal.hasOwnProperty.call(#{@native}, #{name})`
end
def each(*args)
if block_given?
%x{
for (var key in #{@native}) {
#{yield `key`, `#{@native}[key]`}
}
}
self
else
method_missing(:each, *args)
end
end
def [](key)
%x{
var prop = #{@native}[key];
if (prop instanceof Function) {
return prop;
}
else {
return #{::Native.call(@native, key)}
}
}
end
def []=(key, value)
native = ::Native.try_convert(value)
if `#{native} === nil`
`#{@native}[key] = #{value}`
else
`#{@native}[key] = #{native}`
end
end
def merge!(other)
%x{
other = #{::Native.convert(other)};
for (var prop in other) {
#{@native}[prop] = other[prop];
}
}
self
end
def respond_to?(name, include_all = false)
::Kernel.instance_method(:respond_to?).bind(self).call(name, include_all)
end
def respond_to_missing?(name, include_all = false)
`Opal.hasOwnProperty.call(#{@native}, #{name})`
end
def method_missing(mid, *args, &block)
%x{
if (mid.charAt(mid.length - 1) === '=') {
return #{self[mid.slice(0, mid.length - 1)] = args[0]};
}
else {
return #{::Native.call(@native, mid, *args, &block)};
}
}
end
def nil?
false
end
def is_a?(klass)
`Opal.is_a(self, klass)`
end
def instance_of?(klass)
`self.$$class === klass`
end
def class
`self.$$class`
end
def to_a(options = {}, &block)
::Native::Array.new(@native, options, &block).to_a
end
def inspect
"#<Native:#{`String(#{@native})`}>"
end
alias include? has_key?
alias key? has_key?
alias kind_of? is_a?
alias member? has_key?
end
class Native::Array
include Native::Wrapper
include Enumerable
def initialize(native, options = {}, &block)
super(native)
@get = options[:get] || options[:access]
@named = options[:named]
@set = options[:set] || options[:access]
@length = options[:length] || :length
@block = block
if `#{length} == null`
raise ArgumentError, 'no length found on the array-like object'
end
end
def each(&block)
return enum_for :each unless block
%x{
for (var i = 0, length = #{length}; i < length; i++) {
Opal.yield1(block, #{self[`i`]});
}
}
self
end
def [](index)
result = case index
when String, Symbol
@named ? `#{@native}[#{@named}](#{index})` : `#{@native}[#{index}]`
when Integer
@get ? `#{@native}[#{@get}](#{index})` : `#{@native}[#{index}]`
end
if result
if @block
@block.call(result)
else
Native(result)
end
end
end
def []=(index, value)
if @set
`#{@native}[#{@set}](#{index}, #{Native.convert(value)})`
else
`#{@native}[#{index}] = #{Native.convert(value)}`
end
end
def last(count = nil)
if count
index = length - 1
result = []
while index >= 0
result << self[index]
index -= 1
end
result
else
self[length - 1]
end
end
def length
`#{@native}[#{@length}]`
end
def inspect
to_a.inspect
end
alias to_ary to_a
end
class Numeric
# @return the internal JavaScript value (with `valueOf`).
def to_n
`self.valueOf()`
end
end
class Proc
# @return itself (an instance of `Function`)
def to_n
self
end
end
class String
# @return the internal JavaScript value (with `valueOf`).
def to_n
`self.valueOf()`
end
end
class Regexp
# @return the internal JavaScript value (with `valueOf`).
def to_n
`self.valueOf()`
end
end
class MatchData
# @return the array of matches
def to_n
@matches
end
end
class Struct
# @return a JavaScript object with the members as keys and their
# values as values.
def to_n
result = `{}`
each_pair do |name, value|
`#{result}[#{name}] = #{Native.try_convert(value, value)}`
end
result
end
end
class Array
# Retuns a copy of itself trying to call #to_n on each member.
def to_n
%x{
var result = [];
for (var i = 0, length = self.length; i < length; i++) {
var obj = self[i];
result.push(#{Native.try_convert(`obj`, `obj`)});
}
return result;
}
end
end
class Boolean
# @return the internal JavaScript value (with `valueOf`).
def to_n
`self.valueOf()`
end
end
class Time
# @return itself (an instance of `Date`).
def to_n
self
end
end
class NilClass
# @return the corresponding JavaScript value (`null`).
def to_n
`null`
end
end
# Running this code twice results in an infinite loop. While it's true
# that we shouldn't run this file twice, there are certain cases, like
# for example live reload, when this may happen.
unless Hash.method_defined? :_initialize
class Hash
alias _initialize initialize
%x{
function $hash_dup_conv(old_hash) {
var new_map = new Map();
old_hash.forEach((v, k, h) => $hash_convert_and_put_value(new_map, k, v));
return new_map;
}
function $hash_convert_and_put_value(hash, key, value) {
if (value instanceof Map) {
$hash_put(hash, key, $hash_dup_conv(value));
} else if (value && (
value.constructor === undefined ||
value.constructor === Object)) {
$hash_put(hash, key, #{Hash.new(`value`)});
} else if (value instanceof Array) {
value = value.map(function(item) {
if (item instanceof Map) {
return $hash_dup_conv(item);
} else if (item && (
item.constructor === undefined ||
item.constructor === Object)) {
return #{Hash.new(`item`)};
}
return #{Native(`item`)};
});
$hash_put(hash, key, value)
} else {
$hash_put(hash, key, #{Native(`value`)});
}
}
}
def initialize(defaults = undefined, &block)
%x{
if (defaults != null) {
if (defaults.constructor === undefined ||
defaults.constructor === Object) {
var key, value;
for (key in defaults) {
value = defaults[key];
$hash_convert_and_put_value(self, key, value);
}
return self;
} else if (defaults instanceof Map) {
defaults.forEach((v, k, h) => $hash_convert_and_put_value(self, k, v));
}
}
return #{_initialize(defaults, &block)};
}
end
# @return a JavaScript object, in turn also calling #to_n on
# all keys and values.
def to_n
%x{
var result = {};
Opal.hash_each(self, false, function(key, value) {
result[#{Native.try_convert(`key`, `key`)}] = #{Native.try_convert(`value`, `value`)};
return [false, false];
});
return result;
}
end
end
end
class Module
# Exposes the current module as a property of
# the global object (e.g. `window`).
def native_module
`Opal.global[#{name}] = #{self}`
end
end
class Class
def native_alias(new_jsid, existing_mid)
%x{
var aliased = #{self}.prototype[Opal.jsid(#{existing_mid})];
if (!aliased) {
#{raise NameError.new("undefined method `#{existing_mid}' for class `#{inspect}'", existing_mid)};
}
#{self}.prototype[#{new_jsid}] = aliased;
}
end
def native_class
native_module
`self["new"] = self.$new`
end
end
# Exposes the global value (would be `window` inside a browser)
$$ = $global = Native(`Opal.global`)
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal-platform.rb | stdlib/opal-platform.rb | # backtick_javascript: true
`/* global GjsFileImporter, Deno, Bun */`
browser = `typeof(document) !== "undefined"`
bun = `typeof(Bun) === "object" && typeof(Bun.version) === "string"`
deno = `typeof(Deno) === "object" && typeof(Deno.version) === "object"`
node = `typeof(process) !== "undefined" && process.versions && process.versions.node`
headless_chrome = `typeof(opalheadlesschrome) !== "undefined"`
headless_firefox = `typeof(opalheadlessfirefox) !== "undefined"`
safari = `typeof(opalsafari) !== "undefined"`
gjs = `typeof(window) !== "undefined" && typeof(GjsFileImporter) !== "undefined"`
quickjs = `typeof(window) === "undefined" && typeof(__loadScript) !== "undefined"`
opal_miniracer = `typeof(opalminiracer) !== "undefined"`
OPAL_PLATFORM = if bun
'bun'
elsif deno
'deno'
elsif node
'nodejs'
elsif headless_chrome
'headless-chrome'
elsif headless_firefox
'headless-firefox'
elsif safari
'safari'
elsif gjs
'gjs'
elsif quickjs
'quickjs'
elsif opal_miniracer
'opal-miniracer'
else # possibly browser, which is the primary target
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/shellwords.rb | stdlib/shellwords.rb | # frozen-string-literal: true
##
# == Manipulates strings like the UNIX Bourne shell
#
# This module manipulates strings according to the word parsing rules
# of the UNIX Bourne shell.
#
# The shellwords() function was originally a port of shellwords.pl,
# but modified to conform to the Shell & Utilities volume of the IEEE
# Std 1003.1-2008, 2016 Edition [1].
#
# === Usage
#
# You can use Shellwords to parse a string into a Bourne shell friendly Array.
#
# require 'shellwords'
#
# argv = Shellwords.split('three blind "mice"')
# argv #=> ["three", "blind", "mice"]
#
# Once you've required Shellwords, you can use the #split alias
# String#shellsplit.
#
# argv = "see how they run".shellsplit
# argv #=> ["see", "how", "they", "run"]
#
# They treat quotes as special characters, so an unmatched quote will
# cause an ArgumentError.
#
# argv = "they all ran after the farmer's wife".shellsplit
# #=> ArgumentError: Unmatched quote: ...
#
# Shellwords also provides methods that do the opposite.
# Shellwords.escape, or its alias, String#shellescape, escapes
# shell metacharacters in a string for use in a command line.
#
# filename = "special's.txt"
#
# system("cat -- #{filename.shellescape}")
# # runs "cat -- special\\'s.txt"
#
# Note the '--'. Without it, cat(1) will treat the following argument
# as a command line option if it starts with '-'. It is guaranteed
# that Shellwords.escape converts a string to a form that a Bourne
# shell will parse back to the original string, but it is the
# programmer's responsibility to make sure that passing an arbitrary
# argument to a command does no harm.
#
# Shellwords also comes with a core extension for Array, Array#shelljoin.
#
# dir = "Funny GIFs"
# argv = %W[ls -lta -- #{dir}]
# system(argv.shelljoin + " | less")
# # runs "ls -lta -- Funny\\ GIFs | less"
#
# You can use this method to build a complete command line out of an
# array of arguments.
#
# === Authors
# * Wakou Aoyama
# * Akinori MUSHA <knu@iDaemons.org>
#
# === Contact
# * Akinori MUSHA <knu@iDaemons.org> (current maintainer)
#
# === Resources
#
# 1: {IEEE Std 1003.1-2008, 2016 Edition, the Shell & Utilities volume}[http://pubs.opengroup.org/onlinepubs/9699919799/utilities/contents.html]
module Shellwords
# Splits a string into an array of tokens in the same way the UNIX
# Bourne shell does.
#
# argv = Shellwords.split('here are "two words"')
# argv #=> ["here", "are", "two words"]
#
# Note, however, that this is not a command line parser. Shell
# metacharacters except for the single and double quotes and
# backslash are not treated as such.
#
# argv = Shellwords.split('ruby my_prog.rb | less')
# argv #=> ["ruby", "my_prog.rb", "|", "less"]
#
# String#shellsplit is a shortcut for this function.
#
# argv = 'here are "two words"'.shellsplit
# argv #=> ["here", "are", "two words"]
def shellsplit(line)
line += ' ' # Somehow this is needed for the JS regexp engine
words = []
field = String.new
line.scan(/\s*(?:([^\s\\\'\"]+)|'([^\']*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\r?\n?\Z|\s)?/m) do |(word, sq, dq, esc, garbage, sep)|
raise ArgumentError, "Unmatched quote: #{line.inspect}" if garbage
# 2.2.3 Double-Quotes:
#
# The <backslash> shall retain its special meaning as an
# escape character only when followed by one of the following
# characters when considered special:
#
# $ ` " \ <newline>
field += word || sq || (dq && dq.gsub(/\\([$`"\\\n])/, '\\1')) || esc.gsub(/\\(.)/, '\\1')
if sep
words << field
field = String.new
end
end
words
end
alias shellwords shellsplit
module_function :shellsplit, :shellwords
class << self
alias split shellsplit
end
# Escapes a string so that it can be safely used in a Bourne shell
# command line. +str+ can be a non-string object that responds to
# +to_s+.
#
# Note that a resulted string should be used unquoted and is not
# intended for use in double quotes nor in single quotes.
#
# argv = Shellwords.escape("It's better to give than to receive")
# argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"
#
# String#shellescape is a shorthand for this function.
#
# argv = "It's better to give than to receive".shellescape
# argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"
#
# # Search files in lib for method definitions
# pattern = "^[ \t]*def "
# open("| grep -Ern -e #{pattern.shellescape} lib") { |grep|
# grep.each_line { |line|
# file, lineno, matched_line = line.split(':', 3)
# # ...
# }
# }
#
# It is the caller's responsibility to encode the string in the right
# encoding for the shell environment where this string is used.
#
# Multibyte characters are treated as multibyte characters, not as bytes.
#
# Returns an empty quoted String if +str+ has a length of zero.
def shellescape(str)
str = str.to_s
# An empty argument will be skipped, so return empty quotes.
return "''".dup if str.empty?
str = str.dup
# Treat multibyte characters as is. It is the caller's responsibility
# to encode the string in the right encoding for the shell
# environment.
str = str.gsub(/[^A-Za-z0-9_\-.,:+\/@\n]/, '\\\\\\&')
# A LF cannot be escaped with a backslash because a backslash + LF
# combo is regarded as a line continuation and simply ignored.
str = str.gsub(/\n/, "'\n'")
str
end
module_function :shellescape
class << self
alias escape shellescape
end
# Builds a command line string from an argument list, +array+.
#
# All elements are joined into a single string with fields separated by a
# space, where each element is escaped for the Bourne shell and stringified
# using +to_s+.
#
# ary = ["There's", "a", "time", "and", "place", "for", "everything"]
# argv = Shellwords.join(ary)
# argv #=> "There\\'s a time and place for everything"
#
# Array#shelljoin is a shortcut for this function.
#
# ary = ["Don't", "rock", "the", "boat"]
# argv = ary.shelljoin
# argv #=> "Don\\'t rock the boat"
#
# You can also mix non-string objects in the elements as allowed in Array#join.
#
# output = `#{['ps', '-p', $$].shelljoin}`
#
def shelljoin(array)
array.map { |arg| shellescape(arg) }.join(' ')
end
module_function :shelljoin
class << self
alias join shelljoin
end
end
class String
# call-seq:
# str.shellsplit => array
#
# Splits +str+ into an array of tokens in the same way the UNIX
# Bourne shell does.
#
# See Shellwords.shellsplit for details.
def shellsplit
Shellwords.split(self)
end
# call-seq:
# str.shellescape => string
#
# Escapes +str+ so that it can be safely used in a Bourne shell
# command line.
#
# See Shellwords.shellescape for details.
def shellescape
Shellwords.escape(self)
end
end
class Array
# call-seq:
# array.shelljoin => string
#
# Builds a command line string from an argument list +array+ joining
# all elements escaped for the Bourne shell and separated by a space.
#
# See Shellwords.shelljoin for details.
def shelljoin
Shellwords.join(self)
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/pathname.rb | stdlib/pathname.rb | # backtick_javascript: true
require 'corelib/comparable'
# Portions from Author:: Tanaka Akira <akr@m17n.org>
class Pathname
include Comparable
SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
def initialize(path)
if Pathname === path
@path = path.path.to_s
elsif path.respond_to?(:to_path)
@path = path.to_path
elsif path.is_a?(String)
@path = path
elsif path.nil?
raise TypeError, 'no implicit conversion of nil into String'
else
raise TypeError, "no implicit conversion of #{path.class} into String"
end
raise ArgumentError if @path == "\0"
end
def self.pwd
new(Dir.pwd)
end
attr_reader :path
def ==(other)
other.path == @path
end
def absolute?
!relative?
end
def relative?
path = @path
while (r = chop_basename(path))
path, = r
end
path == ''
end
def chop_basename(path) # :nodoc:
base = File.basename(path)
# ruby uses /^#{SEPARATOR_PAT}?$/o but having issues with interpolation
if Regexp.new("^#{Pathname::SEPARATOR_PAT.source}?$") =~ base
return nil
else
return path[0, path.rindex(base)], base
end
end
def root?
@path == '/'
end
def parent
new_path = @path.sub(%r{/([^/]+/?$)}, '')
new_path = absolute? ? '/' : '.' if new_path == ''
Pathname.new(new_path)
end
def sub(*args)
Pathname.new(@path.sub(*args))
end
def cleanpath
`return Opal.normalize(#{@path})`
end
def to_path
@path
end
def hash
@path.hash
end
def expand_path
Pathname.new(File.expand_path(@path))
end
def +(other)
other = Pathname.new(other) unless Pathname === other
Pathname.new(plus(@path, other.to_s))
end
def plus(path1, path2) # -> path # :nodoc:
prefix2 = path2
index_list2 = []
basename_list2 = []
while (r2 = chop_basename(prefix2))
prefix2, basename2 = r2
index_list2.unshift prefix2.length
basename_list2.unshift basename2
end
return path2 if prefix2 != ''
prefix1 = path1
while true
while !basename_list2.empty? && basename_list2.first == '.'
index_list2.shift
basename_list2.shift
end
break unless (r1 = chop_basename(prefix1))
prefix1, basename1 = r1
next if basename1 == '.'
if basename1 == '..' || basename_list2.empty? || basename_list2.first != '..'
prefix1 += basename1
break
end
index_list2.shift
basename_list2.shift
end
r1 = chop_basename(prefix1)
if !r1 && /#{SEPARATOR_PAT}/ =~ File.basename(prefix1)
while !basename_list2.empty? && basename_list2.first == '..'
index_list2.shift
basename_list2.shift
end
end
if !basename_list2.empty?
suffix2 = path2[index_list2.first..-1]
r1 ? File.join(prefix1, suffix2) : prefix1 + suffix2
else
r1 ? prefix1 : File.dirname(prefix1)
end
end
def join(*args)
return self if args.empty?
result = args.pop
result = Pathname.new(result) unless Pathname === result
return result if result.absolute?
args.reverse_each do |arg|
arg = Pathname.new(arg) unless Pathname === arg
result = arg + result
return result if result.absolute?
end
self + result
end
def split
[dirname, basename]
end
def dirname
Pathname.new(File.dirname(@path))
end
def basename
Pathname.new(File.basename(@path))
end
def directory?
File.directory?(@path)
end
def extname
File.extname(@path)
end
def <=>(other)
path <=> other.path
end
SAME_PATHS = if File::FNM_SYSCASE.nonzero?
# Avoid #zero? here because #casecmp can return nil.
proc { |a, b| a.casecmp(b) == 0 }
else
proc { |a, b| a == b }
end
def relative_path_from(base_directory)
dest_directory = cleanpath.to_s
base_directory = base_directory.cleanpath.to_s
dest_prefix = dest_directory
dest_names = []
while (r = chop_basename(dest_prefix))
dest_prefix, basename = r
dest_names.unshift basename if basename != '.'
end
base_prefix = base_directory
base_names = []
while (r = chop_basename(base_prefix))
base_prefix, basename = r
base_names.unshift basename if basename != '.'
end
unless SAME_PATHS[dest_prefix, base_prefix]
raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}"
end
while !dest_names.empty? &&
!base_names.empty? &&
SAME_PATHS[dest_names.first, base_names.first]
dest_names.shift
base_names.shift
end
if base_names.include? '..'
raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
end
base_names.fill('..')
relpath_names = base_names + dest_names
if relpath_names.empty?
Pathname.new('.')
else
Pathname.new(File.join(*relpath_names))
end
end
def entries
Dir.entries(@path).map { |f| self.class.new(f) }
end
alias === ==
alias eql? ==
alias to_s to_path
alias to_str to_path
end
module Kernel
def Pathname(path)
Pathname.new(path)
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/prettyprint.rb | stdlib/prettyprint.rb | # frozen_string_literal: true
#
# 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:
# * newline object and space generation block for PrettyPrint.new
# * optional width argument for PrettyPrint#text
# * PrettyPrint#breakable
#
# There are several candidate uses:
# * text formatting using proportional fonts
# * multibyte characters which has columns different to number of bytes
# * non-string formatting
#
# == Bugs
# * Box based formatting?
# * Other (better) model/algorithm?
#
# Report any bugs at http://bugs.ruby-lang.org
#
# == References
# Christian Lindig, Strictly Pretty, March 2000,
# http://www.st.cs.uni-sb.de/~lindig/papers/#pretty
#
# Philip Wadler, A prettier printer, March 1998,
# http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier
#
# == Author
# Tanaka Akira <akr@fsij.org>
#
class PrettyPrint
# This is a convenience method which is same as follows:
#
# begin
# q = PrettyPrint.new(output, maxwidth, newline, &genspace)
# ...
# q.flush
# output
# end
#
def PrettyPrint.format(output=''.dup, maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n})
q = PrettyPrint.new(output, maxwidth, newline, &genspace)
yield q
q.flush
output
end
# This is similar to PrettyPrint::format but the result has no breaks.
#
# +maxwidth+, +newline+ and +genspace+ are ignored.
#
# The invocation of +breakable+ in the block doesn't break a line and is
# treated as just an invocation of +text+.
#
def PrettyPrint.singleline_format(output=''.dup, maxwidth=nil, newline=nil, genspace=nil)
q = SingleLine.new(output)
yield q
output
end
# Creates a buffer for pretty printing.
#
# +output+ is an output target. If it is not specified, '' is assumed. It
# should have a << method which accepts the first argument +obj+ of
# PrettyPrint#text, the first argument +sep+ of PrettyPrint#breakable, the
# first argument +newline+ of PrettyPrint.new, and the result of a given
# block for PrettyPrint.new.
#
# +maxwidth+ specifies maximum line length. If it is not specified, 79 is
# assumed. However actual outputs may overflow +maxwidth+ if long
# non-breakable texts are provided.
#
# +newline+ is used for line breaks. "\n" is used if it is not specified.
#
# The block is used to generate spaces. {|width| ' ' * width} is used if it
# is not given.
#
def initialize(output=''.dup, maxwidth=79, newline="\n", &genspace)
@output = output
@maxwidth = maxwidth
@newline = newline
@genspace = genspace || lambda {|n| ' ' * n}
@output_width = 0
@buffer_width = 0
@buffer = []
root_group = Group.new(0)
@group_stack = [root_group]
@group_queue = GroupQueue.new(root_group)
@indent = 0
end
# The output object.
#
# This defaults to '', and should accept the << method
attr_reader :output
# The maximum width of a line, before it is separated in to a newline
#
# This defaults to 79, and should be a Fixnum
attr_reader :maxwidth
# The value that is appended to +output+ to add a new line.
#
# This defaults to "\n", and should be String
attr_reader :newline
# A lambda or Proc, that takes one argument, of a Fixnum, and returns
# the corresponding number of spaces.
#
# By default this is:
# lambda {|n| ' ' * n}
attr_reader :genspace
# The number of spaces to be indented
attr_reader :indent
# The PrettyPrint::GroupQueue of groups in stack to be pretty printed
attr_reader :group_queue
# Returns the group most recently added to the stack.
#
# Contrived example:
# out = ""
# => ""
# q = PrettyPrint.new(out)
# => #<PrettyPrint:0x82f85c0 @output="", @maxwidth=79, @newline="\n", @genspace=#<Proc:0x82f8368@/home/vbatts/.rvm/rubies/ruby-head/lib/ruby/2.0.0/prettyprint.rb:82 (lambda)>, @output_width=0, @buffer_width=0, @buffer=[], @group_stack=[#<PrettyPrint::Group:0x82f8138 @depth=0, @breakables=[], @break=false>], @group_queue=#<PrettyPrint::GroupQueue:0x82fb7c0 @queue=[[#<PrettyPrint::Group:0x82f8138 @depth=0, @breakables=[], @break=false>]]>, @indent=0>
# q.group {
# q.text q.current_group.inspect
# q.text q.newline
# q.group(q.current_group.depth + 1) {
# q.text q.current_group.inspect
# q.text q.newline
# q.group(q.current_group.depth + 1) {
# q.text q.current_group.inspect
# q.text q.newline
# q.group(q.current_group.depth + 1) {
# q.text q.current_group.inspect
# q.text q.newline
# }
# }
# }
# }
# => 284
# puts out
# #<PrettyPrint::Group:0x8354758 @depth=1, @breakables=[], @break=false>
# #<PrettyPrint::Group:0x8354550 @depth=2, @breakables=[], @break=false>
# #<PrettyPrint::Group:0x83541cc @depth=3, @breakables=[], @break=false>
# #<PrettyPrint::Group:0x8347e54 @depth=4, @breakables=[], @break=false>
def current_group
@group_stack.last
end
# Breaks the buffer into lines that are shorter than #maxwidth
def break_outmost_groups
while @maxwidth < @output_width + @buffer_width
return unless group = @group_queue.deq
until group.breakables.empty?
data = @buffer.shift
@output_width = data.output(@output, @output_width)
@buffer_width -= data.width
end
while !@buffer.empty? && Text === @buffer.first
text = @buffer.shift
@output_width = text.output(@output, @output_width)
@buffer_width -= text.width
end
end
end
# This adds +obj+ as a text of +width+ columns in width.
#
# If +width+ is not specified, obj.length is used.
#
def text(obj, width=obj.length)
if @buffer.empty?
@output << obj
@output_width += width
else
text = @buffer.last
unless Text === text
text = Text.new
@buffer << text
end
text.add(obj, width)
@buffer_width += width
break_outmost_groups
end
end
# This is similar to #breakable except
# the decision to break or not is determined individually.
#
# Two #fill_breakable under a group may cause 4 results:
# (break,break), (break,non-break), (non-break,break), (non-break,non-break).
# This is different to #breakable because two #breakable under a group
# may cause 2 results:
# (break,break), (non-break,non-break).
#
# The text +sep+ is inserted if a line is not broken at this point.
#
# If +sep+ is not specified, " " is used.
#
# If +width+ is not specified, +sep.length+ is used. You will have to
# specify this when +sep+ is a multibyte character, for example.
#
def fill_breakable(sep=' ', width=sep.length)
group { breakable sep, width }
end
# This says "you can break a line here if necessary", and a +width+\-column
# text +sep+ is inserted if a line is not broken at the point.
#
# If +sep+ is not specified, " " is used.
#
# If +width+ is not specified, +sep.length+ is used. You will have to
# specify this when +sep+ is a multibyte character, for example.
#
def breakable(sep=' ', width=sep.length)
group = @group_stack.last
if group.break?
flush
@output << @newline
@output << @genspace.call(@indent)
@output_width = @indent
@buffer_width = 0
else
@buffer << Breakable.new(sep, width, self)
@buffer_width += width
break_outmost_groups
end
end
# Groups line break hints added in the block. The line break hints are all
# to be used or not.
#
# If +indent+ is specified, the method call is regarded as nested by
# nest(indent) { ... }.
#
# If +open_obj+ is specified, <tt>text open_obj, open_width</tt> is called
# before grouping. If +close_obj+ is specified, <tt>text close_obj,
# close_width</tt> is called after grouping.
#
def group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length)
text open_obj, open_width
group_sub {
nest(indent) {
yield
}
}
text close_obj, close_width
end
# Takes a block and queues a new group that is indented 1 level further.
def group_sub
group = Group.new(@group_stack.last.depth + 1)
@group_stack.push group
@group_queue.enq group
begin
yield
ensure
@group_stack.pop
if group.breakables.empty?
@group_queue.delete group
end
end
end
# Increases left margin after newline with +indent+ for line breaks added in
# the block.
#
def nest(indent)
@indent += indent
begin
yield
ensure
@indent -= indent
end
end
# outputs buffered data.
#
def flush
@buffer.each {|data|
@output_width = data.output(@output, @output_width)
}
@buffer.clear
@buffer_width = 0
end
# The Text class is the means by which to collect strings from objects.
#
# This class is intended for internal use of the PrettyPrint buffers.
class Text # :nodoc:
# Creates a new text object.
#
# This constructor takes no arguments.
#
# The workflow is to append a PrettyPrint::Text object to the buffer, and
# being able to call the buffer.last() to reference it.
#
# As there are objects, use PrettyPrint::Text#add to include the objects
# and the width to utilized by the String version of this object.
def initialize
@objs = []
@width = 0
end
# The total width of the objects included in this Text object.
attr_reader :width
# Render the String text of the objects that have been added to this Text object.
#
# Output the text to +out+, and increment the width to +output_width+
def output(out, output_width)
@objs.each {|obj| out << obj}
output_width + @width
end
# Include +obj+ in the objects to be pretty printed, and increment
# this Text object's total width by +width+
def add(obj, width)
@objs << obj
@width += width
end
end
# The Breakable class is used for breaking up object information
#
# This class is intended for internal use of the PrettyPrint buffers.
class Breakable # :nodoc:
# Create a new Breakable object.
#
# Arguments:
# * +sep+ String of the separator
# * +width+ Fixnum width of the +sep+
# * +q+ parent PrettyPrint object, to base from
def initialize(sep, width, q)
@obj = sep
@width = width
@pp = q
@indent = q.indent
@group = q.current_group
@group.breakables.push self
end
# Holds the separator String
#
# The +sep+ argument from ::new
attr_reader :obj
# The width of +obj+ / +sep+
attr_reader :width
# The number of spaces to indent.
#
# This is inferred from +q+ within PrettyPrint, passed in ::new
attr_reader :indent
# Render the String text of the objects that have been added to this
# Breakable object.
#
# Output the text to +out+, and increment the width to +output_width+
def output(out, output_width)
@group.breakables.shift
if @group.break?
out << @pp.newline
out << @pp.genspace.call(@indent)
@indent
else
@pp.group_queue.delete @group if @group.breakables.empty?
out << @obj
output_width + @width
end
end
end
# The Group class is used for making indentation easier.
#
# While this class does neither the breaking into newlines nor indentation,
# it is used in a stack (as well as a queue) within PrettyPrint, to group
# objects.
#
# For information on using groups, see PrettyPrint#group
#
# This class is intended for internal use of the PrettyPrint buffers.
class Group # :nodoc:
# Create a Group object
#
# Arguments:
# * +depth+ - this group's relation to previous groups
def initialize(depth)
@depth = depth
@breakables = []
@break = false
end
# This group's relation to previous groups
attr_reader :depth
# Array to hold the Breakable objects for this Group
attr_reader :breakables
# Makes a break for this Group, and returns true
def break
@break = true
end
# Boolean of whether this Group has made a break
def break?
@break
end
# Boolean of whether this Group has been queried for being first
#
# This is used as a predicate, and ought to be called first.
def first?
if defined? @first
false
else
@first = false
true
end
end
end
# The GroupQueue class is used for managing the queue of Group to be pretty
# printed.
#
# This queue groups the Group objects, based on their depth.
#
# This class is intended for internal use of the PrettyPrint buffers.
class GroupQueue # :nodoc:
# Create a GroupQueue object
#
# Arguments:
# * +groups+ - one or more PrettyPrint::Group objects
def initialize(*groups)
@queue = []
groups.each {|g| enq g}
end
# Enqueue +group+
#
# This does not strictly append the group to the end of the queue,
# but instead adds it in line, base on the +group.depth+
def enq(group)
depth = group.depth
@queue << [] until depth < @queue.length
@queue[depth] << group
end
# Returns the outer group of the queue
def deq
@queue.each {|gs|
(gs.length-1).downto(0) {|i|
unless gs[i].breakables.empty?
group = gs.slice!(i, 1).first
group.break
return group
end
}
gs.each {|group| group.break}
gs.clear
}
return nil
end
# Remote +group+ from this queue
def delete(group)
@queue[group.depth].delete(group)
end
end
# PrettyPrint::SingleLine is used by PrettyPrint.singleline_format
#
# It is passed to be similar to a PrettyPrint object itself, by responding to:
# * #text
# * #breakable
# * #nest
# * #group
# * #flush
# * #first?
#
# but instead, the output has no line breaks
#
class SingleLine
# Create a PrettyPrint::SingleLine object
#
# Arguments:
# * +output+ - String (or similar) to store rendered text. Needs to respond to '<<'
# * +maxwidth+ - Argument position expected to be here for compatibility.
# This argument is a noop.
# * +newline+ - Argument position expected to be here for compatibility.
# This argument is a noop.
def initialize(output, maxwidth=nil, newline=nil)
@output = output
@first = [true]
end
# Add +obj+ to the text to be output.
#
# +width+ argument is here for compatibility. It is a noop argument.
def text(obj, width=nil)
@output << obj
end
# Appends +sep+ to the text to be output. By default +sep+ is ' '
#
# +width+ argument is here for compatibility. It is a noop argument.
def breakable(sep=' ', width=nil)
@output << sep
end
# Takes +indent+ arg, but does nothing with it.
#
# Yields to a block.
def nest(indent) # :nodoc:
yield
end
# Opens a block for grouping objects to be pretty printed.
#
# Arguments:
# * +indent+ - noop argument. Present for compatibility.
# * +open_obj+ - text appended before the &blok. Default is ''
# * +close_obj+ - text appended after the &blok. Default is ''
# * +open_width+ - noop argument. Present for compatibility.
# * +close_width+ - noop argument. Present for compatibility.
def group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil)
@first.push true
@output << open_obj
yield
@output << close_obj
@first.pop
end
# Method present for compatibility, but is a noop
def flush # :nodoc:
end
# This is used as a predicate, and ought to be called first.
def first?
result = @first[-1]
@first[-1] = false
result
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/rbconfig.rb | stdlib/rbconfig.rb | module RbConfig
versions = RUBY_VERSION.split('.')
CONFIG = {
'ruby_version' => RUBY_VERSION,
'MAJOR' => versions[0],
'MINOR' => versions[1],
'TEENY' => versions[2],
'RUBY' => RUBY_ENGINE,
'RUBY_INSTALL_NAME' => RUBY_ENGINE,
'ruby_install_name' => RUBY_ENGINE,
'RUBY_SO_NAME' => RUBY_ENGINE,
'target_os' => 'ECMA-262',
'host_os' => 'ECMA-262',
'PATH_SEPARATOR' => ':',
'EXEEXT' => '',
'bindir' => '',
}
end
# required for mspec it would appear
RUBY_EXE = 'bundle exec exe/opal'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal-parser.rb | stdlib/opal-parser.rb | # helpers: call, raise
# backtick_javascript: true
# parser uses String#unpack
require 'corelib/string/unpack'
require 'opal/compiler'
require 'opal/erb'
require 'opal/version'
module Kernel
def eval(str, binding = nil, file = nil, line = nil)
str = ::Opal.coerce_to!(str, String, :to_str)
default_eval_options = { file: file || '(eval)', eval: true }
compiling_options = __OPAL_COMPILER_CONFIG__.merge(default_eval_options)
compiler = Opal::Compiler.new(str, compiling_options)
code = compiler.compile
code += compiler.source_map.to_data_uri_comment unless compiling_options[:no_source_map]
if binding
binding.js_eval(code)
else
%x{
return (function(self) {
return eval(#{code});
})(self)
}
end
end
def require_remote(url)
%x{
var r = new XMLHttpRequest();
r.open("GET", url, false);
r.send('');
}
eval `r.responseText`
end
end
%x{
var $has_own = Object.hasOwn || $call.bind(Object.prototype.hasOwnProperty);
Opal.compile = function(str, options) {
try {
str = #{::Opal.coerce_to!(`str`, String, :to_str)}
if (options) options = Opal.hash(options);
return Opal.$opal_compile(str, options);
}
catch (e) {
if (e.$$class === Opal.Opal.SyntaxError) {
var err = Opal.SyntaxError.$new(e.message);
err.$set_backtrace(e.$backtrace());
throw(err);
}
else { throw e; }
}
};
Opal['eval'] = function(str, options) {
if (!options) { options = new Map(); }
options.set('eval', true);
return eval(Opal.compile(str, options));
};
function run_ruby_scripts() {
var tag, tags = document.getElementsByTagName('script');
for (var i = 0, len = tags.length; i < len; i++) {
tag = tags[i];
if (tag.type === "text/ruby") {
if (tag.src) Opal.Kernel.$require_remote(tag.src);
if (tag.innerHTML) Opal.Kernel.$eval(tag.innerHTML);
}
}
}
if (typeof(document) !== 'undefined') {
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', run_ruby_scripts, false);
}
else {
window.attachEvent('onload', run_ruby_scripts);
}
}
}
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/erb.rb | stdlib/erb.rb | # backtick_javascript: true
require 'template'
class ERB
module Util
`var escapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": '''};`
`var escape_regexp = /[&<>"']/g;`
def html_escape(str)
`("" + str).replace(escape_regexp, function (m) { return escapes[m] })`
end
alias h html_escape
module_function :h
module_function :html_escape
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal-replutils.rb | stdlib/opal-replutils.rb | # backtick_javascript: true
# await: true
require 'await'
require 'pp'
require 'stringio'
module REPLUtils
module_function
def ls(object, colorize)
methods = imethods = object.methods
ancestors = object.class.ancestors
constants = []
ivs = object.instance_variables
cvs = []
if [Class, Module].include? object.class
imethods = object.instance_methods
ancestors = object.ancestors
constants = object.constants
cvs = object.class_variables
end
if colorize
blue = ->(i) { "\e[1;34m#{i}\e[0m" }
dark_blue = ->(i) { "\e[34m#{i}\e[0m" }
else
blue = dark_blue = ->(i) { i }
end
out = ''
out = "#{blue['class variables']}: #{cvs.map { |i| dark_blue[i] }.sort.join(' ')}\n" + out unless cvs.empty?
out = "#{blue['instance variables']}: #{ivs.map { |i| dark_blue[i] }.sort.join(' ')}\n" + out unless ivs.empty?
ancestors.each do |a|
im = a.instance_methods(false)
meths = (im & imethods)
methods -= meths
imethods -= meths
next if meths.empty? || [Object, BasicObject, Kernel, PP::ObjectMixin].include?(a)
out = "#{blue["#{a.name}#methods"]}: #{meths.sort.join(' ')}\n" + out
end
methods &= object.methods(false)
out = "#{blue['self.methods']}: #{methods.sort.join(' ')}\n" + out unless methods.empty?
out = "#{blue['constants']}: #{constants.map { |i| dark_blue[i] }.sort.join(' ')}\n" + out unless constants.empty?
out
end
def eval_and_print(func, mode, colorize, binding = nil)
printer = if colorize
->(i) do
ColorPrinter.default(i)
rescue => e
ColorPrinter.colorize(Opal.inspect(i))
end
else
->(i) do
out = []
PP.pp(i, out)
out.join
rescue
Opal.inspect(i)
end
end
%x{
var $_result = binding === nil ? eval(func) : binding.$js_eval(func);
if (mode == 'silent') return nil;
if ($_result === null) {
return "=> null";
}
else if (typeof $_result === 'undefined') {
return "=> undefined";
}
else if (typeof $_result.$$class === 'undefined') {
try {
var json = JSON.stringify($_result, null, 2);
if (!colorize) json = #{ColorPrinter.colorize(`json`)}
return "=> " + $_result.toString() + " => " + json;
}
catch {
return "=> " + $_result.toString();
}
}
else {
if (mode == 'ls') {
return #{ls(`$_result`, colorize)};
}
else {
var pretty = #{printer.call(`$_result`)};
// Is it multiline? If yes, add a linebreak
if (pretty.match(/\n.*?\n/)) pretty = "\n" + pretty;
return "=> " + pretty;
}
}
}
rescue Exception => e # rubocop:disable Lint/RescueException
e.full_message(highlight: true)
end
def eval_and_print_async(func, mode, colorize, binding = nil)
return eval_and_print(func, mode, colorize, binding)
# bogus call to make this method async
nil.__await__ # rubocop:disable Lint/UnreachableCode
end
def js_repl
while (line = gets)
input = JSON.parse(line)
out = eval_and_print_async(input[:code], input[:mode], input[:colors]).__await__
puts out if out
puts '<<<ready>>>'
end
end
# Slightly based on Pry's implementation
class ColorPrinter < ::PP
# Taken from CodeRay
TOKEN_COLORS = {
debug: "\e[1;37;44m",
annotation: "\e[34m",
attribute_name: "\e[35m",
attribute_value: "\e[31m",
binary: {
self: "\e[31m",
char: "\e[1;31m",
delimiter: "\e[1;31m",
},
char: {
self: "\e[35m",
delimiter: "\e[1;35m"
},
class: "\e[1;35;4m",
class_variable: "\e[36m",
color: "\e[32m",
comment: {
self: "\e[1;30m",
char: "\e[37m",
delimiter: "\e[37m",
},
constant: "\e[1;34;4m",
decorator: "\e[35m",
definition: "\e[1;33m",
directive: "\e[33m",
docstring: "\e[31m",
doctype: "\e[1;34m",
done: "\e[1;30;2m",
entity: "\e[31m",
error: "\e[1;37;41m",
exception: "\e[1;31m",
float: "\e[1;35m",
function: "\e[1;34m",
global_variable: "\e[1;32m",
hex: "\e[1;36m",
id: "\e[1;34m",
include: "\e[31m",
integer: "\e[1;34m",
imaginary: "\e[1;34m",
important: "\e[1;31m",
key: {
self: "\e[35m",
char: "\e[1;35m",
delimiter: "\e[1;35m",
},
keyword: "\e[32m",
label: "\e[1;33m",
local_variable: "\e[33m",
namespace: "\e[1;35m",
octal: "\e[1;34m",
predefined: "\e[36m",
predefined_constant: "\e[1;36m",
predefined_type: "\e[1;32m",
preprocessor: "\e[1;36m",
pseudo_class: "\e[1;34m",
regexp: {
self: "\e[35m",
delimiter: "\e[1;35m",
modifier: "\e[35m",
char: "\e[1;35m",
},
reserved: "\e[32m",
shell: {
self: "\e[33m",
char: "\e[1;33m",
delimiter: "\e[1;33m",
escape: "\e[1;33m",
},
string: {
self: "\e[31m",
modifier: "\e[1;31m",
char: "\e[1;35m",
delimiter: "\e[1;31m",
escape: "\e[1;31m",
},
symbol: {
self: "\e[33m",
delimiter: "\e[1;33m",
},
tag: "\e[32m",
type: "\e[1;34m",
value: "\e[36m",
variable: "\e[34m",
insert: {
self: "\e[42m",
insert: "\e[1;32;42m",
eyecatcher: "\e[102m",
},
delete: {
self: "\e[41m",
delete: "\e[1;31;41m",
eyecatcher: "\e[101m",
},
change: {
self: "\e[44m",
change: "\e[37;44m",
},
head: {
self: "\e[45m",
filename: "\e[37;45m",
},
reset: "\e[0m",
}
TOKEN_COLORS[:keyword] = TOKEN_COLORS[:reserved]
TOKEN_COLORS[:method] = TOKEN_COLORS[:function]
TOKEN_COLORS[:escape] = TOKEN_COLORS[:delimiter]
def self.default(obj, width = 79)
pager = StringIO.new
pp(obj, pager, width)
pager.string
end
def self.pp(obj, output = $DEFAULT_OUTPUT, max_width = 79)
queue = ColorPrinter.new(output, max_width, "\n")
queue.guard_inspect_key { queue.pp(obj) }
queue.flush
output << "\n"
end
def text(str, max_width = str.length)
super(ColorPrinter.colorize(str), max_width)
end
def self.token(string, *name)
TOKEN_COLORS.dig(*name) + string + TOKEN_COLORS[:reset]
end
NUMBER = '[+-]?(?:0x[0-9a-fA-F]+|[0-9.]+(?:e[+-][0-9]+|i)?)'
REGEXP = '/.*?/[iesu]*'
STRING = '".*?"'
TOKEN_REGEXP = /(\s+|=>|[@$:]?[a-z]\w+|[A-Z]\w+|#{NUMBER}|#{REGEXP}|#{STRING}|#<.*?[> ]|.)/
def self.tokenize(str)
str.scan(TOKEN_REGEXP).map(&:first)
end
def self.colorize(str)
tokens = tokenize(str)
tokens.map do |tok|
case tok
when /^[0-9+-]/
if /[.e]/ =~ tok
token(tok, :float)
else
token(tok, :integer)
end
when /^"/
token(tok, :string, :self)
when /^:/
token(tok, :symbol, :self)
when /^[A-Z]/
token(tok, :constant)
when '<', '#', /^#</, '=', '>'
token(tok, :keyword)
when /^\/./
token(tok, :regexp, :self)
when 'true', 'false', 'nil'
token(tok, :predefined_constant)
else
token(tok, :reset)
end
end.join
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/cgi.rb | stdlib/cgi.rb | require 'cgi/util'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/promise.rb | stdlib/promise.rb | # {Promise} is used to help structure asynchronous code.
#
# It is available in the Opal standard library, and can be required in any Opal
# application:
#
# require 'promise'
#
# ## Basic Usage
#
# Promises are created and returned as objects with the assumption that they
# will eventually be resolved or rejected, but never both. A {Promise} has
# a {#then} and {#fail} method (or one of their aliases) that can be used to
# register a block that gets called once resolved or rejected.
#
# promise = Promise.new
#
# promise.then {
# puts "resolved!"
# }.fail {
# puts "rejected!"
# }
#
# # some time later
# promise.resolve
#
# # => "resolved!"
#
# It is important to remember that a promise can only be resolved or rejected
# once, so the block will only ever be called once (or not at all).
#
# ## Resolving Promises
#
# To resolve a promise, means to inform the {Promise} that it has succeeded
# or evaluated to a useful value. {#resolve} can be passed a value which is
# then passed into the block handler:
#
# def get_json
# promise = Promise.new
#
# HTTP.get("some_url") do |req|
# promise.resolve req.json
# end
#
# promise
# end
#
# get_json.then do |json|
# puts "got some JSON from server"
# end
#
# ## Rejecting Promises
#
# Promises are also designed to handle error cases, or situations where an
# outcome is not as expected. Taking the previous example, we can also pass
# a value to a {#reject} call, which passes that object to the registered
# {#fail} handler:
#
# def get_json
# promise = Promise.new
#
# HTTP.get("some_url") do |req|
# if req.ok?
# promise.resolve req.json
# else
# promise.reject req
# end
#
# promise
# end
#
# get_json.then {
# # ...
# }.fail { |req|
# puts "it went wrong: #{req.message}"
# }
#
# ## Chaining Promises
#
# Promises become even more useful when chained together. Each {#then} or
# {#fail} call returns a new {Promise} which can be used to chain more and more
# handlers together.
#
# promise.then { wait_for_something }.then { do_something_else }
#
# Rejections are propagated through the entire chain, so a "catch all" handler
# can be attached at the end of the tail:
#
# promise.then { ... }.then { ... }.fail { ... }
#
# ## Composing Promises
#
# {Promise.when} can be used to wait for more than one promise to resolve (or
# reject). Using the previous example, we could request two different json
# requests and wait for both to finish:
#
# Promise.when(get_json, get_json2).then |first, second|
# puts "got two json payloads: #{first}, #{second}"
# end
#
class Promise
def self.value(value)
new.resolve(value)
end
def self.error(value)
new.reject(value)
end
def self.when(*promises)
When.new(promises)
end
attr_reader :error, :prev, :next
def initialize(action = {})
@action = action
@realized = false
@exception = false
@value = nil
@error = nil
@delayed = false
@prev = nil
@next = []
end
def value
if Promise === @value
@value.value
else
@value
end
end
def act?
@action.key?(:success) || @action.key?(:always)
end
def action
@action.keys
end
def exception?
@exception
end
def realized?
@realized != false
end
def resolved?
@realized == :resolve
end
def rejected?
@realized == :reject
end
def ^(promise)
promise << self
self >> promise
promise
end
def <<(promise)
@prev = promise
self
end
def >>(promise)
@next << promise
if exception?
promise.reject(@delayed[0])
elsif resolved?
promise.resolve(@delayed ? @delayed[0] : value)
elsif rejected?
if !@action.key?(:failure) || Promise === (@delayed ? @delayed[0] : @error)
promise.reject(@delayed ? @delayed[0] : error)
elsif promise.action.include?(:always)
promise.reject(@delayed ? @delayed[0] : error)
end
end
self
end
def resolve(value = nil)
if realized?
raise ArgumentError, 'the promise has already been realized'
end
if Promise === value
return (value << @prev) ^ self
end
begin
block = @action[:success] || @action[:always]
if block
value = block.call(value)
end
resolve!(value)
rescue Exception => e
exception!(e)
end
self
end
def resolve!(value)
@realized = :resolve
@value = value
if @next.any?
@next.each { |p| p.resolve(value) }
else
@delayed = [value]
end
end
def reject(value = nil)
if realized?
raise ArgumentError, 'the promise has already been realized'
end
if Promise === value
return (value << @prev) ^ self
end
begin
block = @action[:failure] || @action[:always]
if block
value = block.call(value)
end
if @action.key?(:always)
resolve!(value)
else
reject!(value)
end
rescue Exception => e
exception!(e)
end
self
end
def reject!(value)
@realized = :reject
@error = value
if @next.any?
@next.each { |p| p.reject(value) }
else
@delayed = [value]
end
end
def exception!(error)
@exception = true
reject!(error)
end
def then(&block)
self ^ Promise.new(success: block)
end
def then!(&block)
there_can_be_only_one!
self.then(&block)
end
def fail(&block)
self ^ Promise.new(failure: block)
end
def fail!(&block)
there_can_be_only_one!
fail(&block)
end
def always(&block)
self ^ Promise.new(always: block)
end
def always!(&block)
there_can_be_only_one!
always(&block)
end
def trace(depth = nil, &block)
self ^ Trace.new(depth, block)
end
def trace!(*args, &block)
there_can_be_only_one!
trace(*args, &block)
end
def there_can_be_only_one!
if @next.any?
raise ArgumentError, 'a promise has already been chained'
end
end
def inspect
result = "#<#{self.class}(#{object_id})"
if @next.any?
result += " >> #{@next.inspect}"
end
result += if realized?
": #{(@value || @error).inspect}>"
else
'>'
end
result
end
def to_v2
v2 = PromiseV2.new
self.then { |i| v2.resolve(i) }.rescue { |i| v2.reject(i) }
v2
end
# PromiseV1 is not a native construct, we must convert it to a v2 promise
alias await to_v2
alias catch fail
alias catch! fail!
alias do then
alias do! then!
alias ensure always
alias ensure! always!
alias finally always
alias finally! always!
alias rescue fail
alias rescue! fail!
alias to_n to_v2
alias to_v1 itself
class Trace < self
def self.it(promise)
current = []
if promise.act? || promise.prev.nil?
current.push(promise.value)
end
prev = promise.prev
if prev
current.concat(it(prev))
else
current
end
end
def initialize(depth, block)
@depth = depth
super success: proc {
trace = Trace.it(self).reverse
trace.pop
if depth && depth <= trace.length
trace.shift(trace.length - depth)
end
block.call(*trace)
}
end
end
class When < self
def initialize(promises = [])
super()
@wait = []
promises.each do |promise|
wait promise
end
end
def each(&block)
raise ArgumentError, 'no block given' unless block
self.then do |values|
values.each(&block)
end
end
def collect(&block)
raise ArgumentError, 'no block given' unless block
self.then do |values|
When.new(values.map(&block))
end
end
def inject(*args, &block)
self.then do |values|
values.reduce(*args, &block)
end
end
def wait(promise)
unless Promise === promise
promise = Promise.value(promise)
end
if promise.act?
promise = promise.then
end
@wait << promise
promise.always do
try if @next.any?
end
self
end
def >>(*)
super.tap do
try
end
end
def try
if @wait.all?(&:realized?)
promise = @wait.find(&:rejected?)
if promise
reject(promise.error)
else
resolve(@wait.map(&:value))
end
end
end
alias map collect
alias reduce inject
alias and wait
end
end
PromiseV1 = Promise
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/await.rb | stdlib/await.rb | # helpers: coerce_to
# await: await
# backtick_javascript: true
%x{
var AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;
}
require 'promise/v2'
class Array
def map_await(&block)
i = 0
results = []
while i < `self.length`
results << yield(self[i]).await
i += 1
end
results
end
def each_await(&block)
i = 0
while i < `self.length`
yield(self[i]).await
i += 1
end
self
end
end
module Enumerable
def each_async(&block)
PromiseV2.when(*map(&block)).await
end
end
module Kernel
# Overwrite Kernel.exit to be async-capable.
def exit(status = true)
$__at_exit__ ||= []
until $__at_exit__.empty?
block = $__at_exit__.pop
block.call.await
end
%x{
if (status.$$is_boolean) {
status = status ? 0 : 1;
} else {
status = $coerce_to(status, #{Integer}, 'to_int')
}
Opal.exit(status);
}
nil
end
def sleep(seconds)
prom = PromiseV2.new
`setTimeout(#{proc { prom.resolve }}, #{seconds * 1000})`
prom
end
alias await itself
end
class Proc
def async?
`self instanceof AsyncFunction`
end
end
class Method
def async?
@method.async?
end
end
class BasicObject
def instance_exec_await(*args, &block)
::Kernel.raise ::ArgumentError, 'no block given' unless block
# The awaits are defined inside an x-string. Opal can't find them
# reliably and async-ify a method. Therefore, let's make Opal know
# this is an async method.
nil.__await__
%x{
var block_self = block.$$s,
result;
block.$$s = null;
if (self.$$is_a_module) {
self.$$eval = true;
try {
result = await block.apply(self, args);
}
finally {
self.$$eval = false;
}
}
else {
result = await block.apply(self, args);
}
block.$$s = block_self;
return result;
}
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/bigdecimal.rb | stdlib/bigdecimal.rb | # backtick_javascript: true
class BigDecimal < Numeric; end
require 'opal/raw'
require 'bigdecimal/bignumber'
module Kernel
def BigDecimal(initial, digits = 0)
bigdecimal = BigDecimal.allocate
bigdecimal.initialize(initial, digits)
bigdecimal
end
end
def BigDecimal.new(*args, **kwargs)
warn 'BigDecimal.new is deprecated; use BigDecimal() method instead.', uplevel: 1
BigDecimal(*args, **kwargs)
end
class BigDecimal < Numeric
VERSION = '0'
ROUND_MODE = 256
# NOTE: the numeric values of the ROUND_* constants
# follow BigNumber.js, they are NOT the same as MRI
ROUND_UP = 0
ROUND_DOWN = 1
ROUND_CEILING = 2
ROUND_FLOOR = 3
ROUND_HALF_UP = 4
ROUND_HALF_DOWN = 5
ROUND_HALF_EVEN = 6
SIGN_NaN = 0
SIGN_POSITIVE_ZERO = 1
SIGN_NEGATIVE_ZERO = -1
SIGN_POSITIVE_FINITE = 2
SIGN_NEGATIVE_FINITE = -2
SIGN_POSITIVE_INFINITE = 3
SIGN_NEGATIVE_INFINITE = -3
def self.limit(digits = nil)
@digits = digits if digits
@digits
end
def self.mode(mode, value = nil)
case mode
when ROUND_MODE
@round_mode = value if value
@round_mode || ROUND_HALF_UP
end
end
attr_reader :bignumber
def initialize(initial, digits = 0)
@bignumber = Opal::Raw.new(BigNumber, initial)
end
def ==(other)
case other
when self.class
bignumber.JS.equals(other.bignumber)
when Number
bignumber.JS.equals(other)
else
false
end
end
def <=>(other)
result = case other
when self.class
bignumber.JS.comparedTo(other.bignumber)
when Number
bignumber.JS.comparedTo(other)
end
`#{result} === null ? nil : #{result}`
end
def <(other)
return false if nan? || other && other.nan?
super
end
def <=(other)
return false if nan? || other && other.nan?
super
end
def >(other)
return false if nan? || other && other.nan?
super
end
def >=(other)
return false if nan? || other && other.nan?
super
end
def abs
BigDecimal(bignumber.JS.abs)
end
def add(other, digits = 0)
if digits.nil?
raise TypeError, 'wrong argument type nil (expected Fixnum)'
end
if digits < 0
raise ArgumentError, 'argument must be positive'
end
other, _ = coerce(other)
result = bignumber.JS.plus(other.bignumber)
if digits > 0
result = result.JS.toDigits(digits, self.class.mode(ROUND_MODE))
end
BigDecimal(result)
end
def ceil(n = nil)
unless bignumber.JS.isFinite
raise FloatDomainError, "Computation results to 'Infinity'"
end
if n.nil?
bignumber.JS.round(0, ROUND_CEILING).JS.toNumber
elsif n >= 0
BigDecimal(bignumber.JS.round(n, ROUND_CEILING))
else
BigDecimal(bignumber.JS.round(0, ROUND_CEILING))
end
end
def coerce(other)
case other
when self.class
[other, self]
when Number
[BigDecimal(other), self]
else
raise TypeError, "#{other.class} can't be coerced into #{self.class}"
end
end
def div(other, digits = nil)
return self / other if digits == 0
other, _ = coerce(other)
if nan? || other.nan?
raise FloatDomainError, "Computation results to 'NaN'(Not a Number)"
end
if digits.nil?
if other.zero?
raise ZeroDivisionError, 'divided by 0'
end
if infinite?
raise FloatDomainError, "Computation results to 'Infinity'"
end
return BigDecimal(bignumber.JS.dividedToIntegerBy(other.bignumber))
end
BigDecimal(bignumber.JS.dividedBy(other.bignumber).JS.round(digits, self.class.mode(ROUND_MODE)))
end
def finite?
bignumber.JS.isFinite
end
def infinite?
return nil if finite? || nan?
bignumber.JS.isNegative ? -1 : 1
end
def minus(other)
other, _ = coerce(other)
BigDecimal(bignumber.JS.minus(other.bignumber))
end
def mult(other, digits = nil)
other, _ = coerce(other)
if digits.nil?
return BigDecimal(bignumber.JS.times(other.bignumber))
end
BigDecimal(bignumber.JS.times(other.bignumber).JS.round(digits, self.class.mode(ROUND_MODE)))
end
def nan?
bignumber.JS.isNaN
end
def quo(other)
other, _ = coerce(other)
BigDecimal(bignumber.JS.dividedBy(other.bignumber))
end
def sign
if bignumber.JS.isNaN
return SIGN_NaN
end
if bignumber.JS.isZero
return bignumber.JS.isNegative ? SIGN_NEGATIVE_ZERO : SIGN_POSITIVE_ZERO
end
end
def sub(other, precision)
other, _ = coerce(other)
BigDecimal(bignumber.JS.minus(other.bignumber))
end
def to_f
bignumber.JS.toNumber
end
def to_s(s = '')
bignumber.JS.toString
end
def zero?
bignumber.JS.isZero
end
def power(other)
other, _ = coerce(other)
self.class.new(bignumber.JS.pow(other.bignumber))
end
def fix
self.class.new(bignumber.JS.trunc)
end
def trunc(other = nil)
if other.nil?
self.class.new(bignumber.JS.trunc)
else
other, _ = coerce(other)
self.class.new(bignumber.JS.round(other, ROUND_DOWN))
end
end
alias === ==
alias + add
alias - minus
alias * mult
alias / quo
alias ** power
alias pow power
alias inspect to_s
alias truncate trunc
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/delegate.rb | stdlib/delegate.rb | # frozen_string_literal: true
# helpers: freeze, freeze_props
# backtick_javascript: true
# = delegate -- Support for the Delegation Pattern
#
# This file ended up in Opal as a port of the following file:
# https://github.com/ruby/ruby/blob/master/lib/delegate.rb
#
# Documentation by James Edward Gray II and Gavin Sinclair
##
# 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
#
# == Notes
#
# Be advised, RDoc will not detect delegated methods.
#
require 'ruby2_keywords'
class Delegator < BasicObject
VERSION = '0.2.0'
kernel = ::Kernel.dup
kernel.class_eval do
alias_method :__raise__, :raise
%i[to_s inspect !~ === <=> hash].each do |m|
undef_method m
end
private_instance_methods.each do |m|
if /\Ablock_given\?\z|\Aiterator\?\z|\A__.*__\z/ =~ m
next
end
undef_method m
end
end
include kernel
# :stopdoc:
def self.const_missing(n)
::Object.const_get(n)
end
# :startdoc:
##
# :method: raise
# Use #__raise__ if your Delegator does not have a object to delegate the
# #raise method call.
#
#
# Pass in the _obj_ to delegate method calls to. All methods supported by
# _obj_ will be delegated to.
#
def initialize(obj)
__setobj__(obj)
end
#
# Handles the magic of delegation through \_\_getobj\_\_.
#
ruby2_keywords def method_missing(m, *args, &block) # rubocop:disable Style/MissingRespondToMissing
r = true
target = __getobj__ { r = false }
if r && target_respond_to?(target, m, false)
target.__send__(m, *args, &block)
elsif ::Kernel.method_defined?(m) || ::Kernel.private_method_defined?(m)
::Kernel.instance_method(m).bind_call(self, *args, &block)
else
super(m, *args, &block)
end
end
#
# Checks for a method provided by this the delegate object by forwarding the
# call through \_\_getobj\_\_.
#
def respond_to_missing?(m, include_private)
r = true
target = __getobj__ { r = false }
r &&= target_respond_to?(target, m, include_private)
if r && include_private && !target_respond_to?(target, m, false)
warn "delegator does not forward private method \##{m}", uplevel: 3
return false
end
r
end
KERNEL_RESPOND_TO = ::Kernel.instance_method(:respond_to?)
private_constant :KERNEL_RESPOND_TO
# Handle BasicObject instances
private def target_respond_to?(target, m, include_private)
case target
when Object
target.respond_to?(m, include_private)
else
if KERNEL_RESPOND_TO.bind_call(target, :respond_to?)
target.respond_to?(m, include_private)
else
KERNEL_RESPOND_TO.bind_call(target, m, include_private)
end
end
end
#
# Returns the methods available to this delegate object as the union
# of this object's and \_\_getobj\_\_ methods.
#
def methods(all = true)
__getobj__.methods(all) | super
end
#
# Returns the methods available to this delegate object as the union
# of this object's and \_\_getobj\_\_ public methods.
#
def public_methods(all = true)
__getobj__.public_methods(all) | super
end
#
# Returns the methods available to this delegate object as the union
# of this object's and \_\_getobj\_\_ protected methods.
#
def protected_methods(all = true)
__getobj__.protected_methods(all) | super
end
# Note: no need to specialize private_methods, since they are not forwarded
#
# Returns true if two objects are considered of equal value.
#
def ==(obj)
return true if obj.equal?(self)
__getobj__ == obj
end
#
# Returns true if two objects are not considered of equal value.
#
def !=(obj)
return false if obj.equal?(self)
__getobj__ != obj
end
#
# Returns true if two objects are considered of equal value.
#
def eql?(obj)
return true if obj.equal?(self)
obj.eql?(__getobj__)
end
#
# Delegates ! to the \_\_getobj\_\_
#
def !
!__getobj__
end
#
# This method must be overridden by subclasses and should return the object
# method calls are being delegated to.
#
def __getobj__
__raise__ ::NotImplementedError, "need to define `__getobj__'"
end
#
# This method must be overridden by subclasses and change the object delegate
# to _obj_.
#
def __setobj__(obj)
__raise__ ::NotImplementedError, "need to define `__setobj__'"
end
#
# Serialization support for the object returned by \_\_getobj\_\_.
#
def marshal_dump
ivars = instance_variables.reject { |var| /\A@delegate_/ =~ var }
[
:__v2__,
ivars, ivars.map { |var| instance_variable_get(var) },
__getobj__
]
end
#
# Reinitializes delegation from a serialized object.
#
def marshal_load(data)
version, vars, values, obj = data
if version == :__v2__
vars.each_with_index { |var, i| instance_variable_set(var, values[i]) }
__setobj__(obj)
else
__setobj__(data)
end
end
def initialize_clone(obj, freeze: nil) # :nodoc:
__setobj__(obj.__getobj__.clone(freeze: freeze))
end
def initialize_dup(obj) # :nodoc:
__setobj__(obj.__getobj__.dup)
end
private :initialize_clone, :initialize_dup
##
# :method: freeze
# Freeze both the object returned by \_\_getobj\_\_ and self.
#
def freeze
__getobj__.freeze
`$freeze_props(self)`
`$freeze(self)`
end
def frozen?
`(self.$$frozen || false)`
end
@delegator_api = public_instance_methods
def self.public_api # :nodoc:
@delegator_api
end
end
##
# 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 <tt>super</tt> 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 SimpleDelegator < Delegator
# Returns the current object method calls are being delegated to.
def __getobj__
unless defined?(@delegate_sd_obj)
return yield if block_given?
__raise__ ::ArgumentError, 'not delegated'
end
@delegate_sd_obj
end
#
# Changes the delegate object to _obj_.
#
# It's important to note that this does *not* cause SimpleDelegator's methods
# to change. Because of this, you probably only want to change delegation
# to objects of the same type as the original delegate.
#
# Here's an example of changing the delegation object.
#
# names = SimpleDelegator.new(%w{James Edward Gray II})
# puts names[1] # => Edward
# names.__setobj__(%w{Gavin Sinclair})
# puts names[1] # => Sinclair
#
def __setobj__(obj)
__raise__ ::ArgumentError, 'cannot delegate to self' if equal?(obj)
@delegate_sd_obj = obj
end
end
def Delegator.delegating_block(mid) # :nodoc:
->(*args, &block) do
target = __getobj__
target.__send__(mid, *args, &block)
end.ruby2_keywords
end
#
# The primary interface to this library. Use to setup delegation when defining
# your class.
#
# class MyClass < DelegateClass(ClassToDelegateTo) # Step 1
# def initialize
# super(obj_of_ClassToDelegateTo) # Step 2
# end
# end
#
# or:
#
# MyClass = DelegateClass(ClassToDelegateTo) do # Step 1
# def initialize
# super(obj_of_ClassToDelegateTo) # Step 2
# end
# end
#
# Here's a sample of use from Tempfile which is really a File object with a
# few special rules about storage location and when the File should be
# deleted. That makes for an almost textbook perfect example of how to use
# delegation.
#
# class Tempfile < DelegateClass(File)
# # constant and class member data initialization...
#
# def initialize(basename, tmpdir=Dir::tmpdir)
# # build up file path/name in var tmpname...
#
# @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
#
# # ...
#
# super(@tmpfile)
#
# # below this point, all methods of File are supported...
# end
#
# # ...
# end
#
def DelegateClass(superclass, &block)
klass = Class.new(Delegator)
ignores = [*::Delegator.public_api, :to_s, :inspect, :=~, :!~, :===]
protected_instance_methods = superclass.protected_instance_methods
protected_instance_methods -= ignores
public_instance_methods = superclass.public_instance_methods
public_instance_methods -= ignores
klass.module_eval do
def __getobj__ # :nodoc:
unless defined?(@delegate_dc_obj)
return yield if block_given?
__raise__ ::ArgumentError, 'not delegated'
end
@delegate_dc_obj
end
def __setobj__(obj) # :nodoc:
__raise__ ::ArgumentError, 'cannot delegate to self' if equal?(obj)
@delegate_dc_obj = obj
end
protected_instance_methods.each do |method|
define_method(method, Delegator.delegating_block(method))
protected method
end
public_instance_methods.each do |method|
define_method(method, Delegator.delegating_block(method))
end
end
klass.define_singleton_method :public_instance_methods do |all = true|
super(all) | superclass.public_instance_methods
end
klass.define_singleton_method :protected_instance_methods do |all = true|
super(all) | superclass.protected_instance_methods
end
klass.define_singleton_method :instance_methods do |all = true|
super(all) | superclass.instance_methods
end
klass.define_singleton_method :public_instance_method do |name|
super(name)
rescue NameError
raise unless self.public_instance_methods.include?(name)
superclass.public_instance_method(name)
end
klass.define_singleton_method :instance_method do |name|
super(name)
rescue NameError
raise unless instance_methods.include?(name)
superclass.instance_method(name)
end
klass.module_eval(&block) if block
klass
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/singleton.rb | stdlib/singleton.rb | module Singleton
def clone
raise TypeError, "can't clone instance of singleton #{self.class}"
end
def dup
raise TypeError, "can't dup instance of singleton #{self.class}"
end
module SingletonClassMethods
def clone
Singleton.__init__(super)
end
def inherited(sub_klass)
super
Singleton.__init__(sub_klass)
end
end
class << Singleton
def __init__(klass)
klass.instance_eval do
@singleton__instance__ = nil
end
def klass.instance
return @singleton__instance__ if @singleton__instance__
@singleton__instance__ = new
end
klass
end
def included(klass)
super
klass.extend SingletonClassMethods
Singleton.__init__(klass)
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/date.rb | stdlib/date.rb | # backtick_javascript: true
require 'forwardable'
require 'date/infinity'
require 'time'
class Date
include Comparable
extend Forwardable
JULIAN = Infinity.new
GREGORIAN = -Infinity.new
ITALY = 2_299_161 # 1582-10-15
ENGLAND = 2_361_222 # 1752-09-14
MONTHNAMES = [nil] + %w[January February March April May June July August September October November December]
ABBR_MONTHNAMES = %w[jan feb mar apr may jun jul aug sep oct nov dec]
DAYNAMES = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday]
ABBR_DAYNAMES = %w[Sun Mon Tue Wed Thu Fri Sat]
class << self
def wrap(native)
instance = allocate
`#{instance}.start = #{ITALY}`
`#{instance}.date = #{native}`
instance
end
def parse(string, comp = true)
%x{
var current_date = new Date();
var current_day = current_date.getDate(),
current_month = current_date.getMonth(),
current_year = current_date.getFullYear(),
current_wday = current_date.getDay(),
full_month_name_regexp = #{MONTHNAMES.compact.join('|')};
function match1(match) { return match[1]; }
function match2(match) { return match[2]; }
function match3(match) { return match[3]; }
function match4(match) { return match[4]; }
// Converts passed short year (0..99)
// to a 4-digits year in the range (1969..2068)
function fromShortYear(fn) {
return function(match) {
var short_year = fn(match);
if (short_year >= 69) {
short_year += 1900;
} else {
short_year += 2000;
}
return short_year;
}
}
// Converts month abbr (nov) to a month number
function fromMonthAbbr(fn) {
return function(match) {
var abbr = fn(match).toLowerCase();
return #{ABBR_MONTHNAMES.index(`abbr`)} + 1;
}
}
function toInt(fn) {
return function(match) {
var value = fn(match);
return parseInt(value, 10);
}
}
// Depending on the 'comp' value appends 20xx to a passed year
function to2000(fn) {
return function(match) {
var value = fn(match);
if (comp) {
return value + 2000;
} else {
return value;
}
}
}
// Converts passed week day name to a day number
function fromDayName(fn) {
return function(match) {
var dayname = fn(match),
wday = #{DAYNAMES.map(&:downcase).index(`dayname`.downcase)};
return current_day - current_wday + wday;
}
}
// Converts passed month name to a month number
function fromFullMonthName(fn) {
return function(match) {
var month_name = fn(match);
return #{MONTHNAMES.compact.map(&:downcase).index(`month_name`.downcase)} + 1;
}
}
var rules = [
{
// DD as month day number
regexp: /^(\d{2})$/,
year: current_year,
month: current_month,
day: toInt(match1)
},
{
// DDD as year day number
regexp: /^(\d{3})$/,
year: current_year,
month: 0,
day: toInt(match1)
},
{
// MMDD as month and day
regexp: /^(\d{2})(\d{2})$/,
year: current_year,
month: toInt(match1),
day: toInt(match2)
},
{
// YYDDD as year and day number in 1969--2068
regexp: /^(\d{2})(\d{3})$/,
year: fromShortYear(toInt(match1)),
month: 0,
day: toInt(match2)
},
{
// YYMMDD as year, month and day in 1969--2068
regexp: /^(\d{2})(\d{2})(\d{2})$/,
year: fromShortYear(toInt(match1)),
month: toInt(match2),
day: toInt(match3)
},
{
// YYYYDDD as year and day number
regexp: /^(\d{4})(\d{3})$/,
year: toInt(match1),
month: 0,
day: toInt(match2)
},
{
// YYYYMMDD as year, month and day number
regexp: /^(\d{4})(\d{2})(\d{2})$/,
year: toInt(match1),
month: toInt(match2),
day: toInt(match3)
},
{
// mmm YYYY
regexp: /^([a-z]{3})[\s\.\/\-](\d{3,4})$/,
year: toInt(match2),
month: fromMonthAbbr(match1),
day: 1
},
{
// DD mmm YYYY
regexp: /^(\d{1,2})[\s\.\/\-]([a-z]{3})[\s\.\/\-](\d{3,4})$/i,
year: toInt(match3),
month: fromMonthAbbr(match2),
day: toInt(match1)
},
{
// mmm DD YYYY
regexp: /^([a-z]{3})[\s\.\/\-](\d{1,2})[\s\.\/\-](\d{3,4})$/i,
year: toInt(match3),
month: fromMonthAbbr(match1),
day: toInt(match2)
},
{
// YYYY mmm DD
regexp: /^(\d{3,4})[\s\.\/\-]([a-z]{3})[\s\.\/\-](\d{1,2})$/i,
year: toInt(match1),
month: fromMonthAbbr(match2),
day: toInt(match3)
},
{
// YYYY-MM-DD YYYY/MM/DD YYYY.MM.DD
regexp: /^(\-?\d{3,4})[\s\.\/\-](\d{1,2})[\s\.\/\-](\d{1,2})$/,
year: toInt(match1),
month: toInt(match2),
day: toInt(match3)
},
{
// YY-MM-DD
regexp: /^(\d{2})[\s\.\/\-](\d{1,2})[\s\.\/\-](\d{1,2})$/,
year: to2000(toInt(match1)),
month: toInt(match2),
day: toInt(match3)
},
{
// DD-MM-YYYY
regexp: /^(\d{1,2})[\s\.\/\-](\d{1,2})[\s\.\/\-](\-?\d{3,4})$/,
year: toInt(match3),
month: toInt(match2),
day: toInt(match1)
},
{
// ddd
regexp: new RegExp("^(" + #{DAYNAMES.join('|')} + ")$", 'i'),
year: current_year,
month: current_month,
day: fromDayName(match1)
},
{
// monthname daynumber YYYY
regexp: new RegExp("^(" + full_month_name_regexp + ")[\\s\\.\\/\\-](\\d{1,2})(th|nd|rd)[\\s\\.\\/\\-](\\-?\\d{3,4})$", "i"),
year: toInt(match4),
month: fromFullMonthName(match1),
day: toInt(match2)
},
{
// monthname daynumber
regexp: new RegExp("^(" + full_month_name_regexp + ")[\\s\\.\\/\\-](\\d{1,2})(th|nd|rd)", "i"),
year: current_year,
month: fromFullMonthName(match1),
day: toInt(match2)
},
{
// daynumber monthname YYYY
regexp: new RegExp("^(\\d{1,2})(th|nd|rd)[\\s\\.\\/\\-](" + full_month_name_regexp + ")[\\s\\.\\/\\-](\\-?\\d{3,4})$", "i"),
year: toInt(match4),
month: fromFullMonthName(match3),
day: toInt(match1)
},
{
// YYYY monthname daynumber
regexp: new RegExp("^(\\-?\\d{3,4})[\\s\\.\\/\\-](" + full_month_name_regexp + ")[\\s\\.\\/\\-](\\d{1,2})(th|nd|rd)$", "i"),
year: toInt(match1),
month: fromFullMonthName(match2),
day: toInt(match3)
}
]
var rule, i, match;
for (i = 0; i < rules.length; i++) {
rule = rules[i];
match = rule.regexp.exec(string);
if (match) {
var year = rule.year;
if (typeof(year) === 'function') {
year = year(match);
}
var month = rule.month;
if (typeof(month) === 'function') {
month = month(match) - 1
}
var day = rule.day;
if (typeof(day) === 'function') {
day = day(match);
}
var result = new Date(year, month, day);
// an edge case, JS can't handle 'new Date(1)', minimal year is 1970
if (year >= 0 && year <= 1970) {
result.setFullYear(year);
}
return #{wrap `result`};
}
}
}
raise ArgumentError, 'invalid date'
end
def today
wrap `new Date()`
end
def gregorian_leap?(year)
`(new Date(#{year}, 1, 29).getMonth()-1) === 0`
end
alias civil new
end
def initialize(year = -4712, month = 1, day = 1, start = ITALY)
%x{
// Because of Gregorian reform calendar goes from 1582-10-04 to 1582-10-15.
// All days in between end up as 4 october.
if (year === 1582 && month === 10 && day > 4 && day < 15) {
day = 4;
}
}
@date = `new Date(year, month - 1, day)`
@start = start
end
attr_reader :start
def <=>(other)
%x{
if (other.$$is_number) {
return #{jd <=> other}
}
if (#{::Date === other}) {
var a = #{@date}, b = #{other}.date;
if (!Opal.is_a(#{self}, #{::DateTime})) a.setHours(0, 0, 0, 0);
if (!Opal.is_a(#{other}, #{::DateTime})) b.setHours(0, 0, 0, 0);
if (a < b) {
return -1;
}
else if (a > b) {
return 1;
}
else {
return 0;
}
} else {
return nil;
}
}
end
def >>(n)
`if (!n.$$is_number) #{raise ::TypeError}`
self << -n
end
def <<(n)
`if (!n.$$is_number) #{raise ::TypeError}`
prev_month(n)
end
def clone
date = Date.wrap(@date.dup)
`date.start = #{@start}`
date
end
def_delegators :@date, :sunday?, :monday?, :tuesday?, :wednesday?, :thursday?, :friday?, :saturday?,
:day, :month, :year, :wday, :yday
alias mday day
alias mon month
def jd
%x{
//Adapted from http://www.physics.sfasu.edu/astro/javascript/julianday.html
var mm = #{@date}.getMonth() + 1,
dd = #{@date}.getDate(),
yy = #{@date}.getFullYear(),
hr = 12, mn = 0, sc = 0,
ggg, s, a, j1, jd;
hr = hr + (mn / 60) + (sc/3600);
ggg = 1;
if (yy <= 1585) {
ggg = 0;
}
jd = -1 * Math.floor(7 * (Math.floor((mm + 9) / 12) + yy) / 4);
s = 1;
if ((mm - 9) < 0) {
s =- 1;
}
a = Math.abs(mm - 9);
j1 = Math.floor(yy + s * Math.floor(a / 7));
j1 = -1 * Math.floor((Math.floor(j1 / 100) + 1) * 3 / 4);
jd = jd + Math.floor(275 * mm / 9) + dd + (ggg * j1);
jd = jd + 1721027 + 2 * ggg + 367 * yy - 0.5;
jd = jd + (hr / 24);
return jd;
}
end
def julian?
`#{@date} < new Date(1582, 10 - 1, 15, 12)`
end
def new_start(start)
new_date = clone
`new_date.start = start`
new_date
end
def next
self + 1
end
def -(date)
%x{
if (date.date) {
return Math.round((#{@date} - #{date}.date) / (1000 * 60 * 60 * 24));
}
}
prev_day(date)
end
def +(date)
next_day(date)
end
def prev_day(n = 1)
%x{
if (n.$$is_number) {
var result = #{clone};
result.date.setDate(#{@date}.getDate() - n);
return result;
}
else {
#{raise ::TypeError};
}
}
end
def next_day(n = 1)
`if (!n.$$is_number) #{raise ::TypeError}`
prev_day(-n)
end
def prev_month(n = 1)
%x{
if (!n.$$is_number) #{raise ::TypeError}
var result = #{clone}, date = result.date, cur = date.getDate();
date.setDate(1);
date.setMonth(date.getMonth() - n);
date.setDate(Math.min(cur, #{Date._days_in_month(`date.getFullYear()`, `date.getMonth()`)}));
return result;
}
end
def next_month(n = 1)
`if (!n.$$is_number) #{raise ::TypeError}`
prev_month(-n)
end
def prev_year(years = 1)
`if (!years.$$is_number) #{raise ::TypeError}`
self.class.new(year - years, month, day)
end
def next_year(years = 1)
`if (!years.$$is_number) #{raise ::TypeError}`
prev_year(-years)
end
def strftime(format = '')
%x{
if (format == '') {
return #{to_s};
}
return #{@date.strftime(format)}
}
end
def to_s
%x{
var d = #{@date}, year = d.getFullYear(), month = d.getMonth() + 1, day = d.getDate();
if (month < 10) { month = '0' + month; }
if (day < 10) { day = '0' + day; }
return year + '-' + month + '-' + day;
}
end
def to_time
Time.new(year, month, day)
end
def to_date
self
end
def to_datetime
DateTime.new(year, month, day)
end
def to_n
@date
end
def step(limit, step = 1, &block)
steps_count = (limit - self).to_i
steps = if steps_count * step < 0
[]
elsif steps_count < 0
(0..-steps_count).step(step.abs).map(&:-@).reverse
else
(0..steps_count).step(step.abs)
end
result = steps.map { |i| self + i }
if block_given?
result.each { |i| yield(i) }
self
else
result
end
end
def upto(max, &block)
step(max, 1, &block)
end
def downto(min, &block)
step(min, -1, &block)
end
def cwday
`#{@date}.getDay() || 7`
end
def cweek
%x{
var d = new Date(#{@date});
d.setHours(0,0,0);
d.setDate(d.getDate()+4-(d.getDay()||7));
return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
}
end
def self._days_in_month(year, month)
%x{
var leap = ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
return [31, (leap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}
end
alias eql? ==
alias succ next
end
require 'date/date_time'
require 'date/formatters'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/buffer.rb | stdlib/buffer.rb | # backtick_javascript: true
require 'native'
require 'buffer/array'
require 'buffer/view'
class Buffer
include Native::Wrapper
def self.supported?
!$$[:ArrayBuffer].nil?
end
def self.name_for(bits, type)
part = case type
when :unsigned then 'Uint'
when :signed then 'Int'
when :float then 'Float'
end
"#{part}#{bits}"
end
def initialize(size, bits = 8)
if native?(size)
super(size)
else
super(`new ArrayBuffer(size * (bits / 8))`)
end
end
def length
`#{@native}.byteLength`
end
def to_a(bits = 8, type = :unsigned)
Array.new(self, bits, type)
end
def view(offset = nil, length = nil)
View.new(self, offset, length)
end
def to_s
to_a.to_a.pack('c*')
end
alias size length
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/pp.rb | stdlib/pp.rb | # frozen_string_literal: true
# backtick_javascript: true
# Opal: load stdlib/thread.rb
require 'thread'
require 'stringio'
require 'prettyprint'
##
# A pretty-printer for Ruby objects.
#
##
# == What PP Does
#
# Standard output by #p returns this:
# #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
#
# Pretty-printed output returns this:
# #<PP:0x81fedf0
# @buffer=[],
# @buffer_width=0,
# @genspace=#<Proc:0x81feda0>,
# @group_queue=
# #<PrettyPrint::GroupQueue:0x81fed3c
# @queue=
# [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
# []]>,
# @group_stack=
# [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
# @indent=0,
# @maxwidth=79,
# @newline="\n",
# @output=#<IO:0x8114ee4>,
# @output_width=2>
#
##
# == Usage
#
# pp(obj) #=> obj
# pp obj #=> obj
# pp(obj1, obj2, ...) #=> [obj1, obj2, ...]
# pp() #=> nil
#
# Output <tt>obj(s)</tt> to <tt>$></tt> in pretty printed format.
#
# It returns <tt>obj(s)</tt>.
#
##
# == Output Customization
#
# To define a customized pretty printing function for your classes,
# redefine method <code>#pretty_print(pp)</code> in the class.
#
# <code>#pretty_print</code> takes the +pp+ argument, which is an instance of the PP class.
# The method uses #text, #breakable, #nest, #group and #pp to print the
# object.
#
##
# == Pretty-Print JSON
#
# To pretty-print JSON refer to JSON#pretty_generate.
#
##
# == Author
# Tanaka Akira <akr@fsij.org>
class PP < PrettyPrint
# Outputs +obj+ to +out+ in pretty printed format of
# +width+ columns in width.
#
# If +out+ is omitted, <code>$></code> is assumed.
# If +width+ is omitted, 79 is assumed.
#
# PP.pp returns +out+.
def PP.pp(obj, out=$stdout, width=79) # Opal: replace $> with $stdout
q = PP.new(out, width)
q.guard_inspect_key {q.pp obj}
q.flush
#$pp = q
out << "\n"
end
# Outputs +obj+ to +out+ like PP.pp but with no indent and
# newline.
#
# PP.singleline_pp returns +out+.
def PP.singleline_pp(obj, out=$stdout) # Opal: replace $> with $stdout
q = SingleLine.new(out)
q.guard_inspect_key {q.pp obj}
q.flush
out
end
# :stopdoc:
def PP.mcall(obj, mod, meth, *args, &block)
mod.instance_method(meth).bind_call(obj, *args, &block)
end
# :startdoc:
@sharing_detection = false
class << self
# Returns the sharing detection flag as a boolean value.
# It is false by default.
attr_accessor :sharing_detection
end
module PPMethods
# Yields to a block
# and preserves the previous set of objects being printed.
def guard_inspect_key
if Thread.current[:__recursive_key__] == nil
Thread.current[:__recursive_key__] = {}.compare_by_identity
end
if Thread.current[:__recursive_key__][:inspect] == nil
Thread.current[:__recursive_key__][:inspect] = {}.compare_by_identity
end
save = Thread.current[:__recursive_key__][:inspect]
begin
Thread.current[:__recursive_key__][:inspect] = {}.compare_by_identity
yield
ensure
Thread.current[:__recursive_key__][:inspect] = save
end
end
# Check whether the object_id +id+ is in the current buffer of objects
# to be pretty printed. Used to break cycles in chains of objects to be
# pretty printed.
def check_inspect_key(id)
Thread.current[:__recursive_key__] &&
Thread.current[:__recursive_key__][:inspect] &&
Thread.current[:__recursive_key__][:inspect].include?(id)
end
# Adds the object_id +id+ to the set of objects being pretty printed, so
# as to not repeat objects.
def push_inspect_key(id)
Thread.current[:__recursive_key__][:inspect][id] = true
end
# Removes an object from the set of objects being pretty printed.
def pop_inspect_key(id)
Thread.current[:__recursive_key__][:inspect].delete id
end
# Adds +obj+ to the pretty printing buffer
# using Object#pretty_print or Object#pretty_print_cycle.
#
# Object#pretty_print_cycle is used when +obj+ is already
# printed, a.k.a the object reference chain has a cycle.
def pp(obj = undefined)
# Opal: consider JS-native variables:
%x{
if (obj === null) {
#{text "null"}
#{return}
}
else if (obj === undefined) {
#{text "undefined"}
#{return}
}
else if (obj.$$class === undefined) {
#{text `Object.prototype.toString.apply(obj)`}
#{return}
}
}
# If obj is a Delegator then use the object being delegated to for cycle
# detection
obj = obj.__getobj__ if defined?(::Delegator) and obj.is_a?(::Delegator)
if check_inspect_key(obj)
group {obj.pretty_print_cycle self}
return
end
begin
push_inspect_key(obj)
group {obj.pretty_print self}
ensure
pop_inspect_key(obj) unless PP.sharing_detection
end
end
# A convenience method which is same as follows:
#
# group(1, '#<' + obj.class.name, '>') { ... }
def object_group(obj, &block) # :yield:
group(1, '#<' + obj.class.name, '>', &block)
end
# A convenience method, like object_group, but also reformats the Object's
# object_id.
def object_address_group(obj, &block)
str = Kernel.instance_method(:to_s).bind_call(obj)
str = str.chomp('>')
group(1, str, '>', &block)
end
# A convenience method which is same as follows:
#
# text ','
# breakable
def comma_breakable
text ','
breakable
end
# Adds a separated list.
# The list is separated by comma with breakable space, by default.
#
# #seplist iterates the +list+ using +iter_method+.
# It yields each object to the block given for #seplist.
# The procedure +separator_proc+ is called between each yields.
#
# If the iteration is zero times, +separator_proc+ is not called at all.
#
# If +separator_proc+ is nil or not given,
# +lambda { comma_breakable }+ is used.
# If +iter_method+ is not given, :each is used.
#
# For example, following 3 code fragments has similar effect.
#
# q.seplist([1,2,3]) {|v| xxx v }
#
# q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
#
# xxx 1
# q.comma_breakable
# xxx 2
# q.comma_breakable
# xxx 3
def seplist(list, sep=nil, iter_method=:each) # :yield: element
sep ||= lambda { comma_breakable }
first = true
list.__send__(iter_method) {|*v|
if first
first = false
else
sep.call
end
yield(*v)
}
end
# A present standard failsafe for pretty printing any given Object
def pp_object(obj)
object_address_group(obj) {
seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
breakable
v = v.to_s if Symbol === v
text v
text '='
group(1) {
breakable ''
pp(obj.instance_eval(v))
}
}
}
end
# A pretty print for a Hash
def pp_hash(obj)
group(1, '{', '}') {
seplist(obj, nil, :each_pair) {|k, v|
group {
pp k
text '=>'
group(1) {
breakable ''
pp v
}
}
}
}
end
end
include PPMethods
class SingleLine < PrettyPrint::SingleLine # :nodoc:
include PPMethods
end
module ObjectMixin # :nodoc:
# 1. specific pretty_print
# 2. specific inspect
# 3. generic pretty_print
# A default pretty printing method for general objects.
# It calls #pretty_print_instance_variables to list instance variables.
#
# If +self+ has a customized (redefined) #inspect method,
# the result of self.inspect is used but it obviously has no
# line break hints.
#
# This module provides predefined #pretty_print methods for some of
# the most commonly used built-in classes for convenience.
def pretty_print(q)
umethod_method = Object.instance_method(:method)
begin
inspect_method = umethod_method.bind_call(self, :inspect)
rescue NameError
end
if inspect_method && inspect_method.owner != Kernel
q.text self.inspect
elsif !inspect_method && self.respond_to?(:inspect)
q.text self.inspect
else
q.pp_object(self)
end
end
# A default pretty printing method for general objects that are
# detected as part of a cycle.
def pretty_print_cycle(q)
q.object_address_group(self) {
q.breakable
q.text '...'
}
end
# Returns a sorted array of instance variable names.
#
# This method should return an array of names of instance variables as symbols or strings as:
# +[:@a, :@b]+.
def pretty_print_instance_variables
instance_variables.sort
end
# Is #inspect implementation using #pretty_print.
# If you implement #pretty_print, it can be used as follows.
#
# alias inspect pretty_print_inspect
#
# However, doing this requires that every class that #inspect is called on
# implement #pretty_print, or a RuntimeError will be raised.
def pretty_print_inspect
if Object.instance_method(:method).bind_call(self, :pretty_print).owner == PP::ObjectMixin
raise "pretty_print is not overridden for #{self.class}"
end
PP.singleline_pp(self, ''.dup)
end
end
end
class Array # :nodoc:
def pretty_print(q) # :nodoc:
q.group(1, '[', ']') {
q.seplist(self) {|v|
q.pp v
}
}
end
def pretty_print_cycle(q) # :nodoc:
q.text(empty? ? '[]' : '[...]')
end
end
class Hash # :nodoc:
def pretty_print(q) # :nodoc:
q.pp_hash self
end
def pretty_print_cycle(q) # :nodoc:
q.text(empty? ? '{}' : '{...}')
end
end
class << ENV # :nodoc:
def pretty_print(q) # :nodoc:
h = {}
ENV.keys.sort.each {|k|
h[k] = ENV[k]
}
q.pp_hash h
end
end
class Struct # :nodoc:
def pretty_print(q) # :nodoc:
q.group(1, sprintf("#<struct %s", PP.mcall(self, Kernel, :class).name), '>') {
q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
q.breakable
q.text member.to_s
q.text '='
q.group(1) {
q.breakable ''
q.pp self[member]
}
}
}
end
def pretty_print_cycle(q) # :nodoc:
q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
end
end
class Range # :nodoc:
def pretty_print(q) # :nodoc:
q.pp self.begin
q.breakable ''
q.text(self.exclude_end? ? '...' : '..')
q.breakable ''
q.pp self.end if self.end
end
end
class String # :nodoc:
def pretty_print(q) # :nodoc:
lines = self.lines
if lines.size > 1
q.group(0, '', '') do
q.seplist(lines, lambda { q.text ' +'; q.breakable }) do |v|
q.pp v
end
end
else
q.text inspect
end
end
end
# Opal: does not have File::Stat
#class File < IO # :nodoc:
# class Stat # :nodoc:
# def pretty_print(q) # :nodoc:
# require 'etc.so'
# q.object_group(self) {
# q.breakable
# q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
# q.text "ino="; q.pp self.ino; q.comma_breakable
# q.group {
# m = self.mode
# q.text sprintf("mode=0%o", m)
# q.breakable
# q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
# self.ftype,
# (m & 0400 == 0 ? ?- : ?r),
# (m & 0200 == 0 ? ?- : ?w),
# (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
# (m & 04000 == 0 ? ?x : ?s)),
# (m & 0040 == 0 ? ?- : ?r),
# (m & 0020 == 0 ? ?- : ?w),
# (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
# (m & 02000 == 0 ? ?x : ?s)),
# (m & 0004 == 0 ? ?- : ?r),
# (m & 0002 == 0 ? ?- : ?w),
# (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
# (m & 01000 == 0 ? ?x : ?t)))
# }
# q.comma_breakable
# q.text "nlink="; q.pp self.nlink; q.comma_breakable
# q.group {
# q.text "uid="; q.pp self.uid
# begin
# pw = Etc.getpwuid(self.uid)
# rescue ArgumentError
# end
# if pw
# q.breakable; q.text "(#{pw.name})"
# end
# }
# q.comma_breakable
# q.group {
# q.text "gid="; q.pp self.gid
# begin
# gr = Etc.getgrgid(self.gid)
# rescue ArgumentError
# end
# if gr
# q.breakable; q.text "(#{gr.name})"
# end
# }
# q.comma_breakable
# q.group {
# q.text sprintf("rdev=0x%x", self.rdev)
# if self.rdev_major && self.rdev_minor
# q.breakable
# q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
# end
# }
# q.comma_breakable
# q.text "size="; q.pp self.size; q.comma_breakable
# q.text "blksize="; q.pp self.blksize; q.comma_breakable
# q.text "blocks="; q.pp self.blocks; q.comma_breakable
# q.group {
# t = self.atime
# q.text "atime="; q.pp t
# q.breakable; q.text "(#{t.tv_sec})"
# }
# q.comma_breakable
# q.group {
# t = self.mtime
# q.text "mtime="; q.pp t
# q.breakable; q.text "(#{t.tv_sec})"
# }
# q.comma_breakable
# q.group {
# t = self.ctime
# q.text "ctime="; q.pp t
# q.breakable; q.text "(#{t.tv_sec})"
# }
# }
# end
# end
#end
class MatchData # :nodoc:
def pretty_print(q) # :nodoc:
nc = []
self.regexp.named_captures.each {|name, indexes|
indexes.each {|i| nc[i] = name }
}
q.object_group(self) {
q.breakable
q.seplist(0...self.size, lambda { q.breakable }) {|i|
if i == 0
q.pp self[i]
else
if nc[i]
q.text nc[i]
else
q.pp i
end
q.text ':'
q.pp self[i]
end
}
}
end
end
# Opal: does not have RubyVM
#class RubyVM::AbstractSyntaxTree::Node
# def pretty_print_children(q, names = [])
# children.zip(names) do |c, n|
# if n
# q.breakable
# q.text "#{n}:"
# end
# q.group(2) do
# q.breakable
# q.pp c
# end
# end
# end
#
# def pretty_print(q)
# q.group(1, "(#{type}@#{first_lineno}:#{first_column}-#{last_lineno}:#{last_column}", ")") {
# case type
# when :SCOPE
# pretty_print_children(q, %w"tbl args body")
# when :ARGS
# pretty_print_children(q, %w[pre_num pre_init opt first_post post_num post_init rest kw kwrest block])
# when :DEFN
# pretty_print_children(q, %w[mid body])
# when :ARYPTN
# pretty_print_children(q, %w[const pre rest post])
# when :HSHPTN
# pretty_print_children(q, %w[const kw kwrest])
# else
# pretty_print_children(q)
# end
# }
# end
#end
class Object < BasicObject # :nodoc:
include PP::ObjectMixin
end
[Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
c.class_eval {
def pretty_print_cycle(q)
q.text inspect
end
}
}
[Numeric, FalseClass, TrueClass, Module].each {|c|
c.class_eval {
def pretty_print(q)
q.text inspect
end
}
}
module Kernel
# Returns a pretty printed object as a string.
#
# In order to use this method you must first require the PP module:
#
# require 'pp'
#
# See the PP module for more information.
def pretty_inspect
PP.pp(self, StringIO.new).string
end
# prints arguments in pretty form.
#
# pp returns argument(s).
def pp(*objs)
objs.each {|obj|
PP.pp(obj)
}
objs.size <= 1 ? objs.first : objs
end
module_function :pp
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/gjs.rb | stdlib/gjs.rb | require 'gjs/io'
require 'gjs/kernel'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/e2mmap.rb | stdlib/e2mmap.rb | # frozen_string_literal: true
#
#--
# e2mmap.rb - for Ruby 1.1
# $Release Version: 2.0$
# $Revision: 1.10 $
# by Keiju ISHITSUKA
#
#++
#
# Helper module for easily defining exceptions with predefined messages.
#
# == Usage
#
# 1.
# class Foo
# extend Exception2MessageMapper
# def_e2message ExistingExceptionClass, "message..."
# def_exception :NewExceptionClass, "message..."[, superclass]
# ...
# end
#
# 2.
# module Error
# extend Exception2MessageMapper
# def_e2message ExistingExceptionClass, "message..."
# def_exception :NewExceptionClass, "message..."[, superclass]
# ...
# end
# class Foo
# include Error
# ...
# end
#
# foo = Foo.new
# foo.Fail ....
#
# 3.
# module Error
# extend Exception2MessageMapper
# def_e2message ExistingExceptionClass, "message..."
# def_exception :NewExceptionClass, "message..."[, superclass]
# ...
# end
# class Foo
# extend Exception2MessageMapper
# include Error
# ...
# end
#
# Foo.Fail NewExceptionClass, arg...
# Foo.Fail ExistingExceptionClass, arg...
#
#
module Exception2MessageMapper
E2MM = Exception2MessageMapper # :nodoc:
def E2MM.extend_object(cl)
super
cl.bind(self) unless cl < E2MM
end
def bind(cl)
self.module_eval do
def Raise(err = nil, *rest)
Exception2MessageMapper.Raise(self.class, err, *rest)
end
alias Fail Raise
class << self
undef included
end
def self.included(mod)
mod.extend Exception2MessageMapper
end
end
end
# Fail(err, *rest)
# err: exception
# rest: message arguments
#
def Raise(err = nil, *rest)
E2MM.Raise(self, err, *rest)
end
alias Fail Raise
alias fail Raise
# def_e2message(c, m)
# c: exception
# m: message_form
# define exception c with message m.
#
def def_e2message(c, m)
E2MM.def_e2message(self, c, m)
end
# def_exception(n, m, s)
# n: exception_name
# m: message_form
# s: superclass(default: StandardError)
# define exception named ``c'' with message m.
#
def def_exception(n, m, s = StandardError)
E2MM.def_exception(self, n, m, s)
end
#
# Private definitions.
#
# {[class, exp] => message, ...}
@MessageMap = {}
# E2MM.def_e2message(k, e, m)
# k: class to define exception under.
# e: exception
# m: message_form
# define exception c with message m.
#
def E2MM.def_e2message(k, c, m)
E2MM.instance_eval{@MessageMap[[k, c]] = m}
c
end
# E2MM.def_exception(k, n, m, s)
# k: class to define exception under.
# n: exception_name
# m: message_form
# s: superclass(default: StandardError)
# define exception named ``c'' with message m.
#
def E2MM.def_exception(k, n, m, s = StandardError)
e = Class.new(s)
E2MM.instance_eval{@MessageMap[[k, e]] = m}
k.module_eval {remove_const(n)} if k.const_defined?(n, false)
k.const_set(n, e)
end
# Fail(klass, err, *rest)
# klass: class to define exception under.
# err: exception
# rest: message arguments
#
def E2MM.Raise(klass = E2MM, err = nil, *rest)
if form = e2mm_message(klass, err)
b = $@.nil? ? caller(1) : $@
b.shift if b[0] =~ /^#{Regexp.quote(__FILE__)}:/
raise err, sprintf(form, *rest), b
else
E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect
end
end
class << E2MM
alias Fail Raise
end
def E2MM.e2mm_message(klass, exp)
klass.ancestors.each do |c|
if mes = @MessageMap[[c,exp]]
# PATCH: who needs this hack?
# m = klass.instance_eval('"' + mes + '"')
# return m
return mes
end
end
nil
end
class << self
alias message e2mm_message
end
E2MM.def_exception(E2MM,
:ErrNotRegisteredException,
"not registered exception(%s)")
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/cgi/util.rb | stdlib/cgi/util.rb | # backtick_javascript: true
# This file contains parts of https://github.com/ruby/ruby/blob/master/lib/cgi/util.rb
# licensed under a Ruby license.
class CGI
module Util
# URL-encode a string into application/x-www-form-urlencoded.
# Space characters (+" "+) are encoded with plus signs (+"+"+)
# url_encoded_string = CGI.escape("'Stop!' said Fred")
# # => "%27Stop%21%27+said+Fred"
def escape(c)
`encodeURI(c)`
end
# URL-decode an application/x-www-form-urlencoded string with encoding(optional).
# string = CGI.unescape("%27Stop%21%27+said+Fred")
# # => "'Stop!' said Fred"
def unescape(c)
`decodeURI(c)`
end
# URL-encode a string following RFC 3986
# Space characters (+" "+) are encoded with (+"%20"+)
# url_encoded_string = CGI.escapeURIComponent("'Stop!' said Fred")
# # => "%27Stop%21%27%20said%20Fred"
def escapeURIComponent(c)
`encodeURIComponent(c)`
end
# URL-decode a string following RFC 3986 with encoding(optional).
# string = CGI.unescapeURIComponent("%27Stop%21%27+said%20Fred")
# # => "'Stop!'+said Fred"
def unescapeURIComponent(c)
`decodeURIComponent(c)`
end
# The set of special characters and their escaped values
TABLE_FOR_ESCAPE_HTML__ = {
"'" => ''',
'&' => '&',
'"' => '"',
'<' => '<',
'>' => '>',
}
# Escape special characters in HTML, namely '&\"<>
# CGI.escapeHTML('Usage: foo "bar" <baz>')
# # => "Usage: foo "bar" <baz>"
def escapeHTML(string)
string.gsub(/['&"<>]/, TABLE_FOR_ESCAPE_HTML__)
end
# Unescape a string that has been HTML-escaped
# CGI.unescapeHTML("Usage: foo "bar" <baz>")
# # => "Usage: foo \"bar\" <baz>"
def unescapeHTML(string)
string.gsub(/&(apos|amp|quot|gt|lt|\#[0-9]+|\#[xX][0-9A-Fa-f]+);/) do
match = ::Regexp.last_match(1)
case match
when 'apos' then "'"
when 'amp' then '&'
when 'quot' then '"'
when 'gt' then '>'
when 'lt' then '<'
when /\A#0*(\d+)\z/
n = ::Regexp.last_match(1).to_i
n.chr('utf-8')
when /\A#x([0-9a-f]+)\z/i
n = ::Regexp.last_match(1).hex
n.chr('utf-8')
else
"&#{match};"
end
end
end
# Synonym for CGI.escapeHTML(str)
alias escape_html escapeHTML
# Synonym for CGI.unescapeHTML(str)
alias unescape_html unescapeHTML
alias h escapeHTML
end
include Util
extend Util
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal/platform.rb | stdlib/opal/platform.rb | require 'opal-platform'
case OPAL_PLATFORM
when 'gjs' then require 'gjs'
when 'quickjs' then require 'quickjs'
when 'deno' then require 'deno/base'
when 'nodejs' then require 'nodejs/base'
when 'headless-chrome' then require 'headless_browser/base'
when 'headless-firefox' then require 'headless_browser/base'
when 'safari' then require 'headless_browser/base'
when 'opal-miniracer' then require 'opal/miniracer'
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal/raw.rb | stdlib/opal/raw.rb | # backtick_javascript: true
# The Opal::Raw module provides syntax sugar for calling native javascript
# operators (e.g. typeof, instanceof, new, delete) and global functions
# (e.g. parseFloat, parseInt).
module ::Opal
module Raw
# Use delete to remove a property from an object.
def delete(object, property)
`delete #{object}[#{property}]`
end
# The global object
def global
`Opal.global`
end
# Use in to check for a property in an object.
def in(property, object)
`#{property} in #{object}`
end
# Use instanceof to return whether value is an instance of the function.
def instanceof(value, func)
`#{value} instanceof #{func}`
end
# Use new to create a new instance of the prototype of the function.
if `typeof Function.prototype.bind == 'function'`
def new(func, *args, &block)
args.insert(0, `this`)
args << block if block
`new (#{func}.bind.apply(#{func}, #{args}))()`
end
else
def new(func, *args, &block)
args << block if block
f = `function(){return func.apply(this, args)}`
f.JS[:prototype] = func.JS[:prototype]
`new f()`
end
end
# Use typeof to return the underlying javascript type of value.
# Note that for undefined values, this will not work exactly like
# the javascript typeof operator, as the argument is evaluated before
# the function call.
def typeof(value)
`typeof #{value}`
end
# Use void to return undefined.
def void(expr)
# Could use `undefined` here, but this is closer to the intent of the method
`void #{expr}`
end
# Call the global javascript function with the given arguments.
def call(func, *args, &block)
g = global
args << block if block
g.JS[func].JS.apply(g, args)
end
def [](name)
`Opal.global[#{name}]`
end
alias method_missing call
extend self # rubocop:disable Style/ModuleFunction
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal/miniracer.rb | stdlib/opal/miniracer.rb | # backtick_javascript: true
`/* global opalminiracer */`
# Compatibility utilities for the API we provide in
# lib/opal/cli_runners/mini_racer
ARGV = `opalminiracer.argv`
`Opal.exit = opalminiracer.exit`
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal/repl_js.rb | stdlib/opal/repl_js.rb | require 'opal/platform'
require 'opal-replutils'
require 'json'
REPLUtils.js_repl
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/io.rb | stdlib/nodejs/io.rb | # backtick_javascript: true
require 'nodejs/file'
%x{
function executeIOAction(action) {
try {
return action();
} catch (error) {
if (error.code === 'EACCES' ||
error.code === 'EISDIR' ||
error.code === 'EMFILE' ||
error.code === 'ENOENT' ||
error.code === 'EPERM') {
throw Opal.IOError.$new(error.message)
}
throw error;
}
}
}
`var __fs__ = require('fs')`
class IO
@__fs__ = `__fs__`
attr_reader :lineno
alias initialize_before_node_io initialize
def initialize(fd, flags = 'r')
@lineno = 0
initialize_before_node_io(fd, flags)
end
def self.write(path, data)
File.write(path, data)
end
def self.read(path)
File.read(path)
end
def self.binread(path)
`return executeIOAction(function(){return __fs__.readFileSync(#{path}).toString('binary')})`
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/open-uri.rb | stdlib/nodejs/open-uri.rb | # backtick_javascript: true
module OpenURI
@__xmlhttprequest__ = `require('unxhr')`
`var __XMLHttpRequest__ = #{@__xmlhttprequest__}.XMLHttpRequest`
def self.request(uri)
%x{
var xhr = new __XMLHttpRequest__();
xhr.open('GET', uri, false);
xhr.responseType = 'arraybuffer';
xhr.send();
return xhr;
}
end
def self.data(req)
%x{
var arrayBuffer = req.response;
var byteArray = new Uint8Array(arrayBuffer);
var result = []
for (var i = 0; i < byteArray.byteLength; i++) {
result.push(byteArray[i]);
}
return result;
}
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/stacktrace.rb | stdlib/nodejs/stacktrace.rb | warn <<-WARN, uplevel: 1
Requiring nodejs/stacktrace has been deprecated, if you use the default
Node.js runner stack-traces will have source-map support out of the box.
WARN
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/file.rb | stdlib/nodejs/file.rb | # backtick_javascript: true
require 'corelib/file'
%x{
var warnings = {}, errno_codes = #{Errno.constants};
function handle_unsupported_feature(message) {
switch (Opal.config.unsupported_features_severity) {
case 'error':
#{Kernel.raise NotImplementedError, `message`}
break;
case 'warning':
warn(message)
break;
default: // ignore
// noop
}
}
function warn(string) {
if (warnings[string]) {
return;
}
warnings[string] = true;
#{warn(`string`)};
}
function is_utf8(bytes) {
var i = 0;
while (i < bytes.length) {
if ((// ASCII
bytes[i] === 0x09 ||
bytes[i] === 0x0A ||
bytes[i] === 0x0D ||
(0x20 <= bytes[i] && bytes[i] <= 0x7E)
)
) {
i += 1;
continue;
}
if ((// non-overlong 2-byte
(0xC2 <= bytes[i] && bytes[i] <= 0xDF) &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF)
)
) {
i += 2;
continue;
}
if ((// excluding overlongs
bytes[i] === 0xE0 &&
(0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
) ||
(// straight 3-byte
((0xE1 <= bytes[i] && bytes[i] <= 0xEC) ||
bytes[i] === 0xEE ||
bytes[i] === 0xEF) &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
) ||
(// excluding surrogates
bytes[i] === 0xED &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x9F) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
)
) {
i += 3;
continue;
}
if ((// planes 1-3
bytes[i] === 0xF0 &&
(0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
) ||
(// planes 4-15
(0xF1 <= bytes[i] && bytes[i] <= 0xF3) &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
) ||
(// plane 16
bytes[i] === 0xF4 &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
)
) {
i += 4;
continue;
}
return false;
}
return true;
}
function executeIOAction(action) {
try {
return action();
} catch (error) {
if (errno_codes.indexOf(error.code) >= 0) {
var error_class = #{Errno.const_get(`error.code`)}
#{Kernel.raise `error_class`.new(`error.message`)}
}
#{Kernel.raise `error`}
}
}
}
class File < IO
@__fs__ = `require('fs')`
@__path__ = `require('path')`
`var __fs__ = #{@__fs__}`
`var __path__ = #{@__path__}`
# Since Node.js 11+ TextEncoder and TextDecoder are now available on the global object.
%x{
var __TextEncoder__, __TextDecoder__;
if (typeof TextEncoder !== 'undefined') {
__TextEncoder__ = TextEncoder;
__TextDecoder__ = TextDecoder;
} else {
var __util__ = require('util');
__TextEncoder__ = __util__.TextEncoder;
__TextDecoder__ = __util__.TextDecoder;
}
var __utf8TextDecoder__ = new __TextDecoder__('utf8');
var __textEncoder__ = new __TextEncoder__();
}
if `__path__.sep !== #{Separator}`
ALT_SEPARATOR = `__path__.sep`
end
def self.read(path)
`return executeIOAction(function(){return __fs__.readFileSync(#{path}).toString()})`
end
def self.write(path, data)
`executeIOAction(function(){return __fs__.writeFileSync(#{path}, #{data})})`
data.size
end
def self.symlink(path, new_path)
`executeIOAction(function(){return __fs__.symlinkSync(#{path}, #{new_path})})`
0
end
def self.delete(path)
`executeIOAction(function(){return __fs__.unlinkSync(#{path})})`
end
class << self
alias unlink delete
end
def self.exist?(path)
path = path.path if path.respond_to? :path
`return executeIOAction(function(){return __fs__.existsSync(#{path})})`
end
def self.realpath(pathname, dir_string = nil, cache = nil, &block)
pathname = join(dir_string, pathname) if dir_string
if block_given?
`
__fs__.realpath(#{pathname}, #{cache}, function(error, realpath){
if (error) Opal.IOError.$new(error.message)
else #{block.call(`realpath`)}
})
`
else
`return executeIOAction(function(){return __fs__.realpathSync(#{pathname}, #{cache})})`
end
end
def self.join(*paths)
# by itself, `path.posix.join` normalizes leading // to /.
# restore the leading / on UNC paths (i.e., paths starting with //).
paths = paths.map(&:to_s)
prefix = paths.first&.start_with?('//') ? '/' : ''
`#{prefix} + __path__.posix.join.apply(__path__, #{paths})`
end
def self.directory?(path)
return false unless exist? path
result = `executeIOAction(function(){return !!__fs__.lstatSync(path).isDirectory()})`
unless result
realpath = realpath(path)
if realpath != path
result = `executeIOAction(function(){return !!__fs__.lstatSync(realpath).isDirectory()})`
end
end
result
end
def self.file?(path)
return false unless exist? path
result = `executeIOAction(function(){return !!__fs__.lstatSync(path).isFile()})`
unless result
realpath = realpath(path)
if realpath != path
result = `executeIOAction(function(){return !!__fs__.lstatSync(realpath).isFile()})`
end
end
result
end
def self.readable?(path)
return false unless exist? path
%x{
try {
__fs__.accessSync(path, __fs__.R_OK);
return true;
} catch {
return false;
}
}
end
def self.size(path)
`return executeIOAction(function(){return __fs__.lstatSync(path).size})`
end
def self.open(path, mode = 'r')
file = new(path, mode)
if block_given?
begin
yield(file)
ensure
file.close
end
else
file
end
end
def self.stat(path)
path = path.path if path.respond_to? :path
File::Stat.new(path)
end
def self.mtime(path)
`return executeIOAction(function(){return __fs__.statSync(#{path}).mtime})`
end
def self.symlink?(path)
`return executeIOAction(function(){return __fs__.lstatSync(#{path}).isSymbolicLink()})`
end
def self.absolute_path(path, basedir = nil)
path = path.respond_to?(:to_path) ? path.to_path : path
basedir ||= Dir.pwd
`return __path__.normalize(__path__.resolve(#{basedir.to_str}, #{path.to_str})).split(__path__.sep).join(__path__.posix.sep)`
end
def self.absolute_path?(path)
`__path__.isAbsolute(path)`
end
# Instance Methods
def initialize(path, flags = 'r')
@binary_flag = flags.include?('b')
# Node does not recognize this flag
flags = flags.delete('b')
# encoding flag is unsupported
encoding_option_rx = /:(.*)/
if encoding_option_rx.match?(flags)
`handle_unsupported_feature("Encoding option (:encoding) is unsupported by Node.js openSync method and will be removed.")`
flags = flags.sub(encoding_option_rx, '')
end
@path = path
fd = `executeIOAction(function(){return __fs__.openSync(path, flags.toString())})`
super(fd, flags)
end
attr_reader :path
def sysread(bytes)
if @eof
raise EOFError, 'end of file reached'
else
if @binary_flag
%x{
var buf = executeIOAction(function(){return __fs__.readFileSync(#{@path})})
var content
if (is_utf8(buf)) {
content = buf.toString('utf8')
} else {
// coerce to utf8
content = __utf8TextDecoder__.decode(__textEncoder__.encode(buf.toString('binary')))
}
}
res = `content`
else
res = `executeIOAction(function(){return __fs__.readFileSync(#{@path}).toString('utf8')})`
end
@eof = true
@lineno = res.size
res
end
end
def write(string)
`executeIOAction(function(){return __fs__.writeSync(#{@fd}, #{string})})`
end
def flush
`executeIOAction(function(){return __fs__.fsyncSync(#{@fd})})`
end
def close
`executeIOAction(function(){return __fs__.closeSync(#{@fd})})`
super
end
def mtime
`return executeIOAction(function(){return __fs__.statSync(#{@path}).mtime})`
end
end
class File::Stat
@__fs__ = `require('fs')`
`var __fs__ = #{@__fs__}`
def initialize(path)
@path = path
end
def file?
`return executeIOAction(function(){return __fs__.statSync(#{@path}).isFile()})`
end
def directory?
`return executeIOAction(function(){return __fs__.statSync(#{@path}).isDirectory()})`
end
def mtime
`return executeIOAction(function(){return __fs__.statSync(#{@path}).mtime})`
end
def readable?
`return executeIOAction(function(){return __fs__.accessSync(#{@path}, __fs__.constants.R_OK)})`
end
def writable?
`return executeIOAction(function(){return __fs__.accessSync(#{@path}, __fs__.constants.W_OK)})`
end
def executable?
`return executeIOAction(function(){return __fs__.accessSync(#{@path}, __fs__.constants.X_OK)})`
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/fileutils.rb | stdlib/nodejs/fileutils.rb | # backtick_javascript: true
module FileUtils
extend self
`var __fs__ = #{File}.__fs__`
def chmod(mode, file_list)
raise NotImplementedError, 'symbolic mode is not supported, use numeric mode' if String === mode
Array(file_list).each do |file|
`__fs__.chmodSync(mode, file)`
end
end
def cp(source, target)
target = File.join(target, File.basename(source)) if File.directory? target
`__fs__.writeFileSync(target, __fs__.readFileSync(source))`
end
def rm(path)
`__fs__.unlinkSync(path)`
end
def mkdir_p(path)
return true if File.directory? path
`__fs__.mkdirSync(#{path})`
end
def mv(source, target)
target = File.join(target, File.basename(source)) if File.directory? target
`__fs__.renameSync(source, target)`
end
alias mkpath mkdir_p
alias makedirs mkdir_p
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/yaml.rb | stdlib/nodejs/yaml.rb | # backtick_javascript: true
require 'native'
require 'nodejs/js-yaml-3-6-1'
module YAML
@__yaml__ = `globalThis.jsyaml`
`var __yaml__ = #{@__yaml__}`
def self.load_path(path)
load(`#{File}.__fs__.readFileSync(#{path}, 'utf8')`)
end
def self.load(data)
loaded = `__yaml__.safeLoad(data)`
loaded = Hash.new(loaded) if native?(loaded)
loaded
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/env.rb | stdlib/nodejs/env.rb | # backtick_javascript: true
ENV = Object.new
class << ENV
def [](name)
`process.env[#{name}] || nil`
end
def []=(name, value)
`process.env[#{name.to_s}] = #{value.to_s}`
end
def key?(name)
`process.env.hasOwnProperty(#{name})`
end
def empty?
`Object.keys(process.env).length === 0`
end
def keys
`Object.keys(process.env)`
end
def delete(name)
%x{
var value = process.env[#{name}] || nil;
delete process.env[#{name}];
return value;
}
end
def fetch(key, default_value = undefined, &block)
return self[key] if key?(key)
return yield key if block_given?
return default_value unless `typeof(#{default_value}) === 'undefined'`
raise KeyError, 'key not found'
end
def to_s
'ENV'
end
def to_h
keys.to_h { |k| [k, self[k]] }
end
def merge(keys)
to_h.merge(keys)
end
alias has_key? key?
alias include? key?
alias inspect to_s
alias member? key?
alias to_hash to_h
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/kernel.rb | stdlib/nodejs/kernel.rb | # backtick_javascript: true
require 'buffer'
require 'corelib/process/status'
module Kernel
@__child_process__ = `require('node:child_process')`
@__cluster__ = `require('node:cluster')`
@__process__ = `require('node:process')`
`var __child_process__ = #{@__child_process__}`
`var __cluster__ = #{@__cluster__}`
`var __process__ = #{@__process__}`
def system(*argv, exception: false)
env = {}
env = argv.shift if argv.first.is_a? Hash
env = ENV.merge(env).to_n
cmdname = argv.shift
out = if argv.empty?
`__child_process__.spawnSync(#{cmdname}, { shell: true, stdio: 'inherit', env: #{env} })`
elsif Array === cmdname
`__child_process__.spawnSync(#{cmdname[0]}, #{argv}, { argv0: #{cmdname[1]}, stdio: 'inherit', env: #{env} })`
else
`__child_process__.spawnSync(#{cmdname}, #{argv}, { stdio: 'inherit', env: #{env} })`
end
status = out.JS[:status]
status = 127 if `status === null`
pid = out.JS[:pid]
$? = Process::Status.new(status, pid)
raise "Command failed with exit #{status}: #{cmdname}" if exception && status != 0
status == 0
end
def `(cmdline)
Buffer.new(`__child_process__.execSync(#{cmdline})`).to_s.encode('UTF-8')
end
def fork
`var worker`
if block_given?
%x{
if (__cluster__.isPrimary) {
worker = __cluster__.fork();
return worker.process.pid;
} else if (__cluster__.isWorker) {
#{yield}
}
}
else
%x{
if (__cluster__.isPrimary) {
worker = __cluster__.fork();
return worker.process.pid;
}
}
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/argf.rb | stdlib/nodejs/argf.rb | ARGF = Object.new
class << ARGF
include Enumerable
def inspect
'ARGF'
end
def argv
ARGV
end
def file
fn = filename
if fn == '-'
$stdin
else
@file ||= File.open(fn, 'r')
end
end
def filename
return @filename if @filename
if argv == ['-']
'-'
elsif argv == []
@last_filename || '-'
else
@file = nil
@filename = @last_filename = argv.shift
end
end
def close
file.close
@filename = nil
self
end
def closed?
file.closed?
end
def each(*args, &block)
return enum_for(:each) unless block_given?
while (l = gets(*args))
yield(l)
end
end
def gets(*args)
s = file.gets(*args)
if s.nil?
close
s = file.gets(*args)
end
@lineno += 1 if s
s
end
def read(len = nil)
buf = ''
loop do
r = file.read(len)
if r
buf += r
len -= r.length
end
file.close
break if len && len > 0 && @filename
end
end
def readlines(*args)
each(*args).to_a
end
attr_accessor :lineno
def rewind
@lineno = 1
f = file
begin
f.rewind
rescue
nil
end
0
end
def fileno
return 0 if !@filename && @last_filename
file.fileno
end
def eof?
file.eof?
end
alias each_line each
alias eof eof?
alias path filename
alias skip close
alias to_i fileno
alias to_io file
end
ARGF.lineno = 1
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/dir.rb | stdlib/nodejs/dir.rb | # backtick_javascript: true
class Dir
@__pm__ = `require('picomatch')`
@__fs__ = `require('fs')`
@__path__ = `require('path')`
@__os__ = `require('os')`
`var __pm__ = #{@__pm__}`
`var __fs__ = #{@__fs__}`
`var __path__ = #{@__path__}`
`var __os__ = #{@__os__}`
%x{
function pwd() {
return process.cwd().split(__path__.sep).join(__path__.posix.sep)
}
function readdirRecursive(dir, agg) {
try {
const files = __fs__.readdirSync(dir, {withFileTypes: true})
for (const file of files) {
agg.push(__path__.join(dir, file.name))
if (file.isDirectory()) {
readdirRecursive(__path__.join(dir, file.name), agg)
}
}
return agg
} catch (e) {
if (e.code === 'ENOENT' || e.code === 'EACCES' || e.code === 'ENOTDIR') {
// ignore
} else {
throw e
}
}
}
}
class << self
def [](pattern)
glob(pattern)
end
def pwd
`pwd()`
end
def home
`__os__.homedir()`
end
def chdir(path)
`process.chdir(#{path})`
end
def mkdir(path)
`__fs__.mkdirSync(#{path}, { recursive: true })`
end
def entries(dirname)
%x{
var result = [];
var entries = __fs__.readdirSync(#{dirname});
for (var i = 0, ii = entries.length; i < ii; i++) {
result.push(entries[i]);
}
return result;
}
end
def glob(pattern)
pattern = [pattern] unless pattern.respond_to? :each
pattern = pattern.map do |subpattern|
subpattern = subpattern.to_path if subpattern.respond_to? :to_path
::Opal.coerce_to!(subpattern, String, :to_str)
end
%x{
return #{pattern}.flatMap((subpattern) => {
const scanResult = __pm__.scan(subpattern, { tokens: true })
let base = scanResult.negated || scanResult.base === ''
? process.cwd().split(__path__.sep).join(__path__.posix.sep)
: scanResult.base
try {
const stat = __fs__.statSync(base)
if (scanResult.glob === '' && stat.isDirectory()) {
return [base]
}
if (stat.isFile()) {
base = __path__.dirname(base)
}
} catch (e) {
if (e.code === 'ENOENT' || e.code === 'EACCES' || e.code === 'ENOTDIR') {
return []
}
}
try {
const recursive = (scanResult.glob.includes('**') && scanResult.glob.includes('/*'))
|| scanResult.glob.includes('*/')
|| scanResult.glob.includes('**/')
let files = []
if (recursive) {
files = readdirRecursive(base, [])
} else {
files = __fs__.readdirSync(base).map(f => __path__.join(base, f))
}
const isMatch = __pm__(subpattern, {windows: true})
return files.filter(f => isMatch(f));
} catch (e) {
if (e.code === 'ENOENT' || e.code === 'EACCES' || e.code === 'ENOTDIR') {
return []
}
throw e
}
})
}
end
alias getwd pwd
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/base.rb | stdlib/nodejs/base.rb | # backtick_javascript: true
module NodeJS
VERSION = `process.version`
end
`Opal.exit = process.exit`
ARGV = `process.argv.slice(2)`
ARGV.shift if ARGV.first == '--'
STDOUT.write_proc = ->(string) { `process.stdout.write(string)` }
STDERR.write_proc = ->(string) { `process.stderr.write(string)` }
`var __fs__ = require('fs')`
STDIN.read_proc = %x{function(_count) {
// Ignore count, return as much as we can get
var buf = Buffer.alloc(65536), count;
try {
count = __fs__.readSync(this.fd, buf, 0, 65536, null);
}
catch { // Windows systems may raise EOF
return nil;
}
if (count == 0) return nil;
return buf.toString('utf8', 0, count);
}}
STDIN.tty = true
STDOUT.tty = true
STDERR.tty = true
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/process.rb | stdlib/nodejs/process.rb | # backtick_javascript: true
module ::Process
def self.pid
`Opal.Kernel.__process__.pid`
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/require.rb | stdlib/nodejs/require.rb | # backtick_javascript: true
require 'opal-parser'
module Kernel
def __prepare_require__(path)
name = `Opal.normalize(#{path})`
full_path = name.end_with?('.rb') ? name : name + '.rb'
if `!Opal.modules[#{name}]`
ruby = File.read(full_path)
compiler = Opal::Compiler.new(ruby, requirable: true, file: name)
js = compiler.compile
compiler.requires.each do |sub_path|
__prepare_require__(sub_path)
end
`eval(#{js})`
end
name
rescue => e
raise [path, name, full_path].inspect + e.message
end
def require(path)
`Opal.require(#{__prepare_require__(path)})`
end
def load(path)
`Opal.load(#{__prepare_require__(path)})`
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/pathname.rb | stdlib/nodejs/pathname.rb | # backtick_javascript: true
require 'pathname'
class Pathname
include Comparable
@__path__ = `require('path')`
`var __path__ = #{@__path__}`
def absolute?
`__path__.isAbsolute(#{@path.to_str})`
end
def relative?
!absolute?
end
def to_path
@path
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/nodejs/tmpdir.rb | stdlib/nodejs/tmpdir.rb | class Dir
def self.mktmpdir(prefix_suffix = nil, *_rest, **_options)
if `prefix_suffix.$$is_array`
prefix = prefix_suffix.join('')
elsif `prefix_suffix.$$is_string`
prefix = prefix_suffix
else
prefix = 'd'
end
path = `#@__fs__.mkdtempSync(prefix)`
if block_given?
res = yield path
`#@__fs__.rmdirSync(path)`
return res
end
path
end
def self.tmpdir
`#@__os__.tmpdir()`
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/date/formatters.rb | stdlib/date/formatters.rb | class Date
def self.def_formatter(*args, **kwargs)
Time.def_formatter(*args, **kwargs, on: self)
end
def_formatter :asctime, '%c'
alias ctime asctime
def_formatter :iso8601, '%F'
alias xmlschema iso8601
def_formatter :rfc3339, '%FT%T%:z'
def_formatter :rfc2822, '%a, %-d %b %Y %T %z'
alias rfc822 rfc2822
def_formatter :httpdate, '%a, %d %b %Y %T GMT', utc: true
def_formatter :jisx0301, '%J'
alias to_s iso8601
end
class DateTime < Date
def_formatter :xmlschema, '%FT%T', fractions: true, tz_format: '%:z'
alias iso8601 xmlschema
alias rfc3339 xmlschema
def_formatter :jisx0301, '%JT%T', fractions: true, tz_format: '%:z'
alias to_s xmlschema
def_formatter :zone, '%:z'
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/date/infinity.rb | stdlib/date/infinity.rb | class Date
class Infinity < Numeric
include Comparable
def initialize(d = 1)
@d = d <=> 0
end
attr_reader :d
def zero?
false
end
def finite?
false
end
def infinite?
d.nonzero?
end
def nan?
d.zero?
end
def abs
self.class.new
end
def -@
self.class.new(-d)
end
def +@
self.class.new(+d)
end
def <=>(other)
case other
when Infinity
d <=> other.d
when Numeric
d
else
begin
l, r = other.coerce(self)
l <=> r
rescue NoMethodError
nil
end
end
end
def coerce(other)
case other
when Numeric
[-d, d]
else
super
end
end
def to_f
return 0 if @d == 0
if @d > 0
Float::INFINITY
else
-Float::INFINITY
end
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/date/date_time.rb | stdlib/date/date_time.rb | # backtick_javascript: true
class DateTime < Date
class << self
def now
wrap Time.now
end
def parse(str)
wrap Time.parse(str)
end
end
def initialize(year = -4712, month = 1, day = 1, hours = 0, minutes = 0, seconds = 0, offset = 0, start = ITALY)
%x{
// Because of Gregorian reform calendar goes from 1582-10-04 to 1582-10-15.
// All days in between end up as 4 october.
if (year === 1582 && month === 10 && day > 4 && day < 15) {
day = 4;
}
}
@date = Time.new(year, month, day, hours, minutes, seconds, offset)
@start = start
end
def_delegators :@date, :min, :hour, :sec
alias minute min
alias second sec
def sec_fraction
@date.usec/1_000_000r
end
alias second_fraction sec_fraction
def offset
@date.gmt_offset / (24 * 3600r)
end
def +(other)
::DateTime.wrap @date + other
end
def -(other)
`if (Opal.is_a(other, #{::Date})) other = other.date`
result = @date - other
if result.is_a? ::Time
::DateTime.wrap result
else
result
end
end
def new_offset(offset)
new_date = clone
offset = Time._parse_offset(offset)
`new_date.date.timezone = offset`
new_date
end
def to_datetime
self
end
def to_time
@date.dup
end
def to_date
Date.new(year, month, day)
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/rbconfig/sizeof.rb | stdlib/rbconfig/sizeof.rb | # This file is not intended for real checks,
# but just to make happy libraries needing it.
require_relative '../rbconfig'
RbConfig::SIZEOF = {
'clock_t' => 8,
'double _Complex' => 16,
'double' => 8,
'float _Complex' => 8,
'float' => 4,
'int' => 4,
'int128_t' => 16,
'int16_t' => 2,
'int32_t' => 4,
'int64_t' => 8,
'int8_t' => 1,
'intmax_t' => 8,
'intptr_t' => 8,
'int_fast16_t' => 2,
'int_fast32_t' => 4,
'int_fast64_t' => 8,
'int_fast8_t' => 1,
'int_least16_t' => 2,
'int_least32_t' => 4,
'int_least64_t' => 8,
'int_least8_t' => 1,
'long double _Complex' => 32,
'long double' => 16,
'long long' => 8,
'long' => 8,
'off_t' => 8,
'ptrdiff_t' => 8,
'short' => 2,
'sig_atomic_t' => 4,
'size_t' => 8,
'ssize_t' => 8,
'time_t' => 8,
'uint128_t' => 16,
'uint16_t' => 2,
'uint32_t' => 4,
'uint64_t' => 8,
'uint8_t' => 1,
'uintptr_t' => 8,
'void*' => 8,
'wchar_t' => 4,
'wctrans_t' => 4,
'wctype_t' => 4,
'wint_t' => 4,
'_Bool' => 1,
'__int128' => 16,
}
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/optparse/version.rb | stdlib/optparse/version.rb | # frozen_string_literal: false
# OptionParser internal utility
class << OptionParser
def show_version(*pkgs)
progname = ARGV.options.program_name
result = false
show = proc do |klass, cname, version|
str = progname.to_s
unless (klass == ::Object) && (cname == :VERSION)
version = version.join('.') if Array === version
str << ": #{klass}" unless klass == Object
str << " version #{version}"
end
%i[Release RELEASE].find do |rel|
if klass.const_defined?(rel)
str << " (#{klass.const_get(rel)})"
end
end
puts str
result = true
end
if (pkgs.size == 1) && (pkgs[0] == 'all')
search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
unless (cname[1] == 'e') && klass.const_defined?(:Version)
show.call(klass, cname.intern, version)
end
end
else
pkgs.each do |pkg|
pkg = pkg.split(/::|\//).inject(::Object) { |m, c| m.const_get(c) }
v = case
when pkg.const_defined?(:Version)
pkg.const_get(n = :Version)
when pkg.const_defined?(:VERSION)
pkg.const_get(n = :VERSION)
else
n = nil
'unknown'
end
show.call(pkg, n, v)
rescue NameError
end
end
result
end
def each_const(path, base = ::Object)
path.split(/::|\//).inject(base) do |klass, name|
raise NameError, path unless Module === klass
klass.constants.grep(/#{name}/i) do |c|
klass.const_defined?(c) || next
klass.const_get(c)
end
end
end
def search_const(klass, name)
klasses = [klass]
while klass = klasses.shift
klass.constants.each do |cname|
klass.const_defined?(cname) || next
const = klass.const_get(cname)
yield klass, cname, const if name === cname
klasses << const if (Module === const) && (const != ::Object)
end
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/optparse/time.rb | stdlib/optparse/time.rb | # frozen_string_literal: false
require 'optparse'
require 'time'
OptionParser.accept(Time) do |s,|
if s
(begin
Time.httpdate(s)
rescue
Time.parse(s)
end)
end
rescue
raise OptionParser::InvalidArgument, s
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/optparse/kwargs.rb | stdlib/optparse/kwargs.rb | # frozen_string_literal: true
require 'optparse'
class OptionParser
# :call-seq:
# define_by_keywords(options, method, **params)
#
# :include: ../../doc/optparse/creates_option.rdoc
#
def define_by_keywords(options, meth, **opts)
meth.parameters.each do |type, name|
case type
when :key, :keyreq
op, cl = *(type == :key ? %w"[ ]" : ['', ''])
define("--#{name}=#{op}#{name.upcase}#{cl}", *opts[name]) do |o|
options[name] = o
end
end
end
options
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/optparse/uri.rb | stdlib/optparse/uri.rb | # frozen_string_literal: false
# -*- ruby -*-
require 'optparse'
require 'uri'
OptionParser.accept(URI) { |s,| URI.parse(s) if s }
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/optparse/shellwords.rb | stdlib/optparse/shellwords.rb | # frozen_string_literal: false
# -*- ruby -*-
require 'shellwords'
require 'optparse'
OptionParser.accept(Shellwords) { |s,| Shellwords.shellwords(s) }
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/optparse/date.rb | stdlib/optparse/date.rb | # frozen_string_literal: false
require 'optparse'
require 'date'
OptionParser.accept(DateTime) do |s,|
DateTime.parse(s) if s
rescue ArgumentError
raise OptionParser::InvalidArgument, s
end
OptionParser.accept(Date) do |s,|
Date.parse(s) if s
rescue ArgumentError
raise OptionParser::InvalidArgument, s
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/optparse/ac.rb | stdlib/optparse/ac.rb | # frozen_string_literal: false
require 'optparse'
class OptionParser::AC < OptionParser
private
def _check_ac_args(name, block)
unless /\A\w[-\w]*\z/ =~ name
raise ArgumentError, name
end
unless block
raise ArgumentError, 'no block given', ParseError.filter_backtrace(caller)
end
end
ARG_CONV = proc { |val| val.nil? ? true : val }
def _ac_arg_enable(prefix, name, help_string, block)
_check_ac_args(name, block)
sdesc = []
ldesc = ["--#{prefix}-#{name}"]
desc = [help_string]
q = name.downcase
ac_block = proc { |val| block.call(ARG_CONV.call(val)) }
enable = Switch::PlacedArgument.new(nil, ARG_CONV, sdesc, ldesc, nil, desc, ac_block)
disable = Switch::NoArgument.new(nil, proc { false }, sdesc, ldesc, nil, desc, ac_block)
top.append(enable, [], ['enable-' + q], disable, ['disable-' + q])
enable
end
public
def ac_arg_enable(name, help_string, &block)
_ac_arg_enable('enable', name, help_string, block)
end
def ac_arg_disable(name, help_string, &block)
_ac_arg_enable('disable', name, help_string, block)
end
def ac_arg_with(name, help_string, &block)
_check_ac_args(name, block)
sdesc = []
ldesc = ["--with-#{name}"]
desc = [help_string]
q = name.downcase
with = Switch::PlacedArgument.new(*search(:atype, String), sdesc, ldesc, nil, desc, block)
without = Switch::NoArgument.new(nil, proc {}, sdesc, ldesc, nil, desc, block)
top.append(with, [], ['with-' + q], without, ['without-' + q])
with
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/matrix/eigenvalue_decomposition.rb | stdlib/matrix/eigenvalue_decomposition.rb | # frozen_string_literal: false
class Matrix
# Adapted from JAMA: http://math.nist.gov/javanumerics/jama/
# Eigenvalues and eigenvectors of a real matrix.
#
# Computes the eigenvalues and eigenvectors of a matrix A.
#
# If A is diagonalizable, this provides matrices V and D
# such that A = V*D*V.inv, where D is the diagonal matrix with entries
# equal to the eigenvalues and V is formed by the eigenvectors.
#
# If A is symmetric, then V is orthogonal and thus A = V*D*V.t
class EigenvalueDecomposition
# Constructs the eigenvalue decomposition for a square matrix +A+
#
def initialize(a)
# @d, @e: Arrays for internal storage of eigenvalues.
# @v: Array for internal storage of eigenvectors.
# @h: Array for internal storage of nonsymmetric Hessenberg form.
raise TypeError, "Expected Matrix but got #{a.class}" unless a.is_a?(Matrix)
@size = a.row_count
@d = Array.new(@size, 0)
@e = Array.new(@size, 0)
if (@symmetric = a.symmetric?)
@v = a.to_a
tridiagonalize
diagonalize
else
@v = Array.new(@size) { Array.new(@size, 0) }
@h = a.to_a
@ort = Array.new(@size, 0)
reduce_to_hessenberg
hessenberg_to_real_schur
end
end
# Returns the eigenvector matrix +V+
#
def eigenvector_matrix
Matrix.send(:new, build_eigenvectors.transpose)
end
alias v eigenvector_matrix
# Returns the inverse of the eigenvector matrix +V+
#
def eigenvector_matrix_inv
r = Matrix.send(:new, build_eigenvectors)
r = r.transpose.inverse unless @symmetric
r
end
alias v_inv eigenvector_matrix_inv
# Returns the eigenvalues in an array
#
def eigenvalues
values = @d.dup
@e.each_with_index{|imag, i| values[i] = Complex(values[i], imag) unless imag == 0}
values
end
# Returns an array of the eigenvectors
#
def eigenvectors
build_eigenvectors.map{|ev| Vector.send(:new, ev)}
end
# Returns the block diagonal eigenvalue matrix +D+
#
def eigenvalue_matrix
Matrix.diagonal(*eigenvalues)
end
alias d eigenvalue_matrix
# Returns [eigenvector_matrix, eigenvalue_matrix, eigenvector_matrix_inv]
#
def to_ary
[v, d, v_inv]
end
alias_method :to_a, :to_ary
private
def build_eigenvectors
# JAMA stores complex eigenvectors in a strange way
# See http://web.archive.org/web/20111016032731/http://cio.nist.gov/esd/emaildir/lists/jama/msg01021.html
@e.each_with_index.map do |imag, i|
if imag == 0
Array.new(@size){|j| @v[j][i]}
elsif imag > 0
Array.new(@size){|j| Complex(@v[j][i], @v[j][i+1])}
else
Array.new(@size){|j| Complex(@v[j][i-1], -@v[j][i])}
end
end
end
# Complex scalar division.
def cdiv(xr, xi, yr, yi)
if (yr.abs > yi.abs)
r = yi/yr
d = yr + r*yi
[(xr + r*xi)/d, (xi - r*xr)/d]
else
r = yr/yi
d = yi + r*yr
[(r*xr + xi)/d, (r*xi - xr)/d]
end
end
# Symmetric Householder reduction to tridiagonal form.
def tridiagonalize
# This is derived from the Algol procedures tred2 by
# Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
# Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
# Fortran subroutine in EISPACK.
@size.times do |j|
@d[j] = @v[@size-1][j]
end
# Householder reduction to tridiagonal form.
(@size-1).downto(0+1) do |i|
# Scale to avoid under/overflow.
scale = 0.0
h = 0.0
i.times do |k|
scale = scale + @d[k].abs
end
if (scale == 0.0)
@e[i] = @d[i-1]
i.times do |j|
@d[j] = @v[i-1][j]
@v[i][j] = 0.0
@v[j][i] = 0.0
end
else
# Generate Householder vector.
i.times do |k|
@d[k] /= scale
h += @d[k] * @d[k]
end
f = @d[i-1]
g = Math.sqrt(h)
if (f > 0)
g = -g
end
@e[i] = scale * g
h -= f * g
@d[i-1] = f - g
i.times do |j|
@e[j] = 0.0
end
# Apply similarity transformation to remaining columns.
i.times do |j|
f = @d[j]
@v[j][i] = f
g = @e[j] + @v[j][j] * f
(j+1).upto(i-1) do |k|
g += @v[k][j] * @d[k]
@e[k] += @v[k][j] * f
end
@e[j] = g
end
f = 0.0
i.times do |j|
@e[j] /= h
f += @e[j] * @d[j]
end
hh = f / (h + h)
i.times do |j|
@e[j] -= hh * @d[j]
end
i.times do |j|
f = @d[j]
g = @e[j]
j.upto(i-1) do |k|
@v[k][j] -= (f * @e[k] + g * @d[k])
end
@d[j] = @v[i-1][j]
@v[i][j] = 0.0
end
end
@d[i] = h
end
# Accumulate transformations.
0.upto(@size-1-1) do |i|
@v[@size-1][i] = @v[i][i]
@v[i][i] = 1.0
h = @d[i+1]
if (h != 0.0)
0.upto(i) do |k|
@d[k] = @v[k][i+1] / h
end
0.upto(i) do |j|
g = 0.0
0.upto(i) do |k|
g += @v[k][i+1] * @v[k][j]
end
0.upto(i) do |k|
@v[k][j] -= g * @d[k]
end
end
end
0.upto(i) do |k|
@v[k][i+1] = 0.0
end
end
@size.times do |j|
@d[j] = @v[@size-1][j]
@v[@size-1][j] = 0.0
end
@v[@size-1][@size-1] = 1.0
@e[0] = 0.0
end
# Symmetric tridiagonal QL algorithm.
def diagonalize
# This is derived from the Algol procedures tql2, by
# Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
# Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
# Fortran subroutine in EISPACK.
1.upto(@size-1) do |i|
@e[i-1] = @e[i]
end
@e[@size-1] = 0.0
f = 0.0
tst1 = 0.0
eps = Float::EPSILON
@size.times do |l|
# Find small subdiagonal element
tst1 = [tst1, @d[l].abs + @e[l].abs].max
m = l
while (m < @size) do
if (@e[m].abs <= eps*tst1)
break
end
m+=1
end
# If m == l, @d[l] is an eigenvalue,
# otherwise, iterate.
if (m > l)
iter = 0
begin
iter = iter + 1 # (Could check iteration count here.)
# Compute implicit shift
g = @d[l]
p = (@d[l+1] - g) / (2.0 * @e[l])
r = Math.hypot(p, 1.0)
if (p < 0)
r = -r
end
@d[l] = @e[l] / (p + r)
@d[l+1] = @e[l] * (p + r)
dl1 = @d[l+1]
h = g - @d[l]
(l+2).upto(@size-1) do |i|
@d[i] -= h
end
f += h
# Implicit QL transformation.
p = @d[m]
c = 1.0
c2 = c
c3 = c
el1 = @e[l+1]
s = 0.0
s2 = 0.0
(m-1).downto(l) do |i|
c3 = c2
c2 = c
s2 = s
g = c * @e[i]
h = c * p
r = Math.hypot(p, @e[i])
@e[i+1] = s * r
s = @e[i] / r
c = p / r
p = c * @d[i] - s * g
@d[i+1] = h + s * (c * g + s * @d[i])
# Accumulate transformation.
@size.times do |k|
h = @v[k][i+1]
@v[k][i+1] = s * @v[k][i] + c * h
@v[k][i] = c * @v[k][i] - s * h
end
end
p = -s * s2 * c3 * el1 * @e[l] / dl1
@e[l] = s * p
@d[l] = c * p
# Check for convergence.
end while (@e[l].abs > eps*tst1)
end
@d[l] = @d[l] + f
@e[l] = 0.0
end
# Sort eigenvalues and corresponding vectors.
0.upto(@size-2) do |i|
k = i
p = @d[i]
(i+1).upto(@size-1) do |j|
if (@d[j] < p)
k = j
p = @d[j]
end
end
if (k != i)
@d[k] = @d[i]
@d[i] = p
@size.times do |j|
p = @v[j][i]
@v[j][i] = @v[j][k]
@v[j][k] = p
end
end
end
end
# Nonsymmetric reduction to Hessenberg form.
def reduce_to_hessenberg
# This is derived from the Algol procedures orthes and ortran,
# by Martin and Wilkinson, Handbook for Auto. Comp.,
# Vol.ii-Linear Algebra, and the corresponding
# Fortran subroutines in EISPACK.
low = 0
high = @size-1
(low+1).upto(high-1) do |m|
# Scale column.
scale = 0.0
m.upto(high) do |i|
scale = scale + @h[i][m-1].abs
end
if (scale != 0.0)
# Compute Householder transformation.
h = 0.0
high.downto(m) do |i|
@ort[i] = @h[i][m-1]/scale
h += @ort[i] * @ort[i]
end
g = Math.sqrt(h)
if (@ort[m] > 0)
g = -g
end
h -= @ort[m] * g
@ort[m] = @ort[m] - g
# Apply Householder similarity transformation
# @h = (I-u*u'/h)*@h*(I-u*u')/h)
m.upto(@size-1) do |j|
f = 0.0
high.downto(m) do |i|
f += @ort[i]*@h[i][j]
end
f = f/h
m.upto(high) do |i|
@h[i][j] -= f*@ort[i]
end
end
0.upto(high) do |i|
f = 0.0
high.downto(m) do |j|
f += @ort[j]*@h[i][j]
end
f = f/h
m.upto(high) do |j|
@h[i][j] -= f*@ort[j]
end
end
@ort[m] = scale*@ort[m]
@h[m][m-1] = scale*g
end
end
# Accumulate transformations (Algol's ortran).
@size.times do |i|
@size.times do |j|
@v[i][j] = (i == j ? 1.0 : 0.0)
end
end
(high-1).downto(low+1) do |m|
if (@h[m][m-1] != 0.0)
(m+1).upto(high) do |i|
@ort[i] = @h[i][m-1]
end
m.upto(high) do |j|
g = 0.0
m.upto(high) do |i|
g += @ort[i] * @v[i][j]
end
# Double division avoids possible underflow
g = (g / @ort[m]) / @h[m][m-1]
m.upto(high) do |i|
@v[i][j] += g * @ort[i]
end
end
end
end
end
# Nonsymmetric reduction from Hessenberg to real Schur form.
def hessenberg_to_real_schur
# This is derived from the Algol procedure hqr2,
# by Martin and Wilkinson, Handbook for Auto. Comp.,
# Vol.ii-Linear Algebra, and the corresponding
# Fortran subroutine in EISPACK.
# Initialize
nn = @size
n = nn-1
low = 0
high = nn-1
eps = Float::EPSILON
exshift = 0.0
p = q = r = s = z = 0
# Store roots isolated by balanc and compute matrix norm
norm = 0.0
nn.times do |i|
if (i < low || i > high)
@d[i] = @h[i][i]
@e[i] = 0.0
end
([i-1, 0].max).upto(nn-1) do |j|
norm = norm + @h[i][j].abs
end
end
# Outer loop over eigenvalue index
iter = 0
while (n >= low) do
# Look for single small sub-diagonal element
l = n
while (l > low) do
s = @h[l-1][l-1].abs + @h[l][l].abs
if (s == 0.0)
s = norm
end
if (@h[l][l-1].abs < eps * s)
break
end
l-=1
end
# Check for convergence
# One root found
if (l == n)
@h[n][n] = @h[n][n] + exshift
@d[n] = @h[n][n]
@e[n] = 0.0
n-=1
iter = 0
# Two roots found
elsif (l == n-1)
w = @h[n][n-1] * @h[n-1][n]
p = (@h[n-1][n-1] - @h[n][n]) / 2.0
q = p * p + w
z = Math.sqrt(q.abs)
@h[n][n] = @h[n][n] + exshift
@h[n-1][n-1] = @h[n-1][n-1] + exshift
x = @h[n][n]
# Real pair
if (q >= 0)
if (p >= 0)
z = p + z
else
z = p - z
end
@d[n-1] = x + z
@d[n] = @d[n-1]
if (z != 0.0)
@d[n] = x - w / z
end
@e[n-1] = 0.0
@e[n] = 0.0
x = @h[n][n-1]
s = x.abs + z.abs
p = x / s
q = z / s
r = Math.sqrt(p * p+q * q)
p /= r
q /= r
# Row modification
(n-1).upto(nn-1) do |j|
z = @h[n-1][j]
@h[n-1][j] = q * z + p * @h[n][j]
@h[n][j] = q * @h[n][j] - p * z
end
# Column modification
0.upto(n) do |i|
z = @h[i][n-1]
@h[i][n-1] = q * z + p * @h[i][n]
@h[i][n] = q * @h[i][n] - p * z
end
# Accumulate transformations
low.upto(high) do |i|
z = @v[i][n-1]
@v[i][n-1] = q * z + p * @v[i][n]
@v[i][n] = q * @v[i][n] - p * z
end
# Complex pair
else
@d[n-1] = x + p
@d[n] = x + p
@e[n-1] = z
@e[n] = -z
end
n -= 2
iter = 0
# No convergence yet
else
# Form shift
x = @h[n][n]
y = 0.0
w = 0.0
if (l < n)
y = @h[n-1][n-1]
w = @h[n][n-1] * @h[n-1][n]
end
# Wilkinson's original ad hoc shift
if (iter == 10)
exshift += x
low.upto(n) do |i|
@h[i][i] -= x
end
s = @h[n][n-1].abs + @h[n-1][n-2].abs
x = y = 0.75 * s
w = -0.4375 * s * s
end
# MATLAB's new ad hoc shift
if (iter == 30)
s = (y - x) / 2.0
s *= s + w
if (s > 0)
s = Math.sqrt(s)
if (y < x)
s = -s
end
s = x - w / ((y - x) / 2.0 + s)
low.upto(n) do |i|
@h[i][i] -= s
end
exshift += s
x = y = w = 0.964
end
end
iter = iter + 1 # (Could check iteration count here.)
# Look for two consecutive small sub-diagonal elements
m = n-2
while (m >= l) do
z = @h[m][m]
r = x - z
s = y - z
p = (r * s - w) / @h[m+1][m] + @h[m][m+1]
q = @h[m+1][m+1] - z - r - s
r = @h[m+2][m+1]
s = p.abs + q.abs + r.abs
p /= s
q /= s
r /= s
if (m == l)
break
end
if (@h[m][m-1].abs * (q.abs + r.abs) <
eps * (p.abs * (@h[m-1][m-1].abs + z.abs +
@h[m+1][m+1].abs)))
break
end
m-=1
end
(m+2).upto(n) do |i|
@h[i][i-2] = 0.0
if (i > m+2)
@h[i][i-3] = 0.0
end
end
# Double QR step involving rows l:n and columns m:n
m.upto(n-1) do |k|
notlast = (k != n-1)
if (k != m)
p = @h[k][k-1]
q = @h[k+1][k-1]
r = (notlast ? @h[k+2][k-1] : 0.0)
x = p.abs + q.abs + r.abs
next if x == 0
p /= x
q /= x
r /= x
end
s = Math.sqrt(p * p + q * q + r * r)
if (p < 0)
s = -s
end
if (s != 0)
if (k != m)
@h[k][k-1] = -s * x
elsif (l != m)
@h[k][k-1] = -@h[k][k-1]
end
p += s
x = p / s
y = q / s
z = r / s
q /= p
r /= p
# Row modification
k.upto(nn-1) do |j|
p = @h[k][j] + q * @h[k+1][j]
if (notlast)
p += r * @h[k+2][j]
@h[k+2][j] = @h[k+2][j] - p * z
end
@h[k][j] = @h[k][j] - p * x
@h[k+1][j] = @h[k+1][j] - p * y
end
# Column modification
0.upto([n, k+3].min) do |i|
p = x * @h[i][k] + y * @h[i][k+1]
if (notlast)
p += z * @h[i][k+2]
@h[i][k+2] = @h[i][k+2] - p * r
end
@h[i][k] = @h[i][k] - p
@h[i][k+1] = @h[i][k+1] - p * q
end
# Accumulate transformations
low.upto(high) do |i|
p = x * @v[i][k] + y * @v[i][k+1]
if (notlast)
p += z * @v[i][k+2]
@v[i][k+2] = @v[i][k+2] - p * r
end
@v[i][k] = @v[i][k] - p
@v[i][k+1] = @v[i][k+1] - p * q
end
end # (s != 0)
end # k loop
end # check convergence
end # while (n >= low)
# Backsubstitute to find vectors of upper triangular form
if (norm == 0.0)
return
end
(nn-1).downto(0) do |k|
p = @d[k]
q = @e[k]
# Real vector
if (q == 0)
l = k
@h[k][k] = 1.0
(k-1).downto(0) do |i|
w = @h[i][i] - p
r = 0.0
l.upto(k) do |j|
r += @h[i][j] * @h[j][k]
end
if (@e[i] < 0.0)
z = w
s = r
else
l = i
if (@e[i] == 0.0)
if (w != 0.0)
@h[i][k] = -r / w
else
@h[i][k] = -r / (eps * norm)
end
# Solve real equations
else
x = @h[i][i+1]
y = @h[i+1][i]
q = (@d[i] - p) * (@d[i] - p) + @e[i] * @e[i]
t = (x * s - z * r) / q
@h[i][k] = t
if (x.abs > z.abs)
@h[i+1][k] = (-r - w * t) / x
else
@h[i+1][k] = (-s - y * t) / z
end
end
# Overflow control
t = @h[i][k].abs
if ((eps * t) * t > 1)
i.upto(k) do |j|
@h[j][k] = @h[j][k] / t
end
end
end
end
# Complex vector
elsif (q < 0)
l = n-1
# Last vector component imaginary so matrix is triangular
if (@h[n][n-1].abs > @h[n-1][n].abs)
@h[n-1][n-1] = q / @h[n][n-1]
@h[n-1][n] = -(@h[n][n] - p) / @h[n][n-1]
else
cdivr, cdivi = cdiv(0.0, -@h[n-1][n], @h[n-1][n-1]-p, q)
@h[n-1][n-1] = cdivr
@h[n-1][n] = cdivi
end
@h[n][n-1] = 0.0
@h[n][n] = 1.0
(n-2).downto(0) do |i|
ra = 0.0
sa = 0.0
l.upto(n) do |j|
ra = ra + @h[i][j] * @h[j][n-1]
sa = sa + @h[i][j] * @h[j][n]
end
w = @h[i][i] - p
if (@e[i] < 0.0)
z = w
r = ra
s = sa
else
l = i
if (@e[i] == 0)
cdivr, cdivi = cdiv(-ra, -sa, w, q)
@h[i][n-1] = cdivr
@h[i][n] = cdivi
else
# Solve complex equations
x = @h[i][i+1]
y = @h[i+1][i]
vr = (@d[i] - p) * (@d[i] - p) + @e[i] * @e[i] - q * q
vi = (@d[i] - p) * 2.0 * q
if (vr == 0.0 && vi == 0.0)
vr = eps * norm * (w.abs + q.abs +
x.abs + y.abs + z.abs)
end
cdivr, cdivi = cdiv(x*r-z*ra+q*sa, x*s-z*sa-q*ra, vr, vi)
@h[i][n-1] = cdivr
@h[i][n] = cdivi
if (x.abs > (z.abs + q.abs))
@h[i+1][n-1] = (-ra - w * @h[i][n-1] + q * @h[i][n]) / x
@h[i+1][n] = (-sa - w * @h[i][n] - q * @h[i][n-1]) / x
else
cdivr, cdivi = cdiv(-r-y*@h[i][n-1], -s-y*@h[i][n], z, q)
@h[i+1][n-1] = cdivr
@h[i+1][n] = cdivi
end
end
# Overflow control
t = [@h[i][n-1].abs, @h[i][n].abs].max
if ((eps * t) * t > 1)
i.upto(n) do |j|
@h[j][n-1] = @h[j][n-1] / t
@h[j][n] = @h[j][n] / t
end
end
end
end
end
end
# Vectors of isolated roots
nn.times do |i|
if (i < low || i > high)
i.upto(nn-1) do |j|
@v[i][j] = @h[i][j]
end
end
end
# Back transformation to get eigenvectors of original matrix
(nn-1).downto(low) do |j|
low.upto(high) do |i|
z = 0.0
low.upto([j, high].min) do |k|
z += @v[i][k] * @h[k][j]
end
@v[i][j] = z
end
end
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/matrix/lup_decomposition.rb | stdlib/matrix/lup_decomposition.rb | # frozen_string_literal: false
class Matrix
# Adapted from JAMA: http://math.nist.gov/javanumerics/jama/
#
# For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
# unit lower triangular matrix L, an n-by-n upper triangular matrix U,
# and a m-by-m permutation matrix P so that L*U = P*A.
# If m < n, then L is m-by-m and U is m-by-n.
#
# The LUP decomposition with pivoting always exists, even if the matrix is
# singular, so the constructor will never fail. The primary use of the
# LU decomposition is in the solution of square systems of simultaneous
# linear equations. This will fail if singular? returns true.
#
class LUPDecomposition
# Returns the lower triangular factor +L+
include Matrix::ConversionHelper
def l
Matrix.build(@row_count, [@column_count, @row_count].min) do |i, j|
if (i > j)
@lu[i][j]
elsif (i == j)
1
else
0
end
end
end
# Returns the upper triangular factor +U+
def u
Matrix.build([@column_count, @row_count].min, @column_count) do |i, j|
if (i <= j)
@lu[i][j]
else
0
end
end
end
# Returns the permutation matrix +P+
def p
rows = Array.new(@row_count){Array.new(@row_count, 0)}
@pivots.each_with_index{|p, i| rows[i][p] = 1}
Matrix.send :new, rows, @row_count
end
# Returns +L+, +U+, +P+ in an array
def to_ary
[l, u, p]
end
alias_method :to_a, :to_ary
# Returns the pivoting indices
attr_reader :pivots
# Returns +true+ if +U+, and hence +A+, is singular.
def singular?
@column_count.times do |j|
if (@lu[j][j] == 0)
return true
end
end
false
end
# Returns the determinant of +A+, calculated efficiently
# from the factorization.
def det
if (@row_count != @column_count)
Matrix.Raise Matrix::ErrDimensionMismatch
end
d = @pivot_sign
@column_count.times do |j|
d *= @lu[j][j]
end
d
end
alias_method :determinant, :det
# Returns +m+ so that <tt>A*m = b</tt>,
# or equivalently so that <tt>L*U*m = P*b</tt>
# +b+ can be a Matrix or a Vector
def solve b
if (singular?)
Matrix.Raise Matrix::ErrNotRegular, "Matrix is singular."
end
if b.is_a? Matrix
if (b.row_count != @row_count)
Matrix.Raise Matrix::ErrDimensionMismatch
end
# Copy right hand side with pivoting
nx = b.column_count
m = @pivots.map{|row| b.row(row).to_a}
# Solve L*Y = P*b
@column_count.times do |k|
(k+1).upto(@column_count-1) do |i|
nx.times do |j|
m[i][j] -= m[k][j]*@lu[i][k]
end
end
end
# Solve U*m = Y
(@column_count-1).downto(0) do |k|
nx.times do |j|
m[k][j] = m[k][j].quo(@lu[k][k])
end
k.times do |i|
nx.times do |j|
m[i][j] -= m[k][j]*@lu[i][k]
end
end
end
Matrix.send :new, m, nx
else # same algorithm, specialized for simpler case of a vector
b = convert_to_array(b)
if (b.size != @row_count)
Matrix.Raise Matrix::ErrDimensionMismatch
end
# Copy right hand side with pivoting
m = b.values_at(*@pivots)
# Solve L*Y = P*b
@column_count.times do |k|
(k+1).upto(@column_count-1) do |i|
m[i] -= m[k]*@lu[i][k]
end
end
# Solve U*m = Y
(@column_count-1).downto(0) do |k|
m[k] = m[k].quo(@lu[k][k])
k.times do |i|
m[i] -= m[k]*@lu[i][k]
end
end
Vector.elements(m, false)
end
end
def initialize a
raise TypeError, "Expected Matrix but got #{a.class}" unless a.is_a?(Matrix)
# Use a "left-looking", dot-product, Crout/Doolittle algorithm.
@lu = a.to_a
@row_count = a.row_count
@column_count = a.column_count
@pivots = Array.new(@row_count)
@row_count.times do |i|
@pivots[i] = i
end
@pivot_sign = 1
lu_col_j = Array.new(@row_count)
# Outer loop.
@column_count.times do |j|
# Make a copy of the j-th column to localize references.
@row_count.times do |i|
lu_col_j[i] = @lu[i][j]
end
# Apply previous transformations.
@row_count.times do |i|
lu_row_i = @lu[i]
# Most of the time is spent in the following dot product.
kmax = [i, j].min
s = 0
kmax.times do |k|
s += lu_row_i[k]*lu_col_j[k]
end
lu_row_i[j] = lu_col_j[i] -= s
end
# Find pivot and exchange if necessary.
p = j
(j+1).upto(@row_count-1) do |i|
if (lu_col_j[i].abs > lu_col_j[p].abs)
p = i
end
end
if (p != j)
@column_count.times do |k|
t = @lu[p][k]; @lu[p][k] = @lu[j][k]; @lu[j][k] = t
end
k = @pivots[p]; @pivots[p] = @pivots[j]; @pivots[j] = k
@pivot_sign = -@pivot_sign
end
# Compute multipliers.
if (j < @row_count && @lu[j][j] != 0)
(j+1).upto(@row_count-1) do |i|
@lu[i][j] = @lu[i][j].quo(@lu[j][j])
end
end
end
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/headless_browser/file.rb | stdlib/headless_browser/file.rb | # frozen_string_literal: true
# backtick_javascript: true
class File
def self.write(path, data)
# This is only to enable CDP runners to write the benchmark results
%x{
var http = new XMLHttpRequest();
http.open("POST", "/File.write");
http.setRequestHeader("Content-Type", "application/json");
// Failure is not an option
http.send(JSON.stringify({filename: #{path}, data: #{data}, secret: window.OPAL_CDP_SHARED_SECRET}));
}
data.length
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/headless_browser/base.rb | stdlib/headless_browser/base.rb | # backtick_javascript: true
%x{
// Inhibit the default exit behavior
window.OPAL_EXIT_CODE = "noexit";
Opal.exit = function(code) {
// The first call to Opal.exit should save an exit code.
// All next invocations must be ignored.
// Then we send an event to Chrome CDP Interface that we are finished
if (window.OPAL_EXIT_CODE === "noexit") {
window.OPAL_EXIT_CODE = code;
window.alert("opalheadlessbrowserexit");
}
}
}
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/bigdecimal/util.rb | stdlib/bigdecimal/util.rb | # frozen_string_literal: false
# backtick_javascript: true
#
#--
# bigdecimal/util extends various native classes to provide the #to_d method,
# and provides BigDecimal#to_d and BigDecimal#to_digits.
#++
require 'bigdecimal'
class Integer < Numeric
# call-seq:
# int.to_d -> bigdecimal
#
# Returns the value of +int+ as a BigDecimal.
#
# require 'bigdecimal'
# require 'bigdecimal/util'
#
# 42.to_d # => 0.42e2
#
# See also BigDecimal::new.
#
def to_d
BigDecimal(self)
end
end
class Float < Numeric
# call-seq:
# float.to_d -> bigdecimal
# float.to_d(precision) -> bigdecimal
#
# Returns the value of +float+ as a BigDecimal.
# The +precision+ parameter is used to determine the number of
# significant digits for the result (the default is Float::DIG).
#
# require 'bigdecimal'
# require 'bigdecimal/util'
#
# 0.5.to_d # => 0.5e0
# 1.234.to_d(2) # => 0.12e1
#
# See also BigDecimal::new.
#
def to_d(precision = Float::DIG)
BigDecimal(self, precision)
end
end
class String
# call-seq:
# str.to_d -> bigdecimal
#
# Returns the result of interpreting leading characters in +str+
# as a BigDecimal.
#
# require 'bigdecimal'
# require 'bigdecimal/util'
#
# "0.5".to_d # => 0.5e0
# "123.45e1".to_d # => 0.12345e4
# "45.67 degrees".to_d # => 0.4567e2
#
# See also BigDecimal::new.
#
def to_d
BigDecimal(`#{self}.replace("_", '').replace(/ .*$/,'')`)
end
end
class BigDecimal < Numeric
# call-seq:
# a.to_digits -> string
#
# Converts a BigDecimal to a String of the form "nnnnnn.mmm".
# This method is deprecated; use BigDecimal#to_s("F") instead.
#
# require 'bigdecimal/util'
#
# d = BigDecimal("3.14")
# d.to_digits # => "3.14"
#
def to_digits
if nan? || infinite? || zero?
to_s
else
i = to_i.to_s
_, f, _, z = frac.split
i + '.' + ('0' * -z) + f
end
end
# call-seq:
# a.to_d -> bigdecimal
#
# Returns self.
#
# require 'bigdecimal/util'
#
# d = BigDecimal("3.14")
# d.to_d # => 0.314e1
#
def to_d
self
end
end
class Rational < Numeric
# call-seq:
# rat.to_d(precision) -> bigdecimal
#
# Returns the value as a BigDecimal.
#
# The required +precision+ parameter is used to determine the number of
# significant digits for the result.
#
# require 'bigdecimal'
# require 'bigdecimal/util'
#
# Rational(22, 7).to_d(3) # => 0.314e1
#
# See also BigDecimal::new.
#
def to_d(precision)
BigDecimal(self, precision)
end
end
class NilClass
# call-seq:
# nil.to_d -> bigdecimal
#
# Returns nil represented as a BigDecimal.
#
# require 'bigdecimal'
# require 'bigdecimal/util'
#
# nil.to_d # => 0.0
#
def to_d
BigDecimal(0)
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/bigdecimal/bignumber.js.rb | stdlib/bigdecimal/bignumber.js.rb | # backtick_javascript: true
class BigDecimal < Numeric
%x{
var define = function (f) { Opal.const_set(self, 'BigNumber', f()); };
define.amd = true;
/* eslint-disable */
/* bignumber.js v2.1.4 https://github.com/MikeMcl/bignumber.js/LICENCE */
!function(e){"use strict";function n(e){function E(e,n){var t,r,i,o,u,s,f=this;if(!(f instanceof E))return j&&L(26,"constructor call without new",e),new E(e,n);if(null!=n&&H(n,2,64,M,"base")){if(n=0|n,s=e+"",10==n)return f=new E(e instanceof E?e:s),U(f,P+f.e+1,k);if((o="number"==typeof e)&&0*e!=0||!new RegExp("^-?"+(t="["+N.slice(0,n)+"]+")+"(?:\\."+t+")?$",37>n?"i":"").test(s))return h(f,s,o,n);o?(f.s=0>1/e?(s=s.slice(1),-1):1,j&&s.replace(/^0\.0*|\./,"").length>15&&L(M,v,e),o=!1):f.s=45===s.charCodeAt(0)?(s=s.slice(1),-1):1,s=D(s,10,n,f.s)}else{if(e instanceof E)return f.s=e.s,f.e=e.e,f.c=(e=e.c)?e.slice():e,void(M=0);if((o="number"==typeof e)&&0*e==0){if(f.s=0>1/e?(e=-e,-1):1,e===~~e){for(r=0,i=e;i>=10;i/=10,r++);return f.e=r,f.c=[e],void(M=0)}s=e+""}else{if(!g.test(s=e+""))return h(f,s,o);f.s=45===s.charCodeAt(0)?(s=s.slice(1),-1):1}}for((r=s.indexOf("."))>-1&&(s=s.replace(".","")),(i=s.search(/e/i))>0?(0>r&&(r=i),r+=+s.slice(i+1),s=s.substring(0,i)):0>r&&(r=s.length),i=0;48===s.charCodeAt(i);i++);for(u=s.length;48===s.charCodeAt(--u););if(s=s.slice(i,u+1))if(u=s.length,o&&j&&u>15&&L(M,v,f.s*e),r=r-i-1,r>z)f.c=f.e=null;else if(G>r)f.c=[f.e=0];else{if(f.e=r,f.c=[],i=(r+1)%O,0>r&&(i+=O),u>i){for(i&&f.c.push(+s.slice(0,i)),u-=O;u>i;)f.c.push(+s.slice(i,i+=O));s=s.slice(i),i=O-s.length}else i-=u;for(;i--;s+="0");f.c.push(+s)}else f.c=[f.e=0];M=0}function D(e,n,t,i){var o,u,f,c,a,h,g,p=e.indexOf("."),d=P,m=k;for(37>t&&(e=e.toLowerCase()),p>=0&&(f=J,J=0,e=e.replace(".",""),g=new E(t),a=g.pow(e.length-p),J=f,g.c=s(l(r(a.c),a.e),10,n),g.e=g.c.length),h=s(e,t,n),u=f=h.length;0==h[--f];h.pop());if(!h[0])return"0";if(0>p?--u:(a.c=h,a.e=u,a.s=i,a=C(a,g,d,m,n),h=a.c,c=a.r,u=a.e),o=u+d+1,p=h[o],f=n/2,c=c||0>o||null!=h[o+1],c=4>m?(null!=p||c)&&(0==m||m==(a.s<0?3:2)):p>f||p==f&&(4==m||c||6==m&&1&h[o-1]||m==(a.s<0?8:7)),1>o||!h[0])e=c?l("1",-d):"0";else{if(h.length=o,c)for(--n;++h[--o]>n;)h[o]=0,o||(++u,h.unshift(1));for(f=h.length;!h[--f];);for(p=0,e="";f>=p;e+=N.charAt(h[p++]));e=l(e,u)}return e}function F(e,n,t,i){var o,u,s,c,a;if(t=null!=t&&H(t,0,8,i,w)?0|t:k,!e.c)return e.toString();if(o=e.c[0],s=e.e,null==n)a=r(e.c),a=19==i||24==i&&B>=s?f(a,s):l(a,s);else if(e=U(new E(e),n,t),u=e.e,a=r(e.c),c=a.length,19==i||24==i&&(u>=n||B>=u)){for(;n>c;a+="0",c++);a=f(a,u)}else if(n-=s,a=l(a,u),u+1>c){if(--n>0)for(a+=".";n--;a+="0");}else if(n+=u-c,n>0)for(u+1==c&&(a+=".");n--;a+="0");return e.s<0&&o?"-"+a:a}function _(e,n){var t,r,i=0;for(u(e[0])&&(e=e[0]),t=new E(e[0]);++i<e.length;){if(r=new E(e[i]),!r.s){t=r;break}n.call(t,r)&&(t=r)}return t}function x(e,n,t,r,i){return(n>e||e>t||e!=c(e))&&L(r,(i||"decimal places")+(n>e||e>t?" out of range":" not an integer"),e),!0}function I(e,n,t){for(var r=1,i=n.length;!n[--i];n.pop());for(i=n[0];i>=10;i/=10,r++);return(t=r+t*O-1)>z?e.c=e.e=null:G>t?e.c=[e.e=0]:(e.e=t,e.c=n),e}function L(e,n,t){var r=new Error(["new BigNumber","cmp","config","div","divToInt","eq","gt","gte","lt","lte","minus","mod","plus","precision","random","round","shift","times","toDigits","toExponential","toFixed","toFormat","toFraction","pow","toPrecision","toString","BigNumber"][e]+"() "+n+": "+t);throw r.name="BigNumber Error",M=0,r}function U(e,n,t,r){var i,o,u,s,f,l,c,a=e.c,h=S;if(a){e:{for(i=1,s=a[0];s>=10;s/=10,i++);if(o=n-i,0>o)o+=O,u=n,f=a[l=0],c=f/h[i-u-1]%10|0;else if(l=p((o+1)/O),l>=a.length){if(!r)break e;for(;a.length<=l;a.push(0));f=c=0,i=1,o%=O,u=o-O+1}else{for(f=s=a[l],i=1;s>=10;s/=10,i++);o%=O,u=o-O+i,c=0>u?0:f/h[i-u-1]%10|0}if(r=r||0>n||null!=a[l+1]||(0>u?f:f%h[i-u-1]),r=4>t?(c||r)&&(0==t||t==(e.s<0?3:2)):c>5||5==c&&(4==t||r||6==t&&(o>0?u>0?f/h[i-u]:0:a[l-1])%10&1||t==(e.s<0?8:7)),1>n||!a[0])return a.length=0,r?(n-=e.e+1,a[0]=h[(O-n%O)%O],e.e=-n||0):a[0]=e.e=0,e;if(0==o?(a.length=l,s=1,l--):(a.length=l+1,s=h[O-o],a[l]=u>0?d(f/h[i-u]%h[u])*s:0),r)for(;;){if(0==l){for(o=1,u=a[0];u>=10;u/=10,o++);for(u=a[0]+=s,s=1;u>=10;u/=10,s++);o!=s&&(e.e++,a[0]==b&&(a[0]=1));break}if(a[l]+=s,a[l]!=b)break;a[l--]=0,s=1}for(o=a.length;0===a[--o];a.pop());}e.e>z?e.c=e.e=null:e.e<G&&(e.c=[e.e=0])}return e}var C,M=0,T=E.prototype,q=new E(1),P=20,k=4,B=-7,$=21,G=-1e7,z=1e7,j=!0,H=x,V=!1,W=1,J=100,X={decimalSeparator:".",groupSeparator:",",groupSize:3,secondaryGroupSize:0,fractionGroupSeparator:" ",fractionGroupSize:0};return E.another=n,E.ROUND_UP=0,E.ROUND_DOWN=1,E.ROUND_CEIL=2,E.ROUND_FLOOR=3,E.ROUND_HALF_UP=4,E.ROUND_HALF_DOWN=5,E.ROUND_HALF_EVEN=6,E.ROUND_HALF_CEIL=7,E.ROUND_HALF_FLOOR=8,E.EUCLID=9,E.config=function(){var e,n,t=0,r={},i=arguments,s=i[0],f=s&&"object"==typeof s?function(){return s.hasOwnProperty(n)?null!=(e=s[n]):void 0}:function(){return i.length>t?null!=(e=i[t++]):void 0};return f(n="DECIMAL_PLACES")&&H(e,0,A,2,n)&&(P=0|e),r[n]=P,f(n="ROUNDING_MODE")&&H(e,0,8,2,n)&&(k=0|e),r[n]=k,f(n="EXPONENTIAL_AT")&&(u(e)?H(e[0],-A,0,2,n)&&H(e[1],0,A,2,n)&&(B=0|e[0],$=0|e[1]):H(e,-A,A,2,n)&&(B=-($=0|(0>e?-e:e)))),r[n]=[B,$],f(n="RANGE")&&(u(e)?H(e[0],-A,-1,2,n)&&H(e[1],1,A,2,n)&&(G=0|e[0],z=0|e[1]):H(e,-A,A,2,n)&&(0|e?G=-(z=0|(0>e?-e:e)):j&&L(2,n+" cannot be zero",e))),r[n]=[G,z],f(n="ERRORS")&&(e===!!e||1===e||0===e?(M=0,H=(j=!!e)?x:o):j&&L(2,n+m,e)),r[n]=j,f(n="CRYPTO")&&(e===!!e||1===e||0===e?(V=!(!e||!a),e&&!V&&j&&L(2,"crypto unavailable",a)):j&&L(2,n+m,e)),r[n]=V,f(n="MODULO_MODE")&&H(e,0,9,2,n)&&(W=0|e),r[n]=W,f(n="POW_PRECISION")&&H(e,0,A,2,n)&&(J=0|e),r[n]=J,f(n="FORMAT")&&("object"==typeof e?X=e:j&&L(2,n+" not an object",e)),r[n]=X,r},E.max=function(){return _(arguments,T.lt)},E.min=function(){return _(arguments,T.gt)},E.random=function(){var e=9007199254740992,n=Math.random()*e&2097151?function(){return d(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var t,r,i,o,u,s=0,f=[],l=new E(q);if(e=null!=e&&H(e,0,A,14)?0|e:P,o=p(e/O),V)if(a&&a.getRandomValues){for(t=a.getRandomValues(new Uint32Array(o*=2));o>s;)u=131072*t[s]+(t[s+1]>>>11),u>=9e15?(r=a.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(f.push(u%1e14),s+=2);s=o/2}else if(a&&a.randomBytes){for(t=a.randomBytes(o*=7);o>s;)u=281474976710656*(31&t[s])+1099511627776*t[s+1]+4294967296*t[s+2]+16777216*t[s+3]+(t[s+4]<<16)+(t[s+5]<<8)+t[s+6],u>=9e15?a.randomBytes(7).copy(t,s):(f.push(u%1e14),s+=7);s=o/7}else j&&L(14,"crypto unavailable",a);if(!s)for(;o>s;)u=n(),9e15>u&&(f[s++]=u%1e14);for(o=f[--s],e%=O,o&&e&&(u=S[O-e],f[s]=d(o/u)*u);0===f[s];f.pop(),s--);if(0>s)f=[i=0];else{for(i=-1;0===f[0];f.shift(),i-=O);for(s=1,u=f[0];u>=10;u/=10,s++);O>s&&(i-=O-s)}return l.e=i,l.c=f,l}}(),C=function(){function e(e,n,t){var r,i,o,u,s=0,f=e.length,l=n%R,c=n/R|0;for(e=e.slice();f--;)o=e[f]%R,u=e[f]/R|0,r=c*o+u*l,i=l*o+r%R*R+s,s=(i/t|0)+(r/R|0)+c*u,e[f]=i%t;return s&&e.unshift(s),e}function n(e,n,t,r){var i,o;if(t!=r)o=t>r?1:-1;else for(i=o=0;t>i;i++)if(e[i]!=n[i]){o=e[i]>n[i]?1:-1;break}return o}function r(e,n,t,r){for(var i=0;t--;)e[t]-=i,i=e[t]<n[t]?1:0,e[t]=i*r+e[t]-n[t];for(;!e[0]&&e.length>1;e.shift());}return function(i,o,u,s,f){var l,c,a,h,g,p,m,w,v,N,y,S,R,A,D,F,_,x=i.s==o.s?1:-1,I=i.c,L=o.c;if(!(I&&I[0]&&L&&L[0]))return new E(i.s&&o.s&&(I?!L||I[0]!=L[0]:L)?I&&0==I[0]||!L?0*x:x/0:NaN);for(w=new E(x),v=w.c=[],c=i.e-o.e,x=u+c+1,f||(f=b,c=t(i.e/O)-t(o.e/O),x=x/O|0),a=0;L[a]==(I[a]||0);a++);if(L[a]>(I[a]||0)&&c--,0>x)v.push(1),h=!0;else{for(A=I.length,F=L.length,a=0,x+=2,g=d(f/(L[0]+1)),g>1&&(L=e(L,g,f),I=e(I,g,f),F=L.length,A=I.length),R=F,N=I.slice(0,F),y=N.length;F>y;N[y++]=0);_=L.slice(),_.unshift(0),D=L[0],L[1]>=f/2&&D++;do{if(g=0,l=n(L,N,F,y),0>l){if(S=N[0],F!=y&&(S=S*f+(N[1]||0)),g=d(S/D),g>1)for(g>=f&&(g=f-1),p=e(L,g,f),m=p.length,y=N.length;1==n(p,N,m,y);)g--,r(p,m>F?_:L,m,f),m=p.length,l=1;else 0==g&&(l=g=1),p=L.slice(),m=p.length;if(y>m&&p.unshift(0),r(N,p,y,f),y=N.length,-1==l)for(;n(L,N,F,y)<1;)g++,r(N,y>F?_:L,y,f),y=N.length}else 0===l&&(g++,N=[0]);v[a++]=g,N[0]?N[y++]=I[R]||0:(N=[I[R]],y=1)}while((R++<A||null!=N[0])&&x--);h=null!=N[0],v[0]||v.shift()}if(f==b){for(a=1,x=v[0];x>=10;x/=10,a++);U(w,u+(w.e=a+c*O-1)+1,s,h)}else w.e=c,w.r=+h;return w}}(),h=function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,n=/^([^.]+)\.$/,t=/^\.([^.]+)$/,r=/^-?(Infinity|NaN)$/,i=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,u,s,f){var l,c=s?u:u.replace(i,"");if(r.test(c))o.s=isNaN(c)?null:0>c?-1:1;else{if(!s&&(c=c.replace(e,function(e,n,t){return l="x"==(t=t.toLowerCase())?16:"b"==t?2:8,f&&f!=l?e:n}),f&&(l=f,c=c.replace(n,"$1").replace(t,"0.$1")),u!=c))return new E(c,l);j&&L(M,"not a"+(f?" base "+f:"")+" number",u),o.s=null}o.c=o.e=null,M=0}}(),T.absoluteValue=T.abs=function(){var e=new E(this);return e.s<0&&(e.s=1),e},T.ceil=function(){return U(new E(this),this.e+1,2)},T.comparedTo=T.cmp=function(e,n){return M=1,i(this,new E(e,n))},T.decimalPlaces=T.dp=function(){var e,n,r=this.c;if(!r)return null;if(e=((n=r.length-1)-t(this.e/O))*O,n=r[n])for(;n%10==0;n/=10,e--);return 0>e&&(e=0),e},T.dividedBy=T.div=function(e,n){return M=3,C(this,new E(e,n),P,k)},T.dividedToIntegerBy=T.divToInt=function(e,n){return M=4,C(this,new E(e,n),0,1)},T.equals=T.eq=function(e,n){return M=5,0===i(this,new E(e,n))},T.floor=function(){return U(new E(this),this.e+1,3)},T.greaterThan=T.gt=function(e,n){return M=6,i(this,new E(e,n))>0},T.greaterThanOrEqualTo=T.gte=function(e,n){return M=7,1===(n=i(this,new E(e,n)))||0===n},T.isFinite=function(){return!!this.c},T.isInteger=T.isInt=function(){return!!this.c&&t(this.e/O)>this.c.length-2},T.isNaN=function(){return!this.s},T.isNegative=T.isNeg=function(){return this.s<0},T.isZero=function(){return!!this.c&&0==this.c[0]},T.lessThan=T.lt=function(e,n){return M=8,i(this,new E(e,n))<0},T.lessThanOrEqualTo=T.lte=function(e,n){return M=9,-1===(n=i(this,new E(e,n)))||0===n},T.minus=T.sub=function(e,n){var r,i,o,u,s=this,f=s.s;if(M=10,e=new E(e,n),n=e.s,!f||!n)return new E(NaN);if(f!=n)return e.s=-n,s.plus(e);var l=s.e/O,c=e.e/O,a=s.c,h=e.c;if(!l||!c){if(!a||!h)return a?(e.s=-n,e):new E(h?s:NaN);if(!a[0]||!h[0])return h[0]?(e.s=-n,e):new E(a[0]?s:3==k?-0:0)}if(l=t(l),c=t(c),a=a.slice(),f=l-c){for((u=0>f)?(f=-f,o=a):(c=l,o=h),o.reverse(),n=f;n--;o.push(0));o.reverse()}else for(i=(u=(f=a.length)<(n=h.length))?f:n,f=n=0;i>n;n++)if(a[n]!=h[n]){u=a[n]<h[n];break}if(u&&(o=a,a=h,h=o,e.s=-e.s),n=(i=h.length)-(r=a.length),n>0)for(;n--;a[r++]=0);for(n=b-1;i>f;){if(a[--i]<h[i]){for(r=i;r&&!a[--r];a[r]=n);--a[r],a[i]+=b}a[i]-=h[i]}for(;0==a[0];a.shift(),--c);return a[0]?I(e,a,c):(e.s=3==k?-1:1,e.c=[e.e=0],e)},T.modulo=T.mod=function(e,n){var t,r,i=this;return M=11,e=new E(e,n),!i.c||!e.s||e.c&&!e.c[0]?new E(NaN):!e.c||i.c&&!i.c[0]?new E(i):(9==W?(r=e.s,e.s=1,t=C(i,e,0,3),e.s=r,t.s*=r):t=C(i,e,0,W),i.minus(t.times(e)))},T.negated=T.neg=function(){var e=new E(this);return e.s=-e.s||null,e},T.plus=T.add=function(e,n){var r,i=this,o=i.s;if(M=12,e=new E(e,n),n=e.s,!o||!n)return new E(NaN);if(o!=n)return e.s=-n,i.minus(e);var u=i.e/O,s=e.e/O,f=i.c,l=e.c;if(!u||!s){if(!f||!l)return new E(o/0);if(!f[0]||!l[0])return l[0]?e:new E(f[0]?i:0*o)}if(u=t(u),s=t(s),f=f.slice(),o=u-s){for(o>0?(s=u,r=l):(o=-o,r=f),r.reverse();o--;r.push(0));r.reverse()}for(o=f.length,n=l.length,0>o-n&&(r=l,l=f,f=r,n=o),o=0;n;)o=(f[--n]=f[n]+l[n]+o)/b|0,f[n]%=b;return o&&(f.unshift(o),++s),I(e,f,s)},T.precision=T.sd=function(e){var n,t,r=this,i=r.c;if(null!=e&&e!==!!e&&1!==e&&0!==e&&(j&&L(13,"argument"+m,e),e!=!!e&&(e=null)),!i)return null;if(t=i.length-1,n=t*O+1,t=i[t]){for(;t%10==0;t/=10,n--);for(t=i[0];t>=10;t/=10,n++);}return e&&r.e+1>n&&(n=r.e+1),n},T.round=function(e,n){var t=new E(this);return(null==e||H(e,0,A,15))&&U(t,~~e+this.e+1,null!=n&&H(n,0,8,15,w)?0|n:k),t},T.shift=function(e){var n=this;return H(e,-y,y,16,"argument")?n.times("1e"+c(e)):new E(n.c&&n.c[0]&&(-y>e||e>y)?n.s*(0>e?0:1/0):n)},T.squareRoot=T.sqrt=function(){var e,n,i,o,u,s=this,f=s.c,l=s.s,c=s.e,a=P+4,h=new E("0.5");if(1!==l||!f||!f[0])return new E(!l||0>l&&(!f||f[0])?NaN:f?s:1/0);if(l=Math.sqrt(+s),0==l||l==1/0?(n=r(f),(n.length+c)%2==0&&(n+="0"),l=Math.sqrt(n),c=t((c+1)/2)-(0>c||c%2),l==1/0?n="1e"+c:(n=l.toExponential(),n=n.slice(0,n.indexOf("e")+1)+c),i=new E(n)):i=new E(l+""),i.c[0])for(c=i.e,l=c+a,3>l&&(l=0);;)if(u=i,i=h.times(u.plus(C(s,u,a,1))),r(u.c).slice(0,l)===(n=r(i.c)).slice(0,l)){if(i.e<c&&--l,n=n.slice(l-3,l+1),"9999"!=n&&(o||"4999"!=n)){(!+n||!+n.slice(1)&&"5"==n.charAt(0))&&(U(i,i.e+P+2,1),e=!i.times(i).eq(s));break}if(!o&&(U(u,u.e+P+2,0),u.times(u).eq(s))){i=u;break}a+=4,l+=4,o=1}return U(i,i.e+P+1,k,e)},T.times=T.mul=function(e,n){var r,i,o,u,s,f,l,c,a,h,g,p,d,m,w,v=this,N=v.c,y=(M=17,e=new E(e,n)).c;if(!(N&&y&&N[0]&&y[0]))return!v.s||!e.s||N&&!N[0]&&!y||y&&!y[0]&&!N?e.c=e.e=e.s=null:(e.s*=v.s,N&&y?(e.c=[0],e.e=0):e.c=e.e=null),e;for(i=t(v.e/O)+t(e.e/O),e.s*=v.s,l=N.length,h=y.length,h>l&&(d=N,N=y,y=d,o=l,l=h,h=o),o=l+h,d=[];o--;d.push(0));for(m=b,w=R,o=h;--o>=0;){for(r=0,g=y[o]%w,p=y[o]/w|0,s=l,u=o+s;u>o;)c=N[--s]%w,a=N[s]/w|0,f=p*c+a*g,c=g*c+f%w*w+d[u]+r,r=(c/m|0)+(f/w|0)+p*a,d[u--]=c%m;d[u]=r}return r?++i:d.shift(),I(e,d,i)},T.toDigits=function(e,n){var t=new E(this);return e=null!=e&&H(e,1,A,18,"precision")?0|e:null,n=null!=n&&H(n,0,8,18,w)?0|n:k,e?U(t,e,n):t},T.toExponential=function(e,n){return F(this,null!=e&&H(e,0,A,19)?~~e+1:null,n,19)},T.toFixed=function(e,n){return F(this,null!=e&&H(e,0,A,20)?~~e+this.e+1:null,n,20)},T.toFormat=function(e,n){var t=F(this,null!=e&&H(e,0,A,21)?~~e+this.e+1:null,n,21);if(this.c){var r,i=t.split("."),o=+X.groupSize,u=+X.secondaryGroupSize,s=X.groupSeparator,f=i[0],l=i[1],c=this.s<0,a=c?f.slice(1):f,h=a.length;if(u&&(r=o,o=u,u=r,h-=r),o>0&&h>0){for(r=h%o||o,f=a.substr(0,r);h>r;r+=o)f+=s+a.substr(r,o);u>0&&(f+=s+a.slice(r)),c&&(f="-"+f)}t=l?f+X.decimalSeparator+((u=+X.fractionGroupSize)?l.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+X.fractionGroupSeparator):l):f}return t},T.toFraction=function(e){var n,t,i,o,u,s,f,l,c,a=j,h=this,g=h.c,p=new E(q),d=t=new E(q),m=f=new E(q);if(null!=e&&(j=!1,s=new E(e),j=a,(!(a=s.isInt())||s.lt(q))&&(j&&L(22,"max denominator "+(a?"out of range":"not an integer"),e),e=!a&&s.c&&U(s,s.e+1,1).gte(q)?s:null)),!g)return h.toString();for(c=r(g),o=p.e=c.length-h.e-1,p.c[0]=S[(u=o%O)<0?O+u:u],e=!e||s.cmp(p)>0?o>0?p:d:s,u=z,z=1/0,s=new E(c),f.c[0]=0;l=C(s,p,0,1),i=t.plus(l.times(m)),1!=i.cmp(e);)t=m,m=i,d=f.plus(l.times(i=d)),f=i,p=s.minus(l.times(i=p)),s=i;return i=C(e.minus(t),m,0,1),f=f.plus(i.times(d)),t=t.plus(i.times(m)),f.s=d.s=h.s,o*=2,n=C(d,m,o,k).minus(h).abs().cmp(C(f,t,o,k).minus(h).abs())<1?[d.toString(),m.toString()]:[f.toString(),t.toString()],z=u,n},T.toNumber=function(){return+this},T.toPower=T.pow=function(e){var n,t,r=d(0>e?-e:+e),i=this;if(!H(e,-y,y,23,"exponent")&&(!isFinite(e)||r>y&&(e/=0)||parseFloat(e)!=e&&!(e=NaN)))return new E(Math.pow(+i,e));for(n=J?p(J/O+2):0,t=new E(q);;){if(r%2){if(t=t.times(i),!t.c)break;n&&t.c.length>n&&(t.c.length=n)}if(r=d(r/2),!r)break;i=i.times(i),n&&i.c&&i.c.length>n&&(i.c.length=n)}return 0>e&&(t=q.div(t)),n?U(t,J,k):t},T.toPrecision=function(e,n){return F(this,null!=e&&H(e,1,A,24,"precision")?0|e:null,n,24)},T.toString=function(e){var n,t=this,i=t.s,o=t.e;return null===o?i?(n="Infinity",0>i&&(n="-"+n)):n="NaN":(n=r(t.c),n=null!=e&&H(e,2,64,25,"base")?D(l(n,o),0|e,10,i):B>=o||o>=$?f(n,o):l(n,o),0>i&&t.c[0]&&(n="-"+n)),n},T.truncated=T.trunc=function(){return U(new E(this),this.e+1,1)},T.valueOf=T.toJSON=function(){var e,n=this,t=n.e;return null===t?n.toString():(e=r(n.c),e=B>=t||t>=$?f(e,t):l(e,t),n.s<0?"-"+e:e)},null!=e&&E.config(e),E}function t(e){var n=0|e;return e>0||e===n?n:n-1}function r(e){for(var n,t,r=1,i=e.length,o=e[0]+"";i>r;){for(n=e[r++]+"",t=O-n.length;t--;n="0"+n);o+=n}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function i(e,n){var t,r,i=e.c,o=n.c,u=e.s,s=n.s,f=e.e,l=n.e;if(!u||!s)return null;if(t=i&&!i[0],r=o&&!o[0],t||r)return t?r?0:-s:u;if(u!=s)return u;if(t=0>u,r=f==l,!i||!o)return r?0:!i^t?1:-1;if(!r)return f>l^t?1:-1;for(s=(f=i.length)<(l=o.length)?f:l,u=0;s>u;u++)if(i[u]!=o[u])return i[u]>o[u]^t?1:-1;return f==l?0:f>l^t?1:-1}function o(e,n,t){return(e=c(e))>=n&&t>=e}function u(e){return"[object Array]"==Object.prototype.toString.call(e)}function s(e,n,t){for(var r,i,o=[0],u=0,s=e.length;s>u;){for(i=o.length;i--;o[i]*=n);for(o[r=0]+=N.indexOf(e.charAt(u++));r<o.length;r++)o[r]>t-1&&(null==o[r+1]&&(o[r+1]=0),o[r+1]+=o[r]/t|0,o[r]%=t)}return o.reverse()}function f(e,n){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(0>n?"e":"e+")+n}function l(e,n){var t,r;if(0>n){for(r="0.";++n;r+="0");e=r+e}else if(t=e.length,++n>t){for(r="0",n-=t;--n;r+="0");e+=r}else t>n&&(e=e.slice(0,n)+"."+e.slice(n));return e}function c(e){return e=parseFloat(e),0>e?p(e):d(e)}var a,h,g=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,p=Math.ceil,d=Math.floor,m=" not a boolean or binary digit",w="rounding mode",v="number type has more than 15 significant digits",N="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",b=1e14,O=14,y=9007199254740991,S=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],R=1e7,A=1e9;if("undefined"!=typeof crypto&&(a=crypto),"function"==typeof define&&define.amd)define(function(){return n()});else if("undefined"!=typeof module&&module.exports){if(module.exports=n(),!a)try{a=require("crypto")}catch(E){}}else e||(e="undefined"!=typeof self?self:Function("return this")()),e.BigNumber=n()}(this);
/* eslint-enable */
}
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/quickjs/io.rb | stdlib/quickjs/io.rb | # backtick_javascript: true
%x{
Opal.gvars.stdout.write_proc = function(s) {
std.out.printf("%s", s);
std.out.flush();
}
Opal.gvars.stderr.write_proc = function(s) {
std.err.printf("%s", s);
std.err.flush();
}
Opal.gvars.stdin.read_proc = function(s) {
if (std.in.eof()) {
return nil;
}
else {
return std.in.readAsString(s);
}
}
}
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/quickjs/file.rb | stdlib/quickjs/file.rb | class File
def self.read(path)
%x{
const body = std.loadFile(path);
if (body === null) {
throw new Error(`Unable to read "${path}"`);
}
return body;
}
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/quickjs/kernel.rb | stdlib/quickjs/kernel.rb | # backtick_javascript: true
ARGV = `scriptArgs`
`Opal.exit = std.exit`
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/gjs/io.rb | stdlib/gjs/io.rb | # backtick_javascript: true
`/* global imports */`
# Basic version, appends \n:
# $stdout.write_proc = `function(s){print(s)}`
# $stderr.write_proc = `function(s){printerr(s)}`
# Advanced version:
%x{
var GLib = imports.gi.GLib;
var ByteArray = imports.byteArray;
var stdin = GLib.IOChannel.unix_new(0);
var stdout = GLib.IOChannel.unix_new(1);
var stderr = GLib.IOChannel.unix_new(2);
Opal.gvars.stdout.write_proc = function(s) {
var buf = ByteArray.fromString(s);
stdout.write_chars(buf, buf.length);
stdout.flush();
}
Opal.gvars.stderr.write_proc = function(s) {
var buf = ByteArray.fromString(s);
stderr.write_chars(buf, buf.length);
stderr.flush();
}
Opal.gvars.stdin.read_proc = function(_s) {
var out = stdin.read_line();
if (out[0] == GLib.IOStatus.EOF) return nil;
return out[1].toString();
}
}
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/gjs/kernel.rb | stdlib/gjs/kernel.rb | # backtick_javascript: true
`/* global ARGV */`
ARGV = `ARGV`
`Opal.exit = imports.system.exit`
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/bun/file.rb | stdlib/bun/file.rb | require 'nodejs/file'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/bun/base.rb | stdlib/bun/base.rb | `/* global Bun */`
module Bun
VERSION = `Bun.version`
end
`Opal.exit = process.exit`
ARGV = `process.argv.slice(2)`
ARGV.shift if ARGV.first == '--'
$stdout.write_proc = ->(string) { `process.stdout.write(string)` }
$stderr.write_proc = ->(string) { `process.stderr.write(string)` }
`var __fs__ = require('fs')`
$stdin.read_proc = %x{function(_count) {
// Ignore count, return as much as we can get
var buf = Buffer.alloc(65536), count;
try {
count = __fs__.readSync(this.fd, buf, 0, 65536, null);
}
catch (e) { // Windows systems may raise EOF
return nil;
}
if (count == 0) return nil;
return buf.toString('utf8', 0, count);
}}
$stdin.tty = true
$stdout.tty = true
$stderr.tty = true
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/racc/parser.rb | stdlib/racc/parser.rb | # Opal port of racc/parser.rb.
#
# Original license:
#
# frozen_string_literal: false
#--
# $originalId: parser.rb,v 1.8 2006/07/06 11:42:07 aamine Exp $
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
#
# As a special exception, when this code is copied by Racc
# into a Racc output file, you may use that output file
# without restriction.
#++
module Racc
class ParseError < StandardError; end
end
unless defined?(::ParseError)
ParseError = Racc::ParseError
end
# Racc is a LALR(1) parser generator.
# It is written in Ruby itself, and generates Ruby programs.
#
# == Command-line Reference
#
# racc [-o<var>filename</var>] [--output-file=<var>filename</var>]
# [-e<var>rubypath</var>] [--embedded=<var>rubypath</var>]
# [-v] [--verbose]
# [-O<var>filename</var>] [--log-file=<var>filename</var>]
# [-g] [--debug]
# [-E] [--embedded]
# [-l] [--no-line-convert]
# [-c] [--line-convert-all]
# [-a] [--no-omit-actions]
# [-C] [--check-only]
# [-S] [--output-status]
# [--version] [--copyright] [--help] <var>grammarfile</var>
#
# [+filename+]
# Racc grammar file. Any extension is permitted.
# [-o+outfile+, --output-file=+outfile+]
# A filename for output. default is <+filename+>.tab.rb
# [-O+filename+, --log-file=+filename+]
# Place logging output in file +filename+.
# Default log file name is <+filename+>.output.
# [-e+rubypath+, --executable=+rubypath+]
# output executable file(mode 755). where +path+ is the Ruby interpreter.
# [-v, --verbose]
# verbose mode. create +filename+.output file, like yacc's y.output file.
# [-g, --debug]
# add debug code to parser class. To display debugging information,
# use this '-g' option and set @yydebug true in parser class.
# [-E, --embedded]
# Output parser which doesn't need runtime files (racc/parser.rb).
# [-C, --check-only]
# Check syntax of racc grammar file and quit.
# [-S, --output-status]
# Print messages time to time while compiling.
# [-l, --no-line-convert]
# turns off line number converting.
# [-c, --line-convert-all]
# Convert line number of actions, inner, header and footer.
# [-a, --no-omit-actions]
# Call all actions, even if an action is empty.
# [--version]
# print Racc version and quit.
# [--copyright]
# Print copyright and quit.
# [--help]
# Print usage and quit.
#
# == Generating Parser Using Racc
#
# To compile Racc grammar file, simply type:
#
# $ racc parse.y
#
# This creates Ruby script file "parse.tab.y". The -o option can change the output filename.
#
# == Writing A Racc Grammar File
#
# If you want your own parser, you have to write a grammar file.
# A grammar file contains the name of your parser class, grammar for the parser,
# user code, and anything else.
# When writing a grammar file, yacc's knowledge is helpful.
# If you have not used yacc before, Racc is not too difficult.
#
# Here's an example Racc grammar file.
#
# class Calcparser
# rule
# target: exp { print val[0] }
#
# exp: exp '+' exp
# | exp '*' exp
# | '(' exp ')'
# | NUMBER
# end
#
# Racc grammar files resemble yacc files.
# But (of course), this is Ruby code.
# yacc's $$ is the 'result', $0, $1... is
# an array called 'val', and $-1, $-2... is an array called '_values'.
#
# See the {Grammar File Reference}[rdoc-ref:lib/racc/rdoc/grammar.en.rdoc] for
# more information on grammar files.
#
# == Parser
#
# Then you must prepare the parse entry method. There are two types of
# parse methods in Racc, Racc::Parser#do_parse and Racc::Parser#yyparse
#
# Racc::Parser#do_parse is simple.
#
# It's yyparse() of yacc, and Racc::Parser#next_token is yylex().
# This method must returns an array like [TOKENSYMBOL, ITS_VALUE].
# EOF is [false, false].
# (TOKENSYMBOL is a Ruby symbol (taken from String#intern) by default.
# If you want to change this, see the grammar reference.
#
# Racc::Parser#yyparse is little complicated, but useful.
# It does not use Racc::Parser#next_token, instead it gets tokens from any iterator.
#
# For example, <code>yyparse(obj, :scan)</code> causes
# calling +obj#scan+, and you can return tokens by yielding them from +obj#scan+.
#
# == Debugging
#
# When debugging, "-v" or/and the "-g" option is helpful.
#
# "-v" creates verbose log file (.output).
# "-g" creates a "Verbose Parser".
# Verbose Parser prints the internal status when parsing.
# But it's _not_ automatic.
# You must use -g option and set +@yydebug+ to +true+ in order to get output.
# -g option only creates the verbose parser.
#
# === Racc reported syntax error.
#
# Isn't there too many "end"?
# grammar of racc file is changed in v0.10.
#
# Racc does not use '%' mark, while yacc uses huge number of '%' marks..
#
# === Racc reported "XXXX conflicts".
#
# Try "racc -v xxxx.y".
# It causes producing racc's internal log file, xxxx.output.
#
# === Generated parsers does not work correctly
#
# Try "racc -g xxxx.y".
# This command let racc generate "debugging parser".
# Then set @yydebug=true in your parser.
# It produces a working log of your parser.
#
# == Re-distributing Racc runtime
#
# A parser, which is created by Racc, requires the Racc runtime module;
# racc/parser.rb.
#
# Ruby 1.8.x comes with Racc runtime module,
# you need NOT distribute Racc runtime files.
#
# If you want to include the Racc runtime module with your parser.
# This can be done by using '-E' option:
#
# $ racc -E -omyparser.rb myparser.y
#
# This command creates myparser.rb which `includes' Racc runtime.
# Only you must do is to distribute your parser file (myparser.rb).
#
# Note: parser.rb is LGPL, but your parser is not.
# Your own parser is completely yours.
module Racc
unless defined?(Racc_No_Extensions)
Racc_No_Extensions = false # :nodoc:
end
class Parser
Racc_Runtime_Version = '1.4.6'
Racc_Runtime_Revision = %w$originalRevision: 1.8 $[1]
Racc_Runtime_Core_Version_R = '1.4.6'
Racc_Runtime_Core_Revision_R = %w$originalRevision: 1.8 $[1]
# DISABLED: opal has no racc/cparse
# begin
# require 'racc/cparse'
# # Racc_Runtime_Core_Version_C = (defined in extension)
# Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2]
# unless new.respond_to?(:_racc_do_parse_c, true)
# raise LoadError, 'old cparse.so'
# end
# if Racc_No_Extensions
# raise LoadError, 'selecting ruby version of racc runtime core'
# end
#
# Racc_Main_Parsing_Routine = :_racc_do_parse_c # :nodoc:
# Racc_YY_Parse_Method = :_racc_yyparse_c # :nodoc:
# Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C # :nodoc:
# Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C # :nodoc:
# Racc_Runtime_Type = 'c' # :nodoc:
# rescue LoadError
Racc_Main_Parsing_Routine = :_racc_do_parse_rb
Racc_YY_Parse_Method = :_racc_yyparse_rb
Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
Racc_Runtime_Type = 'ruby'
# end
def Parser.racc_runtime_type # :nodoc:
Racc_Runtime_Type
end
def _racc_setup
@yydebug = false unless self.class::Racc_debug_parser
@yydebug = false unless defined?(@yydebug)
if @yydebug
@racc_debug_out = $stderr unless defined?(@racc_debug_out)
@racc_debug_out ||= $stderr
end
arg = self.class::Racc_arg
arg[13] = true if arg.size < 14
arg
end
def _racc_init_sysvars
@racc_state = [0]
@racc_tstack = []
@racc_vstack = []
@racc_t = nil
@racc_val = nil
@racc_read_next = true
@racc_user_yyerror = false
@racc_error_status = 0
end
# The entry point of the parser. This method is used with #next_token.
# If Racc wants to get token (and its value), calls next_token.
#
# Example:
# def parse
# @q = [[1,1],
# [2,2],
# [3,3],
# [false, '$']]
# do_parse
# end
#
# def next_token
# @q.shift
# end
def do_parse
__send__(Racc_Main_Parsing_Routine, _racc_setup(), false)
end
# The method to fetch next token.
# If you use #do_parse method, you must implement #next_token.
#
# The format of return value is [TOKEN_SYMBOL, VALUE].
# +token-symbol+ is represented by Ruby's symbol by default, e.g. :IDENT
# for 'IDENT'. ";" (String) for ';'.
#
# The final symbol (End of file) must be false.
def next_token
raise NotImplementedError, "#{self.class}\#next_token is not defined"
end
def _racc_do_parse_rb(arg, in_debug)
action_table, action_check, action_default, action_pointer,
_, _, _, _,
_, _, token_table, _,
_, _, * = arg
_racc_init_sysvars
tok = act = i = nil
catch(:racc_end_parse) {
while true
if i = action_pointer[@racc_state[-1]]
if @racc_read_next
if @racc_t != 0 # not EOF
tok, @racc_val = next_token()
unless tok # EOF
@racc_t = 0
else
@racc_t = (token_table[tok] or 1) # error token
end
racc_read_token(@racc_t, tok, @racc_val) if @yydebug
@racc_read_next = false
end
end
i += @racc_t
unless i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
else
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
end
}
end
# Another entry point for the parser.
# If you use this method, you must implement RECEIVER#METHOD_ID method.
#
# RECEIVER#METHOD_ID is a method to get next token.
# It must 'yield' the token, which format is [TOKEN-SYMBOL, VALUE].
def yyparse(recv, mid)
__send__(Racc_YY_Parse_Method, recv, mid, _racc_setup(), true)
end
def _racc_yyparse_rb(recv, mid, arg, c_debug)
action_table, action_check, action_default, action_pointer,
_, _, _, _,
_, _, token_table, _,
_, _, * = arg
_racc_init_sysvars
act = nil
i = nil
catch(:racc_end_parse) {
until i = action_pointer[@racc_state[-1]]
while act = _racc_evalact(action_default[@racc_state[-1]], arg)
;
end
end
recv.__send__(mid) do |tok, val|
unless tok
@racc_t = 0
else
@racc_t = (token_table[tok] or 1) # error token
end
@racc_val = val
@racc_read_next = false
i += @racc_t
unless i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
while not(i = action_pointer[@racc_state[-1]]) or
not @racc_read_next or
@racc_t == 0 # $
unless i and i += @racc_t and
i >= 0 and
act = action_table[i] and
action_check[i] == @racc_state[-1]
act = action_default[@racc_state[-1]]
end
while act = _racc_evalact(act, arg)
;
end
end
end
}
end
###
### common
###
def _racc_evalact(act, arg)
action_table, action_check, _, action_pointer,
_, _, _, _,
_, _, _, shift_n, reduce_n,
_, _, * = arg
if act > 0 and act < shift_n
#
# shift
#
if @racc_error_status > 0
@racc_error_status -= 1 unless @racc_t == 1 # error token
end
@racc_vstack.push @racc_val
@racc_state.push act
@racc_read_next = true
if @yydebug
@racc_tstack.push @racc_t
racc_shift @racc_t, @racc_tstack, @racc_vstack
end
elsif act < 0 and act > -reduce_n
#
# reduce
#
code = catch(:racc_jump) {
@racc_state.push _racc_do_reduce(arg, act)
false
}
if code
case code
when 1 # yyerror
@racc_user_yyerror = true # user_yyerror
return -reduce_n
when 2 # yyaccept
return shift_n
else
raise '[Racc Bug] unknown jump code'
end
end
elsif act == shift_n
#
# accept
#
racc_accept if @yydebug
throw :racc_end_parse, @racc_vstack[0]
elsif act == -reduce_n
#
# error
#
case @racc_error_status
when 0
unless arg[21] # user_yyerror
on_error @racc_t, @racc_val, @racc_vstack
end
when 3
if @racc_t == 0 # is $
throw :racc_end_parse, nil
end
@racc_read_next = true
end
@racc_user_yyerror = false
@racc_error_status = 3
while true
if i = action_pointer[@racc_state[-1]]
i += 1 # error token
if i >= 0 and
(act = action_table[i]) and
action_check[i] == @racc_state[-1]
break
end
end
throw :racc_end_parse, nil if @racc_state.size <= 1
@racc_state.pop
@racc_vstack.pop
if @yydebug
@racc_tstack.pop
racc_e_pop @racc_state, @racc_tstack, @racc_vstack
end
end
return act
else
raise "[Racc Bug] unknown action #{act.inspect}"
end
racc_next_state(@racc_state[-1], @racc_state) if @yydebug
nil
end
def _racc_do_reduce(arg, act)
_, _, _, _,
goto_table, goto_check, goto_default, goto_pointer,
nt_base, reduce_table, _, _,
_, use_result, * = arg
state = @racc_state
vstack = @racc_vstack
tstack = @racc_tstack
i = act * -3
len = reduce_table[i]
reduce_to = reduce_table[i+1]
method_id = reduce_table[i+2]
void_array = []
tmp_t = tstack[-len, len] if @yydebug
tmp_v = vstack[-len, len]
tstack[-len, len] = void_array if @yydebug
vstack[-len, len] = void_array
state[-len, len] = void_array
# tstack must be updated AFTER method call
if use_result
vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
else
vstack.push __send__(method_id, tmp_v, vstack)
end
tstack.push reduce_to
racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
k1 = reduce_to - nt_base
if i = goto_pointer[k1]
i += state[-1]
if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
return curstate
end
end
goto_default[k1]
end
# This method is called when a parse error is found.
#
# ERROR_TOKEN_ID is an internal ID of token which caused error.
# You can get string representation of this ID by calling
# #token_to_str.
#
# ERROR_VALUE is a value of error token.
#
# value_stack is a stack of symbol values.
# DO NOT MODIFY this object.
#
# This method raises ParseError by default.
#
# If this method returns, parsers enter "error recovering mode".
def on_error(t, val, vstack)
raise ParseError, sprintf("\nparse error on value %s (%s)",
val.inspect, token_to_str(t) || '?')
end
# Enter error recovering mode.
# This method does not call #on_error.
def yyerror
throw :racc_jump, 1
end
# Exit parser.
# Return value is Symbol_Value_Stack[0].
def yyaccept
throw :racc_jump, 2
end
# Leave error recovering mode.
def yyerrok
@racc_error_status = 0
end
# For debugging output
def racc_read_token(t, tok, val)
@racc_debug_out.print 'read '
@racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
@racc_debug_out.puts val.inspect
@racc_debug_out.puts
end
def racc_shift(tok, tstack, vstack)
@racc_debug_out.puts "shift #{racc_token2str tok}"
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_reduce(toks, sim, tstack, vstack)
out = @racc_debug_out
out.print 'reduce '
if toks.empty?
out.print ' <none>'
else
toks.each {|t| out.print ' ', racc_token2str(t) }
end
out.puts " --> #{racc_token2str(sim)}"
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_accept
@racc_debug_out.puts 'accept'
@racc_debug_out.puts
end
def racc_e_pop(state, tstack, vstack)
@racc_debug_out.puts 'error recovering mode: pop token'
racc_print_states state
racc_print_stacks tstack, vstack
@racc_debug_out.puts
end
def racc_next_state(curstate, state)
@racc_debug_out.puts "goto #{curstate}"
racc_print_states state
@racc_debug_out.puts
end
def racc_print_stacks(t, v)
out = @racc_debug_out
out.print ' ['
t.each_index do |i|
out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
end
out.puts ' ]'
end
def racc_print_states(s)
out = @racc_debug_out
out.print ' ['
s.each {|st| out.print ' ', st }
out.puts ' ]'
end
def racc_token2str(tok)
self.class::Racc_token_to_s_table[tok] or
raise "[Racc Bug] can't convert token #{tok} to string"
end
# Convert internal ID of token symbol to the string.
def token_to_str(t)
self.class::Racc_token_to_s_table[t]
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/promise/v1.rb | stdlib/promise/v1.rb | require 'promise'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/promise/v2.rb | stdlib/promise/v2.rb | # backtick_javascript: true
# {Promise} is used to help structure asynchronous code.
#
# It is available in the Opal standard library, and can be required in any Opal
# application:
#
# require 'promise/v2'
#
# ## Basic Usage
#
# Promises are created and returned as objects with the assumption that they
# will eventually be resolved or rejected, but never both. A {Promise} has
# a {#then} and {#fail} method (or one of their aliases) that can be used to
# register a block that gets called once resolved or rejected.
#
# promise = PromiseV2.new
#
# promise.then {
# puts "resolved!"
# }.fail {
# puts "rejected!"
# }
#
# # some time later
# promise.resolve
#
# # => "resolved!"
#
# It is important to remember that a promise can only be resolved or rejected
# once, so the block will only ever be called once (or not at all).
#
# ## Resolving Promises
#
# To resolve a promise, means to inform the {Promise} that it has succeeded
# or evaluated to a useful value. {#resolve} can be passed a value which is
# then passed into the block handler:
#
# def get_json
# promise = PromiseV2.new
#
# HTTP.get("some_url") do |req|
# promise.resolve req.json
# end
#
# promise
# end
#
# get_json.then do |json|
# puts "got some JSON from server"
# end
#
# ## Rejecting Promises
#
# Promises are also designed to handle error cases, or situations where an
# outcome is not as expected. Taking the previous example, we can also pass
# a value to a {#reject} call, which passes that object to the registered
# {#fail} handler:
#
# def get_json
# promise = PromiseV2.new
#
# HTTP.get("some_url") do |req|
# if req.ok?
# promise.resolve req.json
# else
# promise.reject req
# end
#
# promise
# end
#
# get_json.then {
# # ...
# }.fail { |req|
# puts "it went wrong: #{req.message}"
# }
#
# ## Chaining Promises
#
# Promises become even more useful when chained together. Each {#then} or
# {#fail} call returns a new {PromiseV2} which can be used to chain more and more
# handlers together.
#
# promise.then { wait_for_something }.then { do_something_else }
#
# Rejections are propagated through the entire chain, so a "catch all" handler
# can be attached at the end of the tail:
#
# promise.then { ... }.then { ... }.fail { ... }
#
# ## Composing Promises
#
# {PromiseV2.when} can be used to wait for more than one promise to resolve (or
# reject). Using the previous example, we could request two different json
# requests and wait for both to finish:
#
# PromiseV2.when(get_json, get_json2).then |first, second|
# puts "got two json payloads: #{first}, #{second}"
# end
#
class PromiseV2 < `Promise`
class << self
def allocate
ok, fail = nil, nil
prom = `new self.$$constructor(function(_ok, _fail) { #{ok} = _ok; #{fail} = _fail; })`
prom.instance_variable_set(:@type, :opal)
prom.instance_variable_set(:@resolve_proc, ok)
prom.instance_variable_set(:@reject_proc, fail)
prom
end
def when(*promises)
promises = Array(promises.length == 1 ? promises.first : promises)
`Promise.all(#{promises})`.tap do |prom|
prom.instance_variable_set(:@type, :when)
end
end
def all_resolved(*promises)
promises = Array(promises.length == 1 ? promises.first : promises)
`Promise.allResolved(#{promises})`.tap do |prom|
prom.instance_variable_set(:@type, :all_resolved)
end
end
def any(*promises)
promises = Array(promises.length == 1 ? promises.first : promises)
`Promise.any(#{promises})`.tap do |prom|
prom.instance_variable_set(:@type, :any)
end
end
def race(*promises)
promises = Array(promises.length == 1 ? promises.first : promises)
`Promise.race(#{promises})`.tap do |prom|
prom.instance_variable_set(:@type, :race)
end
end
def resolve(value = nil)
`Promise.resolve(#{value})`.tap do |prom|
prom.instance_variable_set(:@type, :resolve)
prom.instance_variable_set(:@realized, :resolve)
prom.instance_variable_set(:@value_set, true)
prom.instance_variable_set(:@value, value)
end
end
def reject(value = nil)
`Promise.reject(#{value})`.tap do |prom|
prom.instance_variable_set(:@type, :reject)
prom.instance_variable_set(:@realized, :reject)
prom.instance_variable_set(:@value_set, true)
prom.instance_variable_set(:@value, value)
end
end
alias all when
alias error reject
alias value resolve
end
attr_reader :prev, :next
# Is this promise native to JavaScript? This means, that methods like resolve
# or reject won't be available.
def native?
@type != :opal
end
# Raise an exception when a non-JS-native method is called on a JS-native promise
def nativity_check!
raise ArgumentError, 'this promise is native to JavaScript' if native?
end
# Raise an exception when a non-JS-native method is called on a JS-native promise
# but permits some typed promises
def light_nativity_check!
return if %i[reject resolve trace always fail then].include? @type
raise ArgumentError, 'this promise is native to JavaScript' if native?
end
# Allow only one chain to be present, as needed by the previous implementation.
# This isn't a strict check - it's always possible on the JS side to chain a
# given block.
def there_can_be_only_one!
raise ArgumentError, 'a promise has already been chained' if @next && @next.any?
end
def gen_tracing_proc(passing, &block)
proc do |i|
res = passing.call(i)
yield(res)
res
end
end
def resolve(value = nil)
nativity_check!
raise ArgumentError, 'this promise was already resolved' if @realized
@value_set = true
@value = value
@realized = :resolve
@resolve_proc.call(value)
self
end
def reject(value = nil)
nativity_check!
raise ArgumentError, 'this promise was already resolved' if @realized
@value_set = true
@value = value
@realized = :reject
@reject_proc.call(value)
self
end
def then(&block)
prom = nil
blk = gen_tracing_proc(block) do |val|
prom.instance_variable_set(:@realized, :resolve)
prom.instance_variable_set(:@value_set, true)
prom.instance_variable_set(:@value, val)
end
prom = `self.then(#{blk})`
prom.instance_variable_set(:@prev, self)
prom.instance_variable_set(:@type, :then)
(@next ||= []) << prom
prom
end
def then!(&block)
there_can_be_only_one!
self.then(&block)
end
def fail(&block)
prom = nil
blk = gen_tracing_proc(block) do |val|
prom.instance_variable_set(:@realized, :resolve)
prom.instance_variable_set(:@value_set, true)
prom.instance_variable_set(:@value, val)
end
prom = `self.catch(#{blk})`
prom.instance_variable_set(:@prev, self)
prom.instance_variable_set(:@type, :fail)
(@next ||= []) << prom
prom
end
def fail!(&block)
there_can_be_only_one!
fail(&block)
end
def always(&block)
prom = nil
blk = gen_tracing_proc(block) do |val|
prom.instance_variable_set(:@realized, :resolve)
prom.instance_variable_set(:@value_set, true)
prom.instance_variable_set(:@value, val)
end
prom = `self.finally(function() { return blk(self.$value_internal()); })`
prom.instance_variable_set(:@prev, self)
prom.instance_variable_set(:@type, :always)
(@next ||= []) << prom
prom
end
def always!(&block)
there_can_be_only_one!
always(&block)
end
def trace(depth = nil, &block)
prom = self.then do
values = []
prom = self
while prom && (!depth || depth > 0)
val = nil
begin
val = prom.value
rescue ArgumentError
val = :native
end
values.unshift(val)
depth -= 1 if depth
prom = prom.prev
end
yield(*values)
end
prom.instance_variable_set(:@type, :trace)
prom
end
def trace!(*args, &block)
there_can_be_only_one!
trace(*args, &block)
end
def resolved?
light_nativity_check!
@realized == :resolve
end
def rejected?
light_nativity_check!
@realized == :reject
end
def realized?
light_nativity_check!
!@realized.nil?
end
def value
if resolved?
value_internal
end
end
def error
light_nativity_check!
@value if rejected?
end
def and(*promises)
promises = promises.map do |i|
if PromiseV2 === i
i
else
PromiseV2.value(i)
end
end
PromiseV2.when(self, *promises).then do |a, *b|
[*a, *b]
end
end
def initialize(&block)
yield self if block_given?
end
def to_v1
v1 = PromiseV1.new
self.then { |i| v1.resolve(i) }.rescue { |i| v1.reject(i) }
v1
end
def inspect
result = "#<#{self.class}"
if @type
result += ":#{@type}" unless %i[opal resolve reject].include? @type
else
result += ':native'
end
result += ":#{@realized}" if @realized
result += "(#{object_id})"
if @next && @next.any?
result += " >> #{@next.inspect}"
end
result += ": #{value.inspect}"
result += '>'
result
end
alias catch fail
alias catch! fail!
alias do then
alias do! then!
alias ensure always
alias ensure! always!
alias finally always
alias finally! always!
alias reject! reject
alias rescue fail
alias rescue! fail!
alias resolve! resolve
alias to_n itself
alias to_v2 itself
private
def value_internal
if PromiseV2 === @value
@value.value
elsif @value_set
@value
elsif @prev
@prev.value
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/deno/file.rb | stdlib/deno/file.rb | # backtick_javascript: true
`/* global Deno */`
require 'corelib/file'
%x{
var warnings = {}, errno_codes = #{Errno.constants};
function handle_unsupported_feature(message) {
switch (Opal.config.unsupported_features_severity) {
case 'error':
#{Kernel.raise NotImplementedError, `message`}
break;
case 'warning':
warn(message)
break;
default: // ignore
// noop
}
}
function warn(string) {
if (warnings[string]) {
return;
}
warnings[string] = true;
#{warn(`string`)};
}
function is_utf8(bytes) {
var i = 0;
while (i < bytes.length) {
if ((// ASCII
bytes[i] === 0x09 ||
bytes[i] === 0x0A ||
bytes[i] === 0x0D ||
(0x20 <= bytes[i] && bytes[i] <= 0x7E)
)
) {
i += 1;
continue;
}
if ((// non-overlong 2-byte
(0xC2 <= bytes[i] && bytes[i] <= 0xDF) &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF)
)
) {
i += 2;
continue;
}
if ((// excluding overlongs
bytes[i] === 0xE0 &&
(0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
) ||
(// straight 3-byte
((0xE1 <= bytes[i] && bytes[i] <= 0xEC) ||
bytes[i] === 0xEE ||
bytes[i] === 0xEF) &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
) ||
(// excluding surrogates
bytes[i] === 0xED &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x9F) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
)
) {
i += 3;
continue;
}
if ((// planes 1-3
bytes[i] === 0xF0 &&
(0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
) ||
(// planes 4-15
(0xF1 <= bytes[i] && bytes[i] <= 0xF3) &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
) ||
(// plane 16
bytes[i] === 0xF4 &&
(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) &&
(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
)
) {
i += 4;
continue;
}
return false;
}
return true;
}
function executeIOAction(action) {
try {
return action();
} catch (error) {
if (errno_codes.indexOf(error.code) >= 0) {
var error_class = #{Errno.const_get(`error.code`)}
#{Kernel.raise `error_class`.new(`error.message`)}
}
#{Kernel.raise `error`}
}
}
}
class File < IO
`var __utf8TextDecoder__ = new TextDecoder('utf8')`
`var __textEncoder__ = new TextEncoder()`
def self.read(path)
`return executeIOAction(function(){return Deno.readFileSync(#{path}).toString()})`
end
def self.write(path, data)
`executeIOAction(function(){return Deno.writeFileSync(#{path}, __textEncoder__.encode(#{data}));})`
data.size
end
def self.delete(path)
`executeIOAction(function(){return Deno.removeSync(#{path})})`
end
class << self
alias unlink delete
end
def self.exist?(path)
path = path.path if path.respond_to? :path
`return executeIOAction(function(){return Deno.statSync(#{path})})`
end
def self.realpath(pathname, dir_string = nil, cache = nil, &block)
pathname = join(dir_string, pathname) if dir_string
if block_given?
`
Deno.realpath(#{pathname}, #{cache}, function(error, realpath){
if (error) Opal.IOError.$new(error.message)
else #{block.call(`realpath`)}
})
`
else
`return executeIOAction(function(){return Deno.realpathSync(#{pathname}, #{cache})})`
end
end
def self.join(*paths)
# by itself, `path.posix.join` normalizes leading // to /.
# restore the leading / on UNC paths (i.e., paths starting with //).
paths = paths.map(&:to_s)
prefix = paths.first&.start_with?('//') ? '/' : ''
path = prefix
paths.each do |pth|
path << if pth.end_with?('/') || pth.start_with?('/')
pth
else
'/' + pth
end
end
path
end
def self.directory?(path)
return false unless exist? path
result = `executeIOAction(function(){return !!Deno.lstatSync(path).isDirectory})`
unless result
realpath = realpath(path)
if realpath != path
result = `executeIOAction(function(){return !!Deno.lstatSync(realpath).isDirectory})`
end
end
result
end
def self.file?(path)
return false unless exist? path
result = `executeIOAction(function(){return !!Deno.lstatSync(path).isFile})`
unless result
realpath = realpath(path)
if realpath != path
result = `executeIOAction(function(){return !!Deno.lstatSync(realpath).isFile})`
end
end
result
end
def self.readable?(path)
return false unless exist? path
%x{
try {
Deno.openSync(path, {read: true}).close();
return true;
} catch (error) {
return false;
}
}
end
def self.size(path)
`return executeIOAction(function(){return Deno.lstatSync(path).size})`
end
def self.open(path, mode = 'r')
file = new(path, mode)
if block_given?
begin
yield(file)
ensure
file.close
end
else
file
end
end
def self.stat(path)
path = path.path if path.respond_to? :path
File::Stat.new(path)
end
def self.mtime(path)
`return executeIOAction(function(){return Deno.statSync(#{path}).mtime})`
end
def self.symlink?(path)
`return executeIOAction(function(){return Deno.lstatSync(#{path}).isSymLink})`
end
def self.absolute_path(path, basedir = nil)
raise 'File::absolute_path is currently unsupported in Deno!'
end
# Instance Methods
def initialize(path, flags = 'r')
@binary_flag = flags.include?('b')
# Node does not recognize this flag
flags = flags.delete('b')
# encoding flag is unsupported
encoding_option_rx = /:(.*)/
if encoding_option_rx.match?(flags)
`handle_unsupported_feature("Encoding option (:encoding) is unsupported by Node.js openSync method and will be removed.")`
flags = flags.sub(encoding_option_rx, '')
end
@path = path
fd = `executeIOAction(function(){return Deno.openSync(path, flags)})`
super(fd, flags)
end
attr_reader :path
def sysread(bytes)
if @eof
raise EOFError, 'end of file reached'
else
if @binary_flag
%x{
var buf = executeIOAction(function(){return Deno.readFileSync(#{@path})})
var content
if (is_utf8(buf)) {
content = buf.toString('utf8')
} else {
// coerce to utf8
content = __utf8TextDecoder__.decode(__textEncoder__.encode(buf.toString('binary')))
}
}
res = `content`
else
res = `executeIOAction(function(){return Deno.readFileSync(#{@path}).toString('utf8')})`
end
@eof = true
@lineno = res.size
res
end
end
def write(string)
`executeIOAction(function(){return #{@fd}.writeSync(__textEncoder__.encode(#{string}))})`
end
def flush
# not supported by deno
end
def close
`executeIOAction(function(){return #{@fd}.close()})`
super
end
def mtime
`return executeIOAction(function(){return Deno.statSync(#{@path}).mtime})`
end
end
class File::Stat
def initialize(path)
@path = path
end
def file?
`return executeIOAction(function(){return Deno.statSync(#{@path}).isFile})`
end
def directory?
`return executeIOAction(function(){return Deno.statSync(#{@path}).isDirectory})`
end
def mtime
`return executeIOAction(function(){return Deno.statSync(#{@path}).mtime})`
end
def readable?
%x{
return executeIOAction(function(){
Deno.openSync(path, {read: true}).close();
return true;
})
}
end
def writable?
%x{
return executeIOAction(function(){
Deno.openSync(path, {write: true}).close();
return true;
})
}
end
def executable?
# accessible only over unstable API
false
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/deno/base.rb | stdlib/deno/base.rb | # backtick_javascript: true
`/* global Deno */`
module Deno
VERSION = `Deno.version.deno`
end
`Opal.exit = Deno.exit`
ARGV = `Deno.args.slice(2)`
ARGV.shift if ARGV.first == '--'
STDOUT.write_proc = ->(string) { `Deno.stdout.write(new TextEncoder().encode(string))` }
STDERR.write_proc = ->(string) { `Deno.stderr.write(new TextEncoder().encode(string))` }
STDIN.read_proc = %x{function(_count) {
// Ignore count, return as much as we can get
var buf = new Uint8Array(65536), count;
try {
count = Deno.stdin.readSync(buf);
}
catch (e) { // Windows systems may raise EOF
return nil;
}
if (count == 0) return nil;
return buf.toString('utf8', 0, count);
}}
STDIN.tty = true
STDOUT.tty = true
STDERR.tty = true
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/buffer/array.rb | stdlib/buffer/array.rb | # backtick_javascript: true
class Buffer
class Array
include Native::Wrapper
def self.for(bits, type)
$$["#{Buffer.name_for bits, type}Array"]
end
include Enumerable
attr_reader :buffer, :type
def initialize(buffer, bits = nil, type = nil)
if Native == buffer
super(buffer)
else
%x{
var klass = #{Array.for(bits, type)};
#{super(`new klass(#{buffer.to_n})`)}
}
end
@buffer = buffer
@type = type
end
def bits
`#{@native}.BYTES_PER_ELEMENT * 8`
end
def [](index, offset = nil)
offset ? `#{@native}.subarray(index, offset)` : `#{@native}[index]`
end
def []=(index, value)
`#{@native}[index] = value`
end
def bytesize
`#{@native}.byteLength`
end
def each
return enum_for :each unless block_given?
%x{
for (var i = 0, length = #{@native}.length; i < length; i++) {
#{yield `#{@native}[i]`}
}
}
self
end
def length
`#{@native}.length`
end
def merge!(other, offset = undefined)
`#{@native}.set(#{other.to_n}, offset)`
end
alias size length
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/buffer/view.rb | stdlib/buffer/view.rb | # backtick_javascript: true
class Buffer
class View
include Native::Wrapper
def self.supported?
!$$[:DataView].nil?
end
attr_reader :buffer, :offset
def initialize(buffer, offset = nil, length = nil)
if native?(buffer)
super(buffer)
elsif offset && length
super(`new DataView(#{buffer.to_n}, #{offset.to_n}, #{length.to_n})`)
elsif offset
super(`new DataView(#{buffer.to_n}, #{offset.to_n})`)
else
super(`new DataView(#{buffer.to_n})`)
end
@buffer = buffer
@offset = offset
end
def length
`#{@native}.byteLength`
end
def get(offset, bits = 8, type = :unsigned, little = false)
`#{@native}["get" + #{Buffer.name_for bits, type}](offset, little)`
end
alias [] get
def set(offset, value, bits = 8, type = :unsigned, little = false)
`#{@native}["set" + #{Buffer.name_for bits, type}](offset, value, little)`
end
alias []= set
def get_int8(offset, little = false)
`#{@native}.getInt8(offset, little)`
end
def set_int8(offset, value, little = false)
`#{@native}.setInt8(offset, value, little)`
end
def get_uint8(offset, little = false)
`#{@native}.getUint8(offset, little)`
end
def set_uint8(offset, value, little = false)
`#{@native}.setUint8(offset, value, little)`
end
def get_int16(offset, little = false)
`#{@native}.getInt16(offset, little)`
end
def set_int16(offset, value, little = false)
`#{@native}.setInt16(offset, value, little)`
end
def get_uint16(offset, little = false)
`#{@native}.getUint16(offset, little)`
end
def set_uint16(offset, value, little = false)
`#{@native}.setUint16(offset, value, little)`
end
def get_int32(offset, little = false)
`#{@native}.getInt32(offset, little)`
end
def set_int32(offset, value, little = false)
`#{@native}.setInt32(offset, value, little)`
end
def get_uint32(offset, little = false)
`#{@native}.getUint32(offset, little)`
end
def set_uint32(offset, value, little = false)
`#{@native}.setUint32(offset, value, little)`
end
def get_float32(offset, little = false)
`#{@native}.getFloat32(offset, little)`
end
def set_float32(offset, value, little = false)
`#{@native}.setFloat32(offset, value, little)`
end
def get_float64(offset, little = false)
`#{@native}.getFloat64(offset, little)`
end
def set_float64(offset, value, little = false)
`#{@native}.setFloat64(offset, value, little)`
end
alias size length
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/minitest.rb | vendored-minitest/minitest.rb | # await: *await*
require "optparse"
require "thread"
require "mutex_m"
# require "minitest/parallel"
require "await"
##
# :include: README.txt
module Minitest
VERSION = "5.5.1" # :nodoc:
ENCS = "".respond_to? :encoding # :nodoc:
@@installed_at_exit ||= false
@@after_run = []
@extensions = []
mc = (class << self; self; end)
##
# Parallel test executor
# mc.send :attr_accessor, :parallel_executor
# self.parallel_executor = Parallel::Executor.new((ENV['N'] || 2).to_i)
##
# Filter object for backtraces.
mc.send :attr_accessor, :backtrace_filter
##
# Reporter object to be used for all runs.
#
# NOTE: This accessor is only available during setup, not during runs.
mc.send :attr_accessor, :reporter
##
# Names of known extension plugins.
mc.send :attr_accessor, :extensions
##
# Registers Minitest to run at process exit
def self.autorun
at_exit {
next if $! and not ($!.kind_of? SystemExit and $!.success?)
exit_code = nil
at_exit {
@@after_run.reverse_each(&:call)
exit exit_code || false
}
exit_code = Minitest.run(ARGV).await
} unless @@installed_at_exit
@@installed_at_exit = true
end
##
# A simple hook allowing you to run a block of code after everything
# is done running. Eg:
#
# Minitest.after_run { p $debugging_info }
def self.after_run &block
@@after_run << block
end
def self.init_plugins options # :nodoc:
self.extensions.each do |name|
msg = "plugin_#{name}_init"
send msg, options if self.respond_to? msg
end
end
def self.load_plugins # :nodoc:
# return unless self.extensions.empty?
#
# seen = {}
#
# require "rubygems" unless defined? Gem
#
# Gem.find_files("minitest/*_plugin.rb").each do |plugin_path|
# name = File.basename plugin_path, "_plugin.rb"
#
# next if seen[name]
# seen[name] = true
#
# require plugin_path
# self.extensions << name
# end
end
##
# This is the top-level run method. Everything starts from here. It
# tells each Runnable sub-class to run, and each of those are
# responsible for doing whatever they do.
#
# The overall structure of a run looks like this:
#
# Minitest.autorun
# Minitest.run(args)
# Minitest.__run(reporter, options)
# Runnable.runnables.each
# runnable.run(reporter, options)
# self.runnable_methods.each
# self.run_one_method(self, runnable_method, reporter)
# Minitest.run_one_method(klass, runnable_method, reporter)
# klass.new(runnable_method).run
def self.run args = []
self.load_plugins
options = process_args args
reporter = CompositeReporter.new
reporter << SummaryReporter.new(options[:io], options)
reporter << ProgressReporter.new(options[:io], options)
self.reporter = reporter # this makes it available to plugins
self.init_plugins options
self.reporter = nil # runnables shouldn't depend on the reporter, ever
reporter.start
__run(reporter, options).await
# self.parallel_executor.shutdown
reporter.report
reporter.passed?
end
##
# Internal run method. Responsible for telling all Runnable
# sub-classes to run.
#
# NOTE: this method is redefined in parallel_each.rb, which is
# loaded if a Runnable calls parallelize_me!.
def self.__run reporter, options
suites = Runnable.runnables.shuffle
parallel, serial = suites.partition { |s| s.test_order == :parallel }
# If we run the parallel tests before the serial tests, the parallel tests
# could run in parallel with the serial tests. This would be bad because
# the serial tests won't lock around Reporter#record. Run the serial tests
# first, so that after they complete, the parallel tests will lock when
# recording results.
serial.map_await { |suite| suite.run(reporter, options).await } +
parallel.map_await { |suite| suite.run(reporter, options).await }
end
def self.process_args args = [] # :nodoc:
options = {
:io => $stdout,
}
orig_args = args.dup
OptionParser.new do |opts|
opts.banner = "minitest options:"
opts.version = Minitest::VERSION
opts.on "-h", "--help", "Display this help." do
puts opts
exit
end
desc = "Sets random seed. Also via env. Eg: SEED=n rake"
opts.on "-s", "--seed SEED", Integer, desc do |m|
options[:seed] = m.to_i
end
opts.on "-v", "--verbose", "Verbose. Show progress processing files." do
options[:verbose] = true
end
opts.on "-n", "--name PATTERN","Filter run on /pattern/ or string." do |a|
options[:filter] = a
end
unless extensions.empty?
opts.separator ""
opts.separator "Known extensions: #{extensions.join(', ')}"
extensions.each do |meth|
msg = "plugin_#{meth}_options"
send msg, opts, options if self.respond_to?(msg)
end
end
begin
opts.parse! args
rescue OptionParser::InvalidOption => e
puts
puts e
puts
puts opts
exit 1
end
orig_args -= args
end unless args.empty?
unless options[:seed] then
srand
options[:seed] = (ENV["RANDOM_SEED"] || srand).to_i % 0xFFFF
orig_args << "--seed" << options[:seed].to_s
end
srand options[:seed]
options[:args] = orig_args.map { |s|
s =~ /[\s|&<>$()]/ ? s.inspect : s
}.join " "
options
end
def self.filter_backtrace bt # :nodoc:
backtrace_filter.filter bt
end
##
# Represents anything "runnable", like Test, Spec, Benchmark, or
# whatever you can dream up.
#
# Subclasses of this are automatically registered and available in
# Runnable.runnables.
class Runnable
##
# Number of assertions executed in this run.
attr_accessor :assertions
##
# An assertion raised during the run, if any.
attr_accessor :failures
##
# Name of the run.
def name
@NAME
end
##
# Set the name of the run.
def name= o
@NAME = o
end
def self.inherited klass # :nodoc:
self.runnables << klass
super
end
##
# Returns all instance methods matching the pattern +re+.
def self.methods_matching re
public_instance_methods(true).grep(re).map(&:to_s)
end
def self.reset # :nodoc:
@@runnables = []
end
reset
##
# Responsible for running all runnable methods in a given class,
# each in its own instance. Each instance is passed to the
# reporter to record.
def self.run reporter, options = {}
filter = options[:filter] || '/./'
filter = Regexp.new $1 if filter =~ /\/(.*)\//
filtered_methods = self.runnable_methods.find_all { |m|
filter === m || filter === "#{self}##{m}"
}
with_info_handler(reporter) do
filtered_methods.each_await do |method_name|
run_one_method(self, method_name, reporter).await
end
end.await
end
##
# Runs a single method and has the reporter record the result.
# This was considered internal API but is factored out of run so
# that subclasses can specialize the running of an individual
# test. See Minitest::ParallelTest::ClassMethods for an example.
def self.run_one_method klass, method_name, reporter
reporter.record Minitest.run_one_method(klass, method_name).await
end
def self.with_info_handler reporter, &block # :nodoc:
handler = lambda do
unless reporter.passed? then
warn "Current results:"
warn ""
warn reporter.reporters.first
warn ""
end
end
on_signal("INFO", handler, &block).await
end
SIGNALS = {} # Signal.list # :nodoc:
def self.on_signal name, action # :nodoc:
supported = SIGNALS[name]
old_trap = trap name do
old_trap.call if old_trap.respond_to? :call
action.call
end if supported
yield.await
ensure
trap name, old_trap if supported
end
##
# Each subclass of Runnable is responsible for overriding this
# method to return all runnable methods. See #methods_matching.
def self.runnable_methods
raise NotImplementedError, "subclass responsibility"
end
##
# Returns all subclasses of Runnable.
def self.runnables
@@runnables
end
def marshal_dump # :nodoc:
[self.name, self.failures, self.assertions]
end
def marshal_load ary # :nodoc:
self.name, self.failures, self.assertions = ary
end
def failure # :nodoc:
self.failures.first
end
def initialize name # :nodoc:
self.name = name
self.failures = []
self.assertions = 0
end
##
# Runs a single method. Needs to return self.
def run
raise NotImplementedError, "subclass responsibility"
end
##
# Did this run pass?
#
# Note: skipped runs are not considered passing, but they don't
# cause the process to exit non-zero.
def passed?
raise NotImplementedError, "subclass responsibility"
end
##
# Returns a single character string to print based on the result
# of the run. Eg ".", "F", or "E".
def result_code
raise NotImplementedError, "subclass responsibility"
end
##
# Was this run skipped? See #passed? for more information.
def skipped?
raise NotImplementedError, "subclass responsibility"
end
end
##
# Defines the API for Reporters. Subclass this and override whatever
# you want. Go nuts.
class AbstractReporter
# include Mutex_m
##
# Starts reporting on the run.
def start
end
##
# Record a result and output the Runnable#result_code. Stores the
# result of the run if the run did not pass.
def record result
end
##
# Outputs the summary of the run.
def report
end
##
# Did this run pass?
def passed?
true
end
end
class Reporter < AbstractReporter # :nodoc:
##
# The IO used to report.
attr_accessor :io
##
# Command-line options for this run.
attr_accessor :options
def initialize io = $stdout, options = {} # :nodoc:
super()
self.io = io
self.options = options
end
end
##
# A very simple reporter that prints the "dots" during the run.
#
# This is added to the top-level CompositeReporter at the start of
# the run. If you want to change the output of minitest via a
# plugin, pull this out of the composite and replace it with your
# own.
class ProgressReporter < Reporter
def record result # :nodoc:
io.print "%s#%s = %.2f s = " % [result.class, result.name, result.time] if
options[:verbose]
io.print result.result_code
io.puts if options[:verbose]
end
end
##
# A reporter that gathers statistics about a test run. Does not do
# any IO because meant to be used as a parent class for a reporter
# that does.
#
# If you want to create an entirely different type of output (eg,
# CI, HTML, etc), this is the place to start.
class StatisticsReporter < Reporter
# :stopdoc:
attr_accessor :assertions
attr_accessor :count
attr_accessor :results
attr_accessor :start_time
attr_accessor :total_time
attr_accessor :failures
attr_accessor :errors
attr_accessor :skips
# :startdoc:
def initialize io = $stdout, options = {} # :nodoc:
super
self.assertions = 0
self.count = 0
self.results = []
self.start_time = nil
self.total_time = nil
self.failures = nil
self.errors = nil
self.skips = nil
end
def passed? # :nodoc:
results.all?(&:skipped?)
end
def start # :nodoc:
self.start_time = Time.now
end
def record result # :nodoc:
self.count += 1
self.assertions += result.assertions
results << result if not result.passed? or result.skipped?
end
def report # :nodoc:
aggregate = results.group_by { |r| r.failure.class }
aggregate.default = [] # dumb. group_by should provide this
self.total_time = Time.now - start_time
self.failures = aggregate[Assertion].size
self.errors = aggregate[UnexpectedError].size
self.skips = aggregate[Skip].size
end
end
##
# A reporter that prints the header, summary, and failure details at
# the end of the run.
#
# This is added to the top-level CompositeReporter at the start of
# the run. If you want to change the output of minitest via a
# plugin, pull this out of the composite and replace it with your
# own.
class SummaryReporter < StatisticsReporter
# :stopdoc:
attr_accessor :sync
attr_accessor :old_sync
# :startdoc:
def start # :nodoc:
super
io.puts "Run options: #{options[:args]}"
io.puts
io.puts "# Running:"
io.puts
self.sync = io.respond_to? :"sync=" # stupid emacs
self.old_sync, io.sync = io.sync, true if self.sync
end
def report # :nodoc:
super
io.sync = self.old_sync
io.puts unless options[:verbose] # finish the dots
io.puts
io.puts statistics
io.puts aggregated_results
io.puts summary
end
def statistics # :nodoc:
"Finished in %.6fs, %.4f runs/s, %.4f assertions/s." %
[total_time, count / total_time, assertions / total_time]
end
def aggregated_results # :nodoc:
filtered_results = results.dup
filtered_results.reject!(&:skipped?) unless options[:verbose]
s = filtered_results.each_with_index.map { |result, i|
"\n%3d) %s" % [i+1, result]
}.join("\n") + "\n"
# s.force_encoding(io.external_encoding) if
# ENCS and io.external_encoding and s.encoding != io.external_encoding
s
end
alias to_s aggregated_results
def summary # :nodoc:
extra = ""
extra = "\n\nYou have skipped tests. Run with --verbose for details." if
results.any?(&:skipped?) unless options[:verbose] or ENV["MT_NO_SKIP_MSG"]
"%d runs, %d assertions, %d failures, %d errors, %d skips%s" %
[count, assertions, failures, errors, skips, extra]
end
end
##
# Dispatch to multiple reporters as one.
class CompositeReporter < AbstractReporter
##
# The list of reporters to dispatch to.
attr_accessor :reporters
def initialize *reporters # :nodoc:
super()
self.reporters = reporters
end
##
# Add another reporter to the mix.
def << reporter
self.reporters << reporter
end
def passed? # :nodoc:
self.reporters.all?(&:passed?)
end
def start # :nodoc:
self.reporters.each(&:start)
end
def record result # :nodoc:
self.reporters.each do |reporter|
reporter.record result
end
end
def report # :nodoc:
self.reporters.each(&:report)
end
end
##
# Represents run failures.
class Assertion < Exception
def error # :nodoc:
self
end
##
# Where was this run before an assertion was raised?
def location
last_before_assertion = ""
self.backtrace.reverse_each do |s|
break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/
last_before_assertion = s
end
last_before_assertion.sub(/:in .*$/, "")
end
def result_code # :nodoc:
result_label[0, 1]
end
def result_label # :nodoc:
"Failure"
end
end
##
# Assertion raised when skipping a run.
class Skip < Assertion
def result_label # :nodoc:
"Skipped"
end
end
##
# Assertion wrapping an unexpected error that was raised during a run.
class UnexpectedError < Assertion
attr_accessor :exception # :nodoc:
def initialize exception # :nodoc:
super
self.exception = exception
end
def backtrace # :nodoc:
self.exception.backtrace
end
def error # :nodoc:
self.exception
end
def message # :nodoc:
bt = Minitest::filter_backtrace(self.backtrace).join "\n "
"#{self.exception.class}: #{self.exception.message}\n #{bt}"
end
def result_label # :nodoc:
"Error"
end
end
##
# Provides a simple set of guards that you can use in your tests
# to skip execution if it is not applicable. These methods are
# mixed into Test as both instance and class methods so you
# can use them inside or outside of the test methods.
#
# def test_something_for_mri
# skip "bug 1234" if jruby?
# # ...
# end
#
# if windows? then
# # ... lots of test methods ...
# end
module Guard
##
# Is this running on jruby?
def jruby? platform = RUBY_PLATFORM
"java" == platform
end
##
# Is this running on maglev?
def maglev? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
"maglev" == platform
end
##
# Is this running on mri?
def mri? platform = RUBY_DESCRIPTION
/^ruby/ =~ platform
end
##
# Is this running on rubinius?
def rubinius? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
"rbx" == platform
end
##
# Is this running on windows?
def windows? platform = RUBY_PLATFORM
/mswin|mingw/ =~ platform
end
end
class BacktraceFilter # :nodoc:
def filter bt
return ["No backtrace"] unless bt
return bt.dup if $DEBUG
new_bt = bt.take_while { |line| line !~ /lib\/minitest/ }
new_bt = bt.select { |line| line !~ /lib\/minitest/ } if new_bt.empty?
new_bt = bt.dup if new_bt.empty?
new_bt
end
end
self.backtrace_filter = BacktraceFilter.new
def self.run_one_method klass, method_name # :nodoc:
result = klass.new(method_name).run.await
raise "#{klass}#run _must_ return self" unless klass === result
result
end
end
require "minitest/test"
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/minitest/test.rb | vendored-minitest/minitest/test.rb | # await: *await*
require "minitest" unless defined? Minitest::Runnable
module Minitest
##
# Subclass Test to create your own tests. Typically you'll want a
# Test subclass per implementation class.
#
# See Minitest::Assertions
class Test < Runnable
require "minitest/assertions"
include Minitest::Assertions
PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException, # :nodoc:
Interrupt, SystemExit]
class << self; attr_accessor :io_lock; end # :nodoc:
self.io_lock = Mutex.new
##
# Call this at the top of your tests when you absolutely
# positively need to have ordered tests. In doing so, you're
# admitting that you suck and your tests are weak.
def self.i_suck_and_my_tests_are_order_dependent!
class << self
undef_method :test_order if method_defined? :test_order
define_method :test_order do :alpha end
end
end
##
# Make diffs for this Test use #pretty_inspect so that diff
# in assert_equal can have more details. NOTE: this is much slower
# than the regular inspect but much more usable for complex
# objects.
def self.make_my_diffs_pretty!
require "pp"
define_method :mu_pp do |o|
o.pretty_inspect
end
end
##
# Call this at the top of your tests when you want to run your
# tests in parallel. In doing so, you're admitting that you rule
# and your tests are awesome.
def self.parallelize_me!
include Minitest::Parallel::Test
extend Minitest::Parallel::Test::ClassMethods
end
##
# Returns all instance methods starting with "test_". Based on
# #test_order, the methods are either sorted, randomized
# (default), or run in parallel.
def self.runnable_methods
methods = methods_matching(/^test_/)
case self.test_order
when :random, :parallel then
max = methods.size
methods.sort.sort_by { rand max }
when :alpha, :sorted then
methods.sort
else
raise "Unknown test_order: #{self.test_order.inspect}"
end
end
##
# Defines the order to run tests (:random by default). Override
# this or use a convenience method to change it for your tests.
def self.test_order
:random
end
##
# The time it took to run this test.
attr_accessor :time
def marshal_dump # :nodoc:
super << self.time
end
def marshal_load ary # :nodoc:
self.time = ary.pop
super
end
TEARDOWN_METHODS = %w{ before_teardown teardown after_teardown } # :nodoc:
##
# Runs a single test with setup/teardown hooks.
def run
with_info_handler do
time_it do
capture_exceptions do
before_setup; setup; after_setup
self.send(self.name).await
end.await
TEARDOWN_METHODS.each_await do |hook|
capture_exceptions do
self.send(hook).await
end.await
end.await
end.await
end.await
self # per contract
end
##
# Provides before/after hooks for setup and teardown. These are
# meant for library writers, NOT for regular test authors. See
# #before_setup for an example.
module LifecycleHooks
##
# Runs before every test, before setup. This hook is meant for
# libraries to extend minitest. It is not meant to be used by
# test developers.
#
# As a simplistic example:
#
# module MyMinitestPlugin
# def before_setup
# super
# # ... stuff to do before setup is run
# end
#
# def after_setup
# # ... stuff to do after setup is run
# super
# end
#
# def before_teardown
# super
# # ... stuff to do before teardown is run
# end
#
# def after_teardown
# # ... stuff to do after teardown is run
# super
# end
# end
#
# class MiniTest::Test
# include MyMinitestPlugin
# end
def before_setup; end
##
# Runs before every test. Use this to set up before each test
# run.
def setup; end
##
# Runs before every test, after setup. This hook is meant for
# libraries to extend minitest. It is not meant to be used by
# test developers.
#
# See #before_setup for an example.
def after_setup; end
##
# Runs after every test, before teardown. This hook is meant for
# libraries to extend minitest. It is not meant to be used by
# test developers.
#
# See #before_setup for an example.
def before_teardown; end
##
# Runs after every test. Use this to clean up after each test
# run.
def teardown; end
##
# Runs after every test, after teardown. This hook is meant for
# libraries to extend minitest. It is not meant to be used by
# test developers.
#
# See #before_setup for an example.
def after_teardown; end
end # LifecycleHooks
def capture_exceptions # :nodoc:
yield.await
rescue *PASSTHROUGH_EXCEPTIONS
raise
rescue Assertion => e
self.failures << e
rescue Exception => e
self.failures << UnexpectedError.new(e)
end
##
# Did this run error?
def error?
self.failures.any? { |f| UnexpectedError === f }
end
##
# The location identifier of this test.
def location
loc = " [#{self.failure.location}]" unless passed? or error?
"#{self.class}##{self.name}#{loc}"
end
##
# Did this run pass?
#
# Note: skipped runs are not considered passing, but they don't
# cause the process to exit non-zero.
def passed?
not self.failure
end
##
# Returns ".", "F", or "E" based on the result of the run.
def result_code
self.failure and self.failure.result_code or "."
end
##
# Was this run skipped?
def skipped?
self.failure and Skip === self.failure
end
def time_it # :nodoc:
t0 = Time.now
yield.await
ensure
self.time = Time.now - t0
end
def to_s # :nodoc:
return location if passed? and not skipped?
failures.map { |failure|
"#{failure.result_label}:\n#{self.location}:\n#{failure.message}\n"
}.join "\n"
end
def with_info_handler &block # :nodoc:
t0 = Time.now
handler = lambda do
warn "\nCurrent: %s#%s %.2fs" % [self.class, self.name, Time.now - t0]
end
self.class.on_signal("INFO", handler, &block).await
end
include LifecycleHooks
include Guard
extend Guard
end # Test
end
# require "minitest/unit" unless defined?(MiniTest) # compatibility layer only
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/minitest/assertions.rb | vendored-minitest/minitest/assertions.rb | require "rbconfig"
require "tempfile"
require 'stringio'
module Minitest
##
# Minitest Assertions. All assertion methods accept a +msg+ which is
# printed if the assertion fails.
#
# Protocol: Nearly everything here boils up to +assert+, which
# expects to be able to increment an instance accessor named
# +assertions+. This is not provided by Assertions and must be
# provided by the thing including Assertions. See Minitest::Runnable
# for an example.
module Assertions
UNDEFINED = Object.new # :nodoc:
def UNDEFINED.inspect # :nodoc:
"UNDEFINED" # again with the rdoc bugs... :(
end
##
# Returns the diff command to use in #diff. Tries to intelligently
# figure out what diff to use.
def self.diff
@diff = if (RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ &&
system("diff.exe", __FILE__, __FILE__)) then
"diff.exe -u"
elsif Minitest::Test.maglev? then
"diff -u"
elsif system("gdiff", __FILE__, __FILE__)
"gdiff -u" # solaris and kin suck
elsif system("diff", __FILE__, __FILE__)
"diff -u"
else
nil
end unless defined? @diff
@diff
end
##
# Set the diff command to use in #diff.
def self.diff= o
@diff = o
end
##
# Returns a diff between +exp+ and +act+. If there is no known
# diff command or if it doesn't make sense to diff the output
# (single line, short output), then it simply returns a basic
# comparison between the two.
def diff exp, act
expect = mu_pp_for_diff exp
butwas = mu_pp_for_diff act
result = nil
need_to_diff = false
# (expect.include?("\n") ||
# butwas.include?("\n") ||
# expect.size > 30 ||
# butwas.size > 30 ||
# expect == butwas) &&
# Minitest::Assertions.diff
return "Expected: #{mu_pp exp}\n Actual: #{mu_pp act}" unless
need_to_diff
# Tempfile.open("expect") do |a|
# a.puts expect
# a.flush
#
# Tempfile.open("butwas") do |b|
# b.puts butwas
# b.flush
#
# result = `#{Minitest::Assertions.diff} #{a.path} #{b.path}`
# result.sub!(/^\-\-\- .+/, "--- expected")
# result.sub!(/^\+\+\+ .+/, "+++ actual")
#
# if result.empty? then
# klass = exp.class
# result = [
# "No visible difference in the #{klass}#inspect output.\n",
# "You should look at the implementation of #== on ",
# "#{klass} or its members.\n",
# expect,
# ].join
# end
# end
# end
result
end
##
# This returns a human-readable version of +obj+. By default
# #inspect is called. You can override this to use #pretty_print
# if you want.
def mu_pp obj
s = obj.inspect
# s = s.encode Encoding.default_external if defined? Encoding
s
end
##
# This returns a diff-able human-readable version of +obj+. This
# differs from the regular mu_pp because it expands escaped
# newlines and makes hex-values generic (like object_ids). This
# uses mu_pp to do the first pass and then cleans it up.
def mu_pp_for_diff obj
mu_pp(obj).gsub(/\\n/, "\n").gsub(/:0x[a-fA-F0-9]{4,}/m, ':0xXXXXXX')
end
##
# Fails unless +test+ is truthy.
def assert test, msg = nil
self.assertions += 1
unless test then
msg ||= "Failed assertion, no message given."
msg = msg.call if Proc === msg
raise Minitest::Assertion, msg
end
true
end
def _synchronize # :nodoc:
yield
end
##
# Fails unless +obj+ is empty.
def assert_empty obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to be empty" }
assert_respond_to obj, :empty?
assert obj.empty?, msg
end
E = "" # :nodoc:
##
# Fails unless <tt>exp == act</tt> printing the difference between
# the two, if possible.
#
# If there is no visible difference but the assertion fails, you
# should suspect that your #== is buggy, or your inspect output is
# missing crucial details.
#
# For floats use assert_in_delta.
#
# See also: Minitest::Assertions.diff
def assert_equal exp, act, msg = nil
msg = message(msg, E) { diff exp, act }
assert exp == act, msg
end
##
# For comparing Floats. Fails unless +exp+ and +act+ are within +delta+
# of each other.
#
# assert_in_delta Math::PI, (22.0 / 7.0), 0.01
def assert_in_delta exp, act, delta = 0.001, msg = nil
n = (exp - act).abs
msg = message(msg) {
"Expected |#{exp} - #{act}| (#{n}) to be <= #{delta}"
}
assert delta >= n, msg
end
##
# For comparing Floats. Fails unless +exp+ and +act+ have a relative
# error less than +epsilon+.
def assert_in_epsilon a, b, epsilon = 0.001, msg = nil
assert_in_delta a, b, [a.abs, b.abs].min * epsilon, msg
end
##
# Fails unless +collection+ includes +obj+.
def assert_includes collection, obj, msg = nil
msg = message(msg) {
"Expected #{mu_pp(collection)} to include #{mu_pp(obj)}"
}
assert_respond_to collection, :include?
assert collection.include?(obj), msg
end
##
# Fails unless +obj+ is an instance of +cls+.
def assert_instance_of cls, obj, msg = nil
msg = message(msg) {
"Expected #{mu_pp(obj)} to be an instance of #{cls}, not #{obj.class}"
}
assert obj.instance_of?(cls), msg
end
##
# Fails unless +obj+ is a kind of +cls+.
def assert_kind_of cls, obj, msg = nil
msg = message(msg) {
"Expected #{mu_pp(obj)} to be a kind of #{cls}, not #{obj.class}" }
assert obj.kind_of?(cls), msg
end
##
# Fails unless +matcher+ <tt>=~</tt> +obj+.
def assert_match matcher, obj, msg = nil
msg = message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" }
assert_respond_to matcher, :"=~"
matcher = Regexp.new Regexp.escape matcher if String === matcher
assert matcher =~ obj, msg
end
##
# Fails unless +obj+ is nil
def assert_nil obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to be nil" }
assert obj.nil?, msg
end
##
# For testing with binary operators. Eg:
#
# assert_operator 5, :<=, 4
def assert_operator o1, op, o2 = UNDEFINED, msg = nil
return assert_predicate o1, op, msg if UNDEFINED == o2
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
assert o1.__send__(op, o2), msg
end
##
# Fails if stdout or stderr do not output the expected results.
# Pass in nil if you don't care about that streams output. Pass in
# "" if you require it to be silent. Pass in a regexp if you want
# to pattern match.
#
# NOTE: this uses #capture_io, not #capture_subprocess_io.
#
# See also: #assert_silent
def assert_output stdout = nil, stderr = nil
out, err = capture_io do
yield
end
err_msg = Regexp === stderr ? :assert_match : :assert_equal if stderr
out_msg = Regexp === stdout ? :assert_match : :assert_equal if stdout
y = send err_msg, stderr, err, "In stderr" if err_msg
x = send out_msg, stdout, out, "In stdout" if out_msg
(!stdout || x) && (!stderr || y)
end
##
# For testing with predicates. Eg:
#
# assert_predicate str, :empty?
#
# This is really meant for specs and is front-ended by assert_operator:
#
# str.must_be :empty?
def assert_predicate o1, op, msg = nil
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op}" }
assert o1.__send__(op), msg
end
##
# Fails unless the block raises one of +exp+. Returns the
# exception matched so you can check the message, attributes, etc.
def assert_raises *exp
msg = "#{exp.pop}.\n" if String === exp.last
begin
yield
rescue Minitest::Skip => e
return e if exp.include? Minitest::Skip
raise e
rescue Exception => e
expected = exp.any? { |ex|
if ex.instance_of? Module then
e.kind_of? ex
else
e.instance_of? ex
end
}
assert expected, proc {
exception_details(e, "#{msg}#{mu_pp(exp)} exception expected, not")
}
return e
end
exp = exp.first if exp.size == 1
flunk "#{msg}#{mu_pp(exp)} expected but nothing was raised."
end
##
# Fails unless +obj+ responds to +meth+.
def assert_respond_to obj, meth, msg = nil
msg = message(msg) {
"Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}"
}
assert obj.respond_to?(meth), msg
end
##
# Fails unless +exp+ and +act+ are #equal?
def assert_same exp, act, msg = nil
msg = message(msg) {
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
"Expected %s (oid=%d) to be the same as %s (oid=%d)" % data
}
assert exp.equal?(act), msg
end
##
# +send_ary+ is a receiver, message and arguments.
#
# Fails unless the call returns a true value
def assert_send send_ary, m = nil
recv, msg, *args = send_ary
m = message(m) {
"Expected #{mu_pp(recv)}.#{msg}(*#{mu_pp(args)}) to return true" }
assert recv.__send__(msg, *args), m
end
##
# Fails if the block outputs anything to stderr or stdout.
#
# See also: #assert_output
def assert_silent
assert_output "", "" do
yield
end
end
##
# Fails unless the block throws +sym+
def assert_throws sym, msg = nil
default = "Expected #{mu_pp(sym)} to have been thrown"
caught = true
catch(sym) do
begin
yield
rescue ThreadError => e # wtf?!? 1.8 + threads == suck
default += ", not \:#{e.message[/uncaught throw \`(\w+?)\'/, 1]}"
rescue ArgumentError => e # 1.9 exception
default += ", not #{e.message.split(/ /).last}"
rescue NameError => e # 1.8 exception
default += ", not #{e.name.inspect}"
end
caught = false
end
assert caught, message(msg) { default }
end
##
# Captures $stdout and $stderr into strings:
#
# out, err = capture_io do
# puts "Some info"
# warn "You did a bad thing"
# end
#
# assert_match %r%info%, out
# assert_match %r%bad%, err
#
# NOTE: For efficiency, this method uses StringIO and does not
# capture IO for subprocesses. Use #capture_subprocess_io for
# that.
def capture_io
_synchronize do
begin
captured_stdout, captured_stderr = StringIO.new, StringIO.new
orig_stdout, orig_stderr = $stdout, $stderr
$stdout, $stderr = captured_stdout, captured_stderr
yield
return captured_stdout.string, captured_stderr.string
ensure
$stdout = orig_stdout
$stderr = orig_stderr
end
end
end
alias capture_output capture_io
##
# Captures $stdout and $stderr into strings, using Tempfile to
# ensure that subprocess IO is captured as well.
#
# out, err = capture_subprocess_io do
# system "echo Some info"
# system "echo You did a bad thing 1>&2"
# end
#
# assert_match %r%info%, out
# assert_match %r%bad%, err
#
# NOTE: This method is approximately 10x slower than #capture_io so
# only use it when you need to test the output of a subprocess.
def capture_subprocess_io
_synchronize do
begin
require 'tempfile'
captured_stdout, captured_stderr = Tempfile.new("out"), Tempfile.new("err")
orig_stdout, orig_stderr = $stdout.dup, $stderr.dup
$stdout.reopen captured_stdout
$stderr.reopen captured_stderr
yield
$stdout.rewind
$stderr.rewind
return captured_stdout.read, captured_stderr.read
ensure
captured_stdout.unlink
captured_stderr.unlink
$stdout.reopen orig_stdout
$stderr.reopen orig_stderr
end
end
end
##
# Returns details for exception +e+
def exception_details e, msg
[
"#{msg}",
"Class: <#{e.class}>",
"Message: <#{e.message.inspect}>",
"---Backtrace---",
"#{Minitest::filter_backtrace(e.backtrace).join("\n")}",
"---------------",
].join "\n"
end
##
# Fails with +msg+
def flunk msg = nil
msg ||= "Epic Fail!"
assert false, msg
end
##
# Returns a proc that will output +msg+ along with the default message.
def message msg = nil, ending = nil, &default
proc {
msg = msg.call.chomp(".") if Proc === msg
custom_message = "#{msg}.\n" unless msg.nil? or msg.to_s.empty?
"#{custom_message}#{default.call}#{ending || "."}"
}
end
##
# used for counting assertions
def pass msg = nil
assert true
end
##
# Fails if +test+ is truthy.
def refute test, msg = nil
msg ||= "Failed refutation, no message given"
not assert(! test, msg)
end
##
# Fails if +obj+ is empty.
def refute_empty obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to not be empty" }
assert_respond_to obj, :empty?
refute obj.empty?, msg
end
##
# Fails if <tt>exp == act</tt>.
#
# For floats use refute_in_delta.
def refute_equal exp, act, msg = nil
msg = message(msg) {
"Expected #{mu_pp(act)} to not be equal to #{mu_pp(exp)}"
}
refute exp == act, msg
end
##
# For comparing Floats. Fails if +exp+ is within +delta+ of +act+.
#
# refute_in_delta Math::PI, (22.0 / 7.0)
def refute_in_delta exp, act, delta = 0.001, msg = nil
n = (exp - act).abs
msg = message(msg) {
"Expected |#{exp} - #{act}| (#{n}) to not be <= #{delta}"
}
refute delta >= n, msg
end
##
# For comparing Floats. Fails if +exp+ and +act+ have a relative error
# less than +epsilon+.
def refute_in_epsilon a, b, epsilon = 0.001, msg = nil
refute_in_delta a, b, a * epsilon, msg
end
##
# Fails if +collection+ includes +obj+.
def refute_includes collection, obj, msg = nil
msg = message(msg) {
"Expected #{mu_pp(collection)} to not include #{mu_pp(obj)}"
}
assert_respond_to collection, :include?
refute collection.include?(obj), msg
end
##
# Fails if +obj+ is an instance of +cls+.
def refute_instance_of cls, obj, msg = nil
msg = message(msg) {
"Expected #{mu_pp(obj)} to not be an instance of #{cls}"
}
refute obj.instance_of?(cls), msg
end
##
# Fails if +obj+ is a kind of +cls+.
def refute_kind_of cls, obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to not be a kind of #{cls}" }
refute obj.kind_of?(cls), msg
end
##
# Fails if +matcher+ <tt>=~</tt> +obj+.
def refute_match matcher, obj, msg = nil
msg = message(msg) {"Expected #{mu_pp matcher} to not match #{mu_pp obj}"}
assert_respond_to matcher, :"=~"
matcher = Regexp.new Regexp.escape matcher if String === matcher
refute matcher =~ obj, msg
end
##
# Fails if +obj+ is nil.
def refute_nil obj, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to not be nil" }
refute obj.nil?, msg
end
##
# Fails if +o1+ is not +op+ +o2+. Eg:
#
# refute_operator 1, :>, 2 #=> pass
# refute_operator 1, :<, 2 #=> fail
def refute_operator o1, op, o2 = UNDEFINED, msg = nil
return refute_predicate o1, op, msg if UNDEFINED == o2
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op} #{mu_pp(o2)}"}
refute o1.__send__(op, o2), msg
end
##
# For testing with predicates.
#
# refute_predicate str, :empty?
#
# This is really meant for specs and is front-ended by refute_operator:
#
# str.wont_be :empty?
def refute_predicate o1, op, msg = nil
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op}" }
refute o1.__send__(op), msg
end
##
# Fails if +obj+ responds to the message +meth+.
def refute_respond_to obj, meth, msg = nil
msg = message(msg) { "Expected #{mu_pp(obj)} to not respond to #{meth}" }
refute obj.respond_to?(meth), msg
end
##
# Fails if +exp+ is the same (by object identity) as +act+.
def refute_same exp, act, msg = nil
msg = message(msg) {
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
"Expected %s (oid=%d) to not be the same as %s (oid=%d)" % data
}
refute exp.equal?(act), msg
end
##
# Skips the current run. If run in verbose-mode, the skipped run
# gets listed at the end of the run but doesn't cause a failure
# exit code.
def skip msg = nil, bt = caller
msg ||= "Skipped, no message given"
@skip = true
raise Minitest::Skip, msg, bt
end
##
# Was this testcase skipped? Meant for #teardown.
def skipped?
defined?(@skip) and @skip
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/minitest/benchmark.rb | vendored-minitest/minitest/benchmark.rb | # await: *await*
require 'minitest/unit'
require 'minitest/spec'
module Minitest
##
# Subclass Benchmark to create your own benchmark runs. Methods
# starting with "bench_" get executed on a per-class.
#
# See Minitest::Assertions
class Benchmark < Test
def self.io # :nodoc:
@io
end
def io # :nodoc:
self.class.io
end
def self.run reporter, options = {} # :nodoc:
# NOTE: this is truly horrible... but I don't see a way around this ATM.
@io = reporter.reporters.first.io
super
end
def self.runnable_methods # :nodoc:
methods_matching(/^bench_/)
end
##
# Returns a set of ranges stepped exponentially from +min+ to
# +max+ by powers of +base+. Eg:
#
# bench_exp(2, 16, 2) # => [2, 4, 8, 16]
def self.bench_exp min, max, base = 10
min = (Math.log10(min) / Math.log10(base)).to_i
max = (Math.log10(max) / Math.log10(base)).to_i
(min..max).map { |m| base ** m }.to_a
end
##
# Returns a set of ranges stepped linearly from +min+ to +max+ by
# +step+. Eg:
#
# bench_linear(20, 40, 10) # => [20, 30, 40]
def self.bench_linear min, max, step = 10
(min..max).step(step).to_a
rescue LocalJumpError # 1.8.6
r = []; (min..max).step(step) { |n| r << n }; r
end
##
# Specifies the ranges used for benchmarking for that class.
# Defaults to exponential growth from 1 to 10k by powers of 10.
# Override if you need different ranges for your benchmarks.
#
# See also: ::bench_exp and ::bench_linear.
def self.bench_range
bench_exp 1, 10_000
end
##
# Runs the given +work+, gathering the times of each run. Range
# and times are then passed to a given +validation+ proc. Outputs
# the benchmark name and times in tab-separated format, making it
# easy to paste into a spreadsheet for graphing or further
# analysis.
#
# Ranges are specified by ::bench_range.
#
# Eg:
#
# def bench_algorithm
# validation = proc { |x, y| ... }
# assert_performance validation do |n|
# @obj.algorithm(n)
# end
# end
def assert_performance validation, &work
range = self.class.bench_range
io.print "#{self.name}"
times = []
range.each_await do |x|
GC.start
t0 = Time.now
instance_exec(x, &work).await
t = Time.now - t0
io.print "\t%9.6f" % t
times << t
end
io.puts
validation[range, times]
end
##
# Runs the given +work+ and asserts that the times gathered fit to
# match a constant rate (eg, linear slope == 0) within a given
# +threshold+. Note: because we're testing for a slope of 0, R^2
# is not a good determining factor for the fit, so the threshold
# is applied against the slope itself. As such, you probably want
# to tighten it from the default.
#
# See http://www.graphpad.com/curvefit/goodness_of_fit.htm for
# more details.
#
# Fit is calculated by #fit_linear.
#
# Ranges are specified by ::bench_range.
#
# Eg:
#
# def bench_algorithm
# assert_performance_constant 0.9999 do |n|
# @obj.algorithm(n)
# end
# end
def assert_performance_constant threshold = 0.99, &work
validation = proc do |range, times|
a, b, rr = fit_linear range, times
assert_in_delta 0, b, 1 - threshold
[a, b, rr]
end
assert_performance(validation, &work).await
end
##
# Runs the given +work+ and asserts that the times gathered fit to
# match a exponential curve within a given error +threshold+.
#
# Fit is calculated by #fit_exponential.
#
# Ranges are specified by ::bench_range.
#
# Eg:
#
# def bench_algorithm
# assert_performance_exponential 0.9999 do |n|
# @obj.algorithm(n)
# end
# end
def assert_performance_exponential threshold = 0.99, &work
assert_performance(validation_for_fit(:exponential, threshold), &work).await
end
##
# Runs the given +work+ and asserts that the times gathered fit to
# match a logarithmic curve within a given error +threshold+.
#
# Fit is calculated by #fit_logarithmic.
#
# Ranges are specified by ::bench_range.
#
# Eg:
#
# def bench_algorithm
# assert_performance_logarithmic 0.9999 do |n|
# @obj.algorithm(n)
# end
# end
def assert_performance_logarithmic threshold = 0.99, &work
assert_performance(validation_for_fit(:logarithmic, threshold), &work).await
end
##
# Runs the given +work+ and asserts that the times gathered fit to
# match a straight line within a given error +threshold+.
#
# Fit is calculated by #fit_linear.
#
# Ranges are specified by ::bench_range.
#
# Eg:
#
# def bench_algorithm
# assert_performance_linear 0.9999 do |n|
# @obj.algorithm(n)
# end
# end
def assert_performance_linear threshold = 0.99, &work
assert_performance(validation_for_fit(:linear, threshold), &work).await
end
##
# Runs the given +work+ and asserts that the times gathered curve
# fit to match a power curve within a given error +threshold+.
#
# Fit is calculated by #fit_power.
#
# Ranges are specified by ::bench_range.
#
# Eg:
#
# def bench_algorithm
# assert_performance_power 0.9999 do |x|
# @obj.algorithm
# end
# end
def assert_performance_power threshold = 0.99, &work
assert_performance(validation_for_fit(:power, threshold), &work).await
end
##
# Takes an array of x/y pairs and calculates the general R^2 value.
#
# See: http://en.wikipedia.org/wiki/Coefficient_of_determination
def fit_error xys
y_bar = sigma(xys) { |x, y| y } / xys.size.to_f
ss_tot = sigma(xys) { |x, y| (y - y_bar) ** 2 }
ss_err = sigma(xys) { |x, y| (yield(x) - y) ** 2 }
1 - (ss_err / ss_tot)
end
##
# To fit a functional form: y = ae^(bx).
#
# Takes x and y values and returns [a, b, r^2].
#
# See: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
def fit_exponential xs, ys
n = xs.size
xys = xs.zip(ys)
sxlny = sigma(xys) { |x,y| x * Math.log(y) }
slny = sigma(xys) { |x,y| Math.log(y) }
sx2 = sigma(xys) { |x,y| x * x }
sx = sigma xs
c = n * sx2 - sx ** 2
a = (slny * sx2 - sx * sxlny) / c
b = ( n * sxlny - sx * slny ) / c
return Math.exp(a), b, fit_error(xys) { |x| Math.exp(a + b * x) }
end
##
# To fit a functional form: y = a + b*ln(x).
#
# Takes x and y values and returns [a, b, r^2].
#
# See: http://mathworld.wolfram.com/LeastSquaresFittingLogarithmic.html
def fit_logarithmic xs, ys
n = xs.size
xys = xs.zip(ys)
slnx2 = sigma(xys) { |x,y| Math.log(x) ** 2 }
slnx = sigma(xys) { |x,y| Math.log(x) }
sylnx = sigma(xys) { |x,y| y * Math.log(x) }
sy = sigma(xys) { |x,y| y }
c = n * slnx2 - slnx ** 2
b = ( n * sylnx - sy * slnx ) / c
a = (sy - b * slnx) / n
return a, b, fit_error(xys) { |x| a + b * Math.log(x) }
end
##
# Fits the functional form: a + bx.
#
# Takes x and y values and returns [a, b, r^2].
#
# See: http://mathworld.wolfram.com/LeastSquaresFitting.html
def fit_linear xs, ys
n = xs.size
xys = xs.zip(ys)
sx = sigma xs
sy = sigma ys
sx2 = sigma(xs) { |x| x ** 2 }
sxy = sigma(xys) { |x,y| x * y }
c = n * sx2 - sx**2
a = (sy * sx2 - sx * sxy) / c
b = ( n * sxy - sx * sy ) / c
return a, b, fit_error(xys) { |x| a + b * x }
end
##
# To fit a functional form: y = ax^b.
#
# Takes x and y values and returns [a, b, r^2].
#
# See: http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
def fit_power xs, ys
n = xs.size
xys = xs.zip(ys)
slnxlny = sigma(xys) { |x, y| Math.log(x) * Math.log(y) }
slnx = sigma(xs) { |x | Math.log(x) }
slny = sigma(ys) { | y| Math.log(y) }
slnx2 = sigma(xs) { |x | Math.log(x) ** 2 }
b = (n * slnxlny - slnx * slny) / (n * slnx2 - slnx ** 2);
a = (slny - b * slnx) / n
return Math.exp(a), b, fit_error(xys) { |x| (Math.exp(a) * (x ** b)) }
end
##
# Enumerates over +enum+ mapping +block+ if given, returning the
# sum of the result. Eg:
#
# sigma([1, 2, 3]) # => 1 + 2 + 3 => 7
# sigma([1, 2, 3]) { |n| n ** 2 } # => 1 + 4 + 9 => 14
def sigma enum, &block
enum = enum.map(&block) if block
enum.inject { |sum, n| sum + n }
end
##
# Returns a proc that calls the specified fit method and asserts
# that the error is within a tolerable threshold.
def validation_for_fit msg, threshold
proc do |range, times|
a, b, rr = send "fit_#{msg}", range, times
assert_operator rr, :>=, threshold
[a, b, rr]
end
end
end
end
module Minitest
##
# The spec version of Minitest::Benchmark.
class BenchSpec < Benchmark
extend Minitest::Spec::DSL
##
# This is used to define a new benchmark method. You usually don't
# use this directly and is intended for those needing to write new
# performance curve fits (eg: you need a specific polynomial fit).
#
# See ::bench_performance_linear for an example of how to use this.
def self.bench name, &block
define_method "bench_#{name.gsub(/\W+/, '_')}", &block
end
##
# Specifies the ranges used for benchmarking for that class.
#
# bench_range do
# bench_exp(2, 16, 2)
# end
#
# See Minitest::Benchmark#bench_range for more details.
def self.bench_range &block
return super unless block
meta = (class << self; self; end)
meta.send :define_method, "bench_range", &block
end
##
# Create a benchmark that verifies that the performance is linear.
#
# describe "my class Bench" do
# bench_performance_linear "fast_algorithm", 0.9999 do |n|
# @obj.fast_algorithm(n)
# end
# end
def self.bench_performance_linear name, threshold = 0.99, &work
bench name do
assert_performance_linear threshold, &work
end
end
##
# Create a benchmark that verifies that the performance is constant.
#
# describe "my class Bench" do
# bench_performance_constant "zoom_algorithm!" do |n|
# @obj.zoom_algorithm!(n)
# end
# end
def self.bench_performance_constant name, threshold = 0.99, &work
bench name do
assert_performance_constant threshold, &work
end
end
##
# Create a benchmark that verifies that the performance is exponential.
#
# describe "my class Bench" do
# bench_performance_exponential "algorithm" do |n|
# @obj.algorithm(n)
# end
# end
def self.bench_performance_exponential name, threshold = 0.99, &work
bench name do
assert_performance_exponential threshold, &work
end
end
end
Minitest::Spec.register_spec_type(/Bench(mark)?$/, Minitest::BenchSpec)
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/minitest/expectations.rb | vendored-minitest/minitest/expectations.rb | ##
# It's where you hide your "assertions".
#
# Please note, because of the way that expectations are implemented,
# all expectations (eg must_equal) are dependent upon a thread local
# variable +:current_spec+. If your specs rely on mixing threads into
# the specs themselves, you're better off using assertions. For
# example:
#
# it "should still work in threads" do
# my_threaded_thingy do
# (1+1).must_equal 2 # bad
# assert_equal 2, 1+1 # good
# end
# end
module Minitest::Expectations
##
# See Minitest::Assertions#assert_empty.
#
# collection.must_be_empty
#
# :method: must_be_empty
infect_an_assertion :assert_empty, :must_be_empty, :unary
##
# See Minitest::Assertions#assert_equal
#
# a.must_equal b
#
# :method: must_equal
infect_an_assertion :assert_equal, :must_equal
##
# See Minitest::Assertions#assert_in_delta
#
# n.must_be_close_to m [, delta]
#
# :method: must_be_close_to
infect_an_assertion :assert_in_delta, :must_be_close_to
alias :must_be_within_delta :must_be_close_to # :nodoc:
##
# See Minitest::Assertions#assert_in_epsilon
#
# n.must_be_within_epsilon m [, epsilon]
#
# :method: must_be_within_epsilon
infect_an_assertion :assert_in_epsilon, :must_be_within_epsilon
##
# See Minitest::Assertions#assert_includes
#
# collection.must_include obj
#
# :method: must_include
infect_an_assertion :assert_includes, :must_include, :reverse
##
# See Minitest::Assertions#assert_instance_of
#
# obj.must_be_instance_of klass
#
# :method: must_be_instance_of
infect_an_assertion :assert_instance_of, :must_be_instance_of
##
# See Minitest::Assertions#assert_kind_of
#
# obj.must_be_kind_of mod
#
# :method: must_be_kind_of
infect_an_assertion :assert_kind_of, :must_be_kind_of
##
# See Minitest::Assertions#assert_match
#
# a.must_match b
#
# :method: must_match
infect_an_assertion :assert_match, :must_match
##
# See Minitest::Assertions#assert_nil
#
# obj.must_be_nil
#
# :method: must_be_nil
infect_an_assertion :assert_nil, :must_be_nil, :unary
##
# See Minitest::Assertions#assert_operator
#
# n.must_be :<=, 42
#
# This can also do predicates:
#
# str.must_be :empty?
#
# :method: must_be
infect_an_assertion :assert_operator, :must_be, :reverse
##
# See Minitest::Assertions#assert_output
#
# proc { ... }.must_output out_or_nil [, err]
#
# :method: must_output
infect_an_assertion :assert_output, :must_output
##
# See Minitest::Assertions#assert_raises
#
# proc { ... }.must_raise exception
#
# :method: must_raise
infect_an_assertion :assert_raises, :must_raise
##
# See Minitest::Assertions#assert_respond_to
#
# obj.must_respond_to msg
#
# :method: must_respond_to
infect_an_assertion :assert_respond_to, :must_respond_to, :reverse
##
# See Minitest::Assertions#assert_same
#
# a.must_be_same_as b
#
# :method: must_be_same_as
infect_an_assertion :assert_same, :must_be_same_as
##
# See Minitest::Assertions#assert_silent
#
# proc { ... }.must_be_silent
#
# :method: must_be_silent
infect_an_assertion :assert_silent, :must_be_silent
##
# See Minitest::Assertions#assert_throws
#
# proc { ... }.must_throw sym
#
# :method: must_throw
infect_an_assertion :assert_throws, :must_throw
##
# See Minitest::Assertions#refute_empty
#
# collection.wont_be_empty
#
# :method: wont_be_empty
infect_an_assertion :refute_empty, :wont_be_empty, :unary
##
# See Minitest::Assertions#refute_equal
#
# a.wont_equal b
#
# :method: wont_equal
infect_an_assertion :refute_equal, :wont_equal
##
# See Minitest::Assertions#refute_in_delta
#
# n.wont_be_close_to m [, delta]
#
# :method: wont_be_close_to
infect_an_assertion :refute_in_delta, :wont_be_close_to
alias :wont_be_within_delta :wont_be_close_to # :nodoc:
##
# See Minitest::Assertions#refute_in_epsilon
#
# n.wont_be_within_epsilon m [, epsilon]
#
# :method: wont_be_within_epsilon
infect_an_assertion :refute_in_epsilon, :wont_be_within_epsilon
##
# See Minitest::Assertions#refute_includes
#
# collection.wont_include obj
#
# :method: wont_include
infect_an_assertion :refute_includes, :wont_include, :reverse
##
# See Minitest::Assertions#refute_instance_of
#
# obj.wont_be_instance_of klass
#
# :method: wont_be_instance_of
infect_an_assertion :refute_instance_of, :wont_be_instance_of
##
# See Minitest::Assertions#refute_kind_of
#
# obj.wont_be_kind_of mod
#
# :method: wont_be_kind_of
infect_an_assertion :refute_kind_of, :wont_be_kind_of
##
# See Minitest::Assertions#refute_match
#
# a.wont_match b
#
# :method: wont_match
infect_an_assertion :refute_match, :wont_match
##
# See Minitest::Assertions#refute_nil
#
# obj.wont_be_nil
#
# :method: wont_be_nil
infect_an_assertion :refute_nil, :wont_be_nil, :unary
##
# See Minitest::Assertions#refute_operator
#
# n.wont_be :<=, 42
#
# This can also do predicates:
#
# str.wont_be :empty?
#
# :method: wont_be
infect_an_assertion :refute_operator, :wont_be, :reverse
##
# See Minitest::Assertions#refute_respond_to
#
# obj.wont_respond_to msg
#
# :method: wont_respond_to
infect_an_assertion :refute_respond_to, :wont_respond_to, :reverse
##
# See Minitest::Assertions#refute_same
#
# a.wont_be_same_as b
#
# :method: wont_be_same_as
infect_an_assertion :refute_same, :wont_be_same_as
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/minitest/spec.rb | vendored-minitest/minitest/spec.rb | require "minitest/test"
class Module # :nodoc:
def infect_an_assertion meth, new_name, dont_flip = false # :nodoc:
# warn "%-22p -> %p %p" % [meth, new_name, dont_flip]
dont_flip = !!dont_flip
self.class_eval do
define_method(new_name) do |*args|
case
when dont_flip
Minitest::Spec.current.send(meth, self, *args)
when Proc === self
Minitest::Spec.current.send(meth, *args, &self)
else
Minitest::Spec.current.send(meth, args.first, self, *args[1..-1])
end
end
end
# <<-EOM
# def #{new_name} *args
# case
# when #{dont_flip} then
# Minitest::Spec.current.#{meth}(self, *args)
# when Proc === self then
# Minitest::Spec.current.#{meth}(*args, &self)
# else
# Minitest::Spec.current.#{meth}(args.first, self, *args[1..-1])
# end
# end
# EOM
end
end
module Kernel # :nodoc:
##
# Describe a series of expectations for a given target +desc+.
#
# Defines a test class subclassing from either Minitest::Spec or
# from the surrounding describe's class. The surrounding class may
# subclass Minitest::Spec manually in order to easily share code:
#
# class MySpec < Minitest::Spec
# # ... shared code ...
# end
#
# class TestStuff < MySpec
# it "does stuff" do
# # shared code available here
# end
# describe "inner stuff" do
# it "still does stuff" do
# # ...and here
# end
# end
# end
#
# For more information on getting started with writing specs, see:
#
# http://www.rubyinside.com/a-minitestspec-tutorial-elegant-spec-style-testing-that-comes-with-ruby-5354.html
#
# For some suggestions on how to improve your specs, try:
#
# http://betterspecs.org
#
# but do note that several items there are debatable or specific to
# rspec.
#
# For more information about expectations, see Minitest::Expectations.
def describe desc, *additional_desc, &block # :doc:
stack = Minitest::Spec.describe_stack
name = [stack.last, desc, *additional_desc].compact.join("::")
sclas = stack.last || if Class === self && is_a?(Minitest::Spec::DSL) then
self
else
Minitest::Spec.spec_type desc, *additional_desc
end
cls = sclas.create name, desc
stack.push cls
cls.class_eval(&block)
stack.pop
cls
end
private :describe
end
##
# Minitest::Spec -- The faster, better, less-magical spec framework!
#
# For a list of expectations, see Minitest::Expectations.
class Minitest::Spec < Minitest::Test
def self.current # :nodoc:
Thread.current[:current_spec]
end
def initialize name # :nodoc:
super
Thread.current[:current_spec] = self
end
##
# Oh look! A Minitest::Spec::DSL module! Eat your heart out DHH.
module DSL
##
# Contains pairs of matchers and Spec classes to be used to
# calculate the superclass of a top-level describe. This allows for
# automatically customizable spec types.
#
# See: register_spec_type and spec_type
TYPES = [[//, Minitest::Spec]]
##
# Register a new type of spec that matches the spec's description.
# This method can take either a Regexp and a spec class or a spec
# class and a block that takes the description and returns true if
# it matches.
#
# Eg:
#
# register_spec_type(/Controller$/, Minitest::Spec::Rails)
#
# or:
#
# register_spec_type(Minitest::Spec::RailsModel) do |desc|
# desc.superclass == ActiveRecord::Base
# end
def register_spec_type(*args, &block)
if block then
matcher, klass = block, args.first
else
matcher, klass = *args
end
TYPES.unshift [matcher, klass]
end
##
# Figure out the spec class to use based on a spec's description. Eg:
#
# spec_type("BlahController") # => Minitest::Spec::Rails
def spec_type desc, *additional
TYPES.find { |matcher, klass|
if matcher.respond_to? :call then
matcher.call desc, *additional
else
matcher === desc.to_s
end
}.last
end
def describe_stack # :nodoc:
Thread.current[:describe_stack] ||= []
end
##
# Returns the children of this spec.
def children
@children ||= []
end
def nuke_test_methods! # :nodoc:
self.public_instance_methods.grep(/^test_/).each do |name|
self.send :undef_method, name
end
end
##
# Define a 'before' action. Inherits the way normal methods should.
#
# NOTE: +type+ is ignored and is only there to make porting easier.
#
# Equivalent to Minitest::Test#setup.
def before type = nil, &block
define_method :setup do
super()
self.instance_eval(&block)
end
end
##
# Define an 'after' action. Inherits the way normal methods should.
#
# NOTE: +type+ is ignored and is only there to make porting easier.
#
# Equivalent to Minitest::Test#teardown.
def after type = nil, &block
define_method :teardown do
self.instance_eval(&block)
super()
end
end
##
# Define an expectation with name +desc+. Name gets morphed to a
# proper test method name. For some freakish reason, people who
# write specs don't like class inheritance, so this goes way out of
# its way to make sure that expectations aren't inherited.
#
# This is also aliased to #specify and doesn't require a +desc+ arg.
#
# Hint: If you _do_ want inheritance, use minitest/test. You can mix
# and match between assertions and expectations as much as you want.
def it desc = "anonymous", &block
block ||= proc { skip "(no tests defined)" }
@specs ||= 0
@specs += 1
name = "test_%04d_%s" % [ @specs, desc ]
undef_klasses = self.children.reject { |c| c.public_method_defined? name }
define_method name, &block
undef_klasses.each do |undef_klass|
undef_klass.send :undef_method, name
end
name
end
##
# Essentially, define an accessor for +name+ with +block+.
#
# Why use let instead of def? I honestly don't know.
def let name, &block
name = name.to_s
pre, post = "let '#{name}' cannot ", ". Please use another name."
methods = Minitest::Spec.instance_methods.map(&:to_s) - %w[subject]
raise ArgumentError, "#{pre}begin with 'test'#{post}" if
name =~ /\Atest/
raise ArgumentError, "#{pre}override a method in Minitest::Spec#{post}" if
methods.include? name
define_method name do
@_memoized ||= {}
@_memoized.fetch(name) { |k| @_memoized[k] = instance_eval(&block) }
end
end
##
# Another lazy man's accessor generator. Made even more lazy by
# setting the name for you to +subject+.
def subject &block
let :subject, &block
end
def create name, desc # :nodoc:
cls = Class.new(self) do
@name = name
@desc = desc
nuke_test_methods!
end
children << cls
cls
end
def name # :nodoc:
defined?(@name) ? @name : super
end
def to_s # :nodoc:
name # Can't alias due to 1.8.7, not sure why
end
# :stopdoc:
attr_reader :desc
alias :specify :it
module InstanceMethods
def before_setup
super
Thread.current[:current_spec] = self
end
end
def self.extended obj
obj.send :include, InstanceMethods
end
# :startdoc:
end
extend DSL
TYPES = DSL::TYPES # :nodoc:
end
require "minitest/expectations"
class Object # :nodoc:
include Minitest::Expectations unless ENV["MT_NO_EXPECTATIONS"]
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/minitest/autorun.rb | vendored-minitest/minitest/autorun.rb | # begin
# require "rubygems"
# gem "minitest"
# rescue Gem::LoadError
# # do nothing
# end
require "minitest"
require "minitest/spec"
require "minitest/mock"
Minitest.autorun
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/minitest/mock.rb | vendored-minitest/minitest/mock.rb | class MockExpectationError < StandardError; end # :nodoc:
module Minitest # :nodoc:
##
# A simple and clean mock object framework.
#
# All mock objects are an instance of Mock
class Mock
alias :__respond_to? :respond_to?
overridden_methods = %w(
===
inspect
object_id
public_send
respond_to_missing?
send
to_s
)
instance_methods.each do |m|
undef_method m unless overridden_methods.include?(m.to_s) || m =~ /^__/
end
overridden_methods.map(&:to_sym).each do |method_id|
define_method method_id do |*args, &b|
if @expected_calls.has_key? method_id then
method_missing(method_id, *args, &b)
else
super(*args, &b)
end
end
end
def initialize # :nodoc:
@expected_calls = Hash.new { |calls, name| calls[name] = [] }
@actual_calls = Hash.new { |calls, name| calls[name] = [] }
end
##
# Expect that method +name+ is called, optionally with +args+ or a
# +blk+, and returns +retval+.
#
# @mock.expect(:meaning_of_life, 42)
# @mock.meaning_of_life # => 42
#
# @mock.expect(:do_something_with, true, [some_obj, true])
# @mock.do_something_with(some_obj, true) # => true
#
# @mock.expect(:do_something_else, true) do |a1, a2|
# a1 == "buggs" && a2 == :bunny
# end
#
# +args+ is compared to the expected args using case equality (ie, the
# '===' operator), allowing for less specific expectations.
#
# @mock.expect(:uses_any_string, true, [String])
# @mock.uses_any_string("foo") # => true
# @mock.verify # => true
#
# @mock.expect(:uses_one_string, true, ["foo"])
# @mock.uses_one_string("bar") # => true
# @mock.verify # => raises MockExpectationError
def expect(name, retval, args=[], &blk)
name = name.to_sym
if block_given?
raise ArgumentError, "args ignored when block given" unless args.empty?
@expected_calls[name] << { :retval => retval, :block => blk }
else
raise ArgumentError, "args must be an array" unless Array === args
@expected_calls[name] << { :retval => retval, :args => args }
end
self
end
def __call name, data # :nodoc:
case data
when Hash then
"#{name}(#{data[:args].inspect[1..-2]}) => #{data[:retval].inspect}"
else
data.map { |d| __call name, d }.join ", "
end
end
##
# Verify that all methods were called as expected. Raises
# +MockExpectationError+ if the mock object was not called as
# expected.
def verify
@expected_calls.each do |name, calls|
calls.each do |expected|
msg1 = "expected #{__call name, expected}"
msg2 = "#{msg1}, got [#{__call name, @actual_calls[name]}]"
raise MockExpectationError, msg2 if
@actual_calls.has_key?(name) and
not @actual_calls[name].include?(expected)
raise MockExpectationError, msg1 unless
@actual_calls.has_key?(name) and
@actual_calls[name].include?(expected)
end
end
true
end
def method_missing(sym, *args, &block) # :nodoc:
unless @expected_calls.has_key?(sym) then
raise NoMethodError, "unmocked method %p, expected one of %p" %
[sym, @expected_calls.keys.sort_by(&:to_s)]
end
index = @actual_calls[sym].length
expected_call = @expected_calls[sym][index]
unless expected_call then
raise MockExpectationError, "No more expects available for %p: %p" %
[sym, args]
end
expected_args, retval, val_block =
expected_call.values_at(:args, :retval, :block)
if val_block then
raise MockExpectationError, "mocked method %p failed block w/ %p" %
[sym, args] unless val_block.call(*args, &block)
# keep "verify" happy
@actual_calls[sym] << expected_call
return retval
end
if expected_args.size != args.size then
raise ArgumentError, "mocked method %p expects %d arguments, got %d" %
[sym, expected_args.size, args.size]
end
fully_matched = expected_args.zip(args).all? { |mod, a|
mod === a or mod == a
}
unless fully_matched then
raise MockExpectationError, "mocked method %p called with unexpected arguments %p" %
[sym, args]
end
@actual_calls[sym] << {
:retval => retval,
:args => expected_args.zip(args).map { |mod, a| mod === a ? mod : a }
}
retval
end
def respond_to?(sym, include_private = false) # :nodoc:
return true if @expected_calls.has_key? sym.to_sym
return __respond_to?(sym, include_private)
end
end
end
class Object # :nodoc:
##
# Add a temporary stubbed method replacing +name+ for the duration
# of the +block+. If +val_or_callable+ responds to #call, then it
# returns the result of calling it, otherwise returns the value
# as-is. If stubbed method yields a block, +block_args+ will be
# passed along. Cleans up the stub at the end of the +block+. The
# method +name+ must exist before stubbing.
#
# def test_stale_eh
# obj_under_test = Something.new
# refute obj_under_test.stale?
#
# Time.stub :now, Time.at(0) do
# assert obj_under_test.stale?
# end
# end
#
def stub name, val_or_callable, *block_args, &block
new_name = "__minitest_stub__#{name}"
metaclass = class << self; self; end
if respond_to? name and not methods.map(&:to_s).include? name.to_s then
metaclass.send :define_method, name do |*args|
super(*args)
end
end
metaclass.send :alias_method, new_name, name
metaclass.send :define_method, name do |*args, &blk|
ret = if val_or_callable.respond_to? :call then
val_or_callable.call(*args)
else
val_or_callable
end
blk.call(*block_args) if blk
ret
end
yield self
ensure
metaclass.send :undef_method, name
metaclass.send :alias_method, name, new_name
metaclass.send :undef_method, new_name
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/vendored-minitest/test/unit.rb | vendored-minitest/test/unit.rb | # test/unit compatibility layer using minitest.
require 'minitest/autorun'
module Test
module Unit
class TestCase < Minitest::Test
alias assert_raise assert_raises
def assert_nothing_raised(*)
yield
end
def assert_raise_with_message(exception, err_message, msg = nil)
err = assert_raises(exception, msg) { yield }
if err_message.is_a?(Regexp)
assert_matches err_message, err.message
else
assert_equal err_message, err.message
end
end
def assert_not_equal exp, act, msg = nil
msg = message(msg, E) { diff exp, act }
assert exp != act, msg
end
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_page_link.rb | test/test_mechanize_page_link.rb | # coding: utf-8
# frozen_string_literal: true
require 'mechanize/test_case'
puts "Nokogiri::VERSION_INFO: #{Nokogiri::VERSION_INFO}"
class TestMechanizePageLink < Mechanize::TestCase
WINDOWS_1255 = <<-HTML
<meta http-equiv="content-type" content="text/html; charset=windows-1255">
<title>hi</title>
HTML
BAD = <<-HTML.dup
<meta http-equiv="content-type" content="text/html; charset=windows-1255">
<title>Bia\xB3ystok</title>
HTML
BAD.force_encoding Encoding::BINARY if defined? Encoding
SJIS_TITLE = "\x83\x65\x83\x58\x83\x67"
SJIS_AFTER_TITLE = <<-HTML.dup
<title>#{SJIS_TITLE}</title>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
HTML
SJIS_AFTER_TITLE.force_encoding Encoding::BINARY if defined? Encoding
SJIS_BAD_AFTER_TITLE = <<-HTML.dup
<title>#{SJIS_TITLE}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
HTML
SJIS_BAD_AFTER_TITLE.force_encoding Encoding::BINARY if defined? Encoding
UTF8_TITLE = 'テスト'
UTF8 = <<-HTML
<title>#{UTF8_TITLE}</title>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
HTML
ENCODING_ERROR_CLASS = Nokogiri::XML::SyntaxError
def setup
super
@uri = URI('http://example')
@res = { 'content-type' => 'text/html' }
@body = +'<title>hi</title>'
end
def util_page body = @body, res = @res
Mechanize::Page.new @uri, res, body && body.force_encoding(Encoding::BINARY), 200, @mech
end
def skip_if_nkf_dependency
if RUBY_ENGINE == 'jruby'
meth = caller_locations(1,1).first.base_label
skip "#{meth}: skipped because this feature currently depends on NKF"
end
end
def test_override_content_type
page = Mechanize::Page.new nil, {'content-type' => 'text/html'}, WINDOWS_1255
assert page
assert_equal 'text/html; charset=windows-1255', page.content_type
end
def test_canonical_uri
page = @mech.get("http://localhost/canonical_uri.html")
assert_equal(URI("http://localhost/canonical_uri"), page.canonical_uri)
page = @mech.get("http://localhost/file_upload.html")
assert_nil page.canonical_uri
end
def test_canonical_uri_unescaped
page = util_page(+<<-BODY)
<head>
<link rel="canonical" href="http://example/white space"/>
</head>
BODY
assert_equal @uri + '/white%20space', page.canonical_uri
end
def test_charset_from_content_type
charset = Mechanize::Page.__send__ :charset_from_content_type, 'text/html;charset=UTF-8'
assert_equal 'UTF-8', charset
end
def test_charset_from_bad_content_type
charset = Mechanize::Page.__send__ :charset_from_content_type, 'text/html'
assert_nil charset
end
def test_encoding
page = util_page WINDOWS_1255.dup
assert_equal 'windows-1255', page.encoding
end
def test_encoding_charset_after_title
page = util_page SJIS_AFTER_TITLE
assert_equal false, page.encoding_error?
assert_equal 'Shift_JIS', page.encoding
end
def test_encoding_charset_after_title_bad
skip_if_nkf_dependency
# https://gitlab.gnome.org/GNOME/libxml2/-/issues/543
skip if Nokogiri.uses_libxml?([">= 2.11.0", "< 2.12.0"])
page = util_page UTF8.dup
assert_equal false, page.encoding_error?
assert_equal "UTF-8", page.encoding
end
def test_encoding_charset_after_title_double_bad
skip_if_nkf_dependency
page = util_page SJIS_BAD_AFTER_TITLE
assert_equal false, page.encoding_error?
assert_equal 'SHIFT_JIS', page.encoding
end
def test_encoding_charset_bad
skip_if_nkf_dependency
# https://gitlab.gnome.org/GNOME/libxml2/-/issues/543
skip if Nokogiri.uses_libxml?([">= 2.11.0", "< 2.12.0"])
page = util_page(+"<title>#{UTF8_TITLE}</title>")
page.encodings.replace %w[
UTF-8
Shift_JIS
]
assert_equal false, page.encoding_error?
assert_equal 'UTF-8', page.encoding
end
def test_encoding_meta_charset
page = util_page(+"<meta charset='UTF-8'>")
assert_equal 'UTF-8', page.encoding
end
def test_encoding_equals
page = util_page
page.meta_refresh
assert page.instance_variable_get(:@meta_refresh)
page.encoding = 'UTF-8'
assert_nil page.instance_variable_get(:@meta_refresh)
assert_equal 'UTF-8', page.encoding
assert_equal 'UTF-8', page.parser.encoding
end
def test_page_encoding_error?
page = util_page
page.parser.errors.clear
assert_equal false, page.encoding_error?
end
def test_detect_libxml2error_indicate_encoding
page = util_page
page.parser.errors.clear
# error in libxml2-2.7.8/parser.c, HTMLparser.c or parserInternals.c
page.parser.errors = [ENCODING_ERROR_CLASS.new("Input is not proper UTF-8, indicate encoding !\n")]
assert_equal true, page.encoding_error?
end
def test_detect_libxml2error_invalid_char
page = util_page
page.parser.errors.clear
# error in libxml2-2.7.8/HTMLparser.c
page.parser.errors = [ENCODING_ERROR_CLASS.new("Invalid char in CDATA 0x%X\n")]
assert_equal true, page.encoding_error?
end
def test_detect_libxml2error_input_conversion_failed
page = util_page
page.parser.errors.clear
# error in libxml2-2.7.8/encoding.c
page.parser.errors = [ENCODING_ERROR_CLASS.new("input conversion failed due to input error\n")]
assert_equal true, page.encoding_error?
end
def test_detect_libxml2error_which_unsupported_by_mechanize
page = util_page
page.parser.errors.clear
# error in libxml2-2.7.8/HTMLparser.c
page.parser.errors = [ENCODING_ERROR_CLASS.new("encoder error\n")]
assert_equal false, page.encoding_error?
end
def test_encoding_equals_before_parser
# document has a bad encoding information - windows-1255
page = util_page BAD
# encoding is wrong, so user wants to force ISO-8859-2
page.encoding = 'ISO-8859-2'
assert_equal false, page.encoding_error?
assert_equal 'ISO-8859-2', page.encoding
assert_equal 'ISO-8859-2', page.parser.encoding
end
def test_encoding_equals_after_parser
# document has a bad encoding information - windows-1255
page = util_page BAD
page.parser
# autodetection sets encoding to windows-1255
assert_equal 'windows-1255', page.encoding
# believe in yourself, not machine
assert_equal false, page.encoding_error?
# encoding is wrong, so user wants to force ISO-8859-2
page.encoding = 'ISO-8859-2'
assert_equal false, page.encoding_error?
assert_equal 'ISO-8859-2', page.encoding
assert_equal 'ISO-8859-2', page.parser.encoding
end
def test_frames_with
page = @mech.get("http://localhost/frame_test.html")
assert_equal(3, page.frames.size)
find_orig = page.frames.find_all { |f| f.name == 'frame1' }
find1 = page.frames_with(:name => 'frame1')
find_orig.zip(find1).each { |a,b|
assert_equal(a, b)
}
end
def test_links_with_dom_id
page = @mech.get("http://localhost/tc_links.html")
link = page.links_with(:dom_id => 'bold_aaron_link')
link_by_id = page.links_with(:id => 'bold_aaron_link')
assert_equal(1, link.length)
assert_equal('Aaron Patterson', link.first.text)
assert_equal(link, link_by_id)
end
def test_links_with_dom_class
page = @mech.get("http://localhost/tc_links.html")
link = page.links_with(:dom_class => 'thing_link')
link_by_class = page.links_with(:class => 'thing_link')
assert_equal(1, link.length)
assert_equal(link, link_by_class)
end
def test_link_with_encoded_space
page = @mech.get("http://localhost/tc_links.html")
link = page.link_with(:text => 'encoded space')
page = @mech.click link
end
def test_link_with_space
page = @mech.get("http://localhost/tc_links.html")
link = page.link_with(:text => 'not encoded space')
page = @mech.click link
end
def test_link_with_unusual_characters
page = @mech.get("http://localhost/tc_links.html")
link = page.link_with(:text => 'unusual characters')
@mech.click link
# HACK no assertion
end
def test_links
page = @mech.get("http://localhost/find_link.html")
assert_equal(18, page.links.length)
end unless RUBY_ENGINE == 'jruby' # NekoHTML does not parse FRAME outside of FRAMESET
def test_links_with_bold
page = @mech.get("http://localhost/tc_links.html")
link = page.links_with(:text => /Bold Dude/)
assert_equal(1, link.length)
assert_equal('Bold Dude', link.first.text)
assert_equal [], link.first.rel
assert !link.first.rel?('me')
assert !link.first.rel?('nofollow')
link = page.links_with(:text => 'Aaron James Patterson')
assert_equal(1, link.length)
assert_equal('Aaron James Patterson', link.first.text)
assert_equal ['me'], link.first.rel
assert link.first.rel?('me')
assert !link.first.rel?('nofollow')
link = page.links_with(:text => 'Aaron Patterson')
assert_equal(1, link.length)
assert_equal('Aaron Patterson', link.first.text)
assert_equal ['me', 'nofollow'], link.first.rel
assert link.first.rel?('me')
assert link.first.rel?('nofollow')
link = page.links_with(:text => 'Ruby Rocks!')
assert_equal(1, link.length)
assert_equal('Ruby Rocks!', link.first.text)
end
def test_meta_refresh
page = @mech.get("http://localhost/find_link.html")
assert_equal(3, page.meta_refresh.length)
assert_equal(%w{
http://www.drphil.com/
http://www.upcase.com/
http://tenderlovemaking.com/ }.sort,
page.meta_refresh.map { |x| x.href.downcase }.sort)
end
def test_title
page = util_page
assert_equal('hi', page.title)
end
def test_title_none
page = util_page(+'') # invalid HTML
assert_nil(page.title)
end
def test_page_decoded_with_charset
page = util_page @body, 'content-type' => 'text/html; charset=EUC-JP'
assert_equal 'EUC-JP', page.encoding
assert_equal 'EUC-JP', page.parser.encoding
end
def test_form
page = @mech.get("http://localhost/tc_form_action.html")
form = page.form(:name => 'post_form1')
assert form
yielded = false
form = page.form(:name => 'post_form1') { |f|
yielded = true
assert f
assert_equal(form, f)
}
assert yielded
form_by_action = page.form(:action => '/form_post?a=b&b=c')
assert form_by_action
assert_equal(form, form_by_action)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_form_check_box.rb | test/test_mechanize_form_check_box.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFormCheckBox < Mechanize::TestCase
def setup
super
@page = @mech.get('http://localhost/tc_checkboxes.html')
end
def test_search
form = @page.forms.first
checkbox = form.checkbox_with(name: 'green')
assert_equal('green', checkbox.name)
assert_equal(checkbox, form.checkbox_with('green'))
assert_equal(checkbox, form.checkbox_with(search: 'input[@type=checkbox][@name=green]'))
end
def test_check
form = @page.forms.first
form.checkbox_with(:name => 'green').check
assert(form.checkbox_with(:name => 'green').checked)
%w{ red blue yellow brown }.each do |color|
assert_equal(false, form.checkbox_with(:name => color).checked)
end
end
def test_uncheck
form = @page.forms.first
checkbox = form.checkbox_with(:name => 'green')
checkbox.check
assert form.checkbox_with(:name => 'green').checked
checkbox.uncheck
assert !form.checkbox_with(:name => 'green').checked
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_cookie_jar.rb | test/test_mechanize_cookie_jar.rb | # frozen_string_literal: true
require 'mechanize/test_case'
require 'fileutils'
class TestMechanizeCookieJar < Mechanize::TestCase
def setup
super
@jar = Mechanize::CookieJar.new
@jar.extend Minitest::Assertions
def @jar.add(*args)
capture_io { super }
end
def @jar.jar(*args)
result = nil
capture_io { result = super }
result
end
def @jar.save_as(*args)
result = nil
capture_io { result = super }
result
end
def @jar.clear!(*args)
result = nil
capture_io { result = super }
result
end
end
def cookie_values(options = {})
{
:name => 'Foo',
:value => 'Bar',
:path => '/',
:expires => Time.now + (10 * 86400),
:for_domain => true,
:domain => 'rubygems.org'
}.merge(options)
end
def test_two_cookies_same_domain_and_name_different_paths
url = URI 'http://rubygems.org/'
cookie = Mechanize::Cookie.new(cookie_values)
@jar.add(url, cookie)
@jar.add(url, Mechanize::Cookie.new(cookie_values(:path => '/onetwo')))
assert_equal(1, @jar.cookies(url).length)
assert_equal 2, @jar.cookies(URI('http://rubygems.org/onetwo')).length
end
def test_domain_case
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
@jar.add(url, Mechanize::Cookie.new(
cookie_values(:domain => 'rubygems.Org', :name => 'aaron')))
assert_equal(2, @jar.cookies(url).length)
url2 = URI 'http://rubygems.oRg/'
assert_equal(2, @jar.cookies(url2).length)
end
def test_host_only
url = URI.parse('http://rubygems.org/')
@jar.add(url, Mechanize::Cookie.new(
cookie_values(:domain => 'rubygems.org', :for_domain => false)))
assert_equal(1, @jar.cookies(url).length)
assert_equal(1, @jar.cookies(URI('http://rubygems.org/')).length)
assert_equal(1, @jar.cookies(URI('https://rubygems.org/')).length)
assert_equal(0, @jar.cookies(URI('http://www.rubygems.org/')).length)
end
def test_empty_value
values = cookie_values(:value => "")
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(values)
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
@jar.add url, Mechanize::Cookie.new(values.merge(:domain => 'rubygems.Org',
:name => 'aaron'))
assert_equal(2, @jar.cookies(url).length)
url2 = URI 'http://rubygems.oRg/'
assert_equal(2, @jar.cookies(url2).length)
end
def test_add_future_cookies
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
# Add the same cookie, and we should still only have one
@jar.add(url, Mechanize::Cookie.new(cookie_values))
assert_equal(1, @jar.cookies(url).length)
# Make sure we can get the cookie from different paths
assert_equal(1, @jar.cookies(URI('http://rubygems.org/login')).length)
# Make sure we can't get the cookie from different domains
assert_equal(0, @jar.cookies(URI('http://google.com/')).length)
end
def test_add_multiple_cookies
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
# Add the same cookie, and we should still only have one
@jar.add(url, Mechanize::Cookie.new(cookie_values(:name => 'Baz')))
assert_equal(2, @jar.cookies(url).length)
# Make sure we can get the cookie from different paths
assert_equal(2, @jar.cookies(URI('http://rubygems.org/login')).length)
# Make sure we can't get the cookie from different domains
assert_equal(0, @jar.cookies(URI('http://google.com/')).length)
end
def test_add_rejects_cookies_that_do_not_contain_an_embedded_dot
url = URI 'http://rubygems.org/'
tld_cookie = Mechanize::Cookie.new(cookie_values(:domain => '.org'))
@jar.add(url, tld_cookie)
# single dot domain is now treated as no domain
# single_dot_cookie = Mechanize::Cookie.new(cookie_values(:domain => '.'))
# @jar.add(url, single_dot_cookie)
assert_equal(0, @jar.cookies(url).length)
end
def test_fall_back_rules_for_local_domains
url = URI 'http://www.example.local'
tld_cookie = Mechanize::Cookie.new(cookie_values(:domain => '.local'))
@jar.add(url, tld_cookie)
assert_equal(0, @jar.cookies(url).length)
sld_cookie = Mechanize::Cookie.new(cookie_values(:domain => '.example.local'))
@jar.add(url, sld_cookie)
assert_equal(1, @jar.cookies(url).length)
end
def test_add_makes_exception_for_localhost
url = URI 'http://localhost'
tld_cookie = Mechanize::Cookie.new(cookie_values(:domain => 'localhost'))
@jar.add(url, tld_cookie)
assert_equal(1, @jar.cookies(url).length)
end
def test_add_cookie_for_the_parent_domain
url = URI 'http://x.foo.com'
cookie = Mechanize::Cookie.new(cookie_values(:domain => '.foo.com'))
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
end
def test_add_does_not_reject_cookies_from_a_nested_subdomain
url = URI 'http://y.x.foo.com'
cookie = Mechanize::Cookie.new(cookie_values(:domain => '.foo.com'))
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
end
def test_cookie_without_leading_dot_does_not_cause_substring_match
url = URI 'http://arubygems.org/'
cookie = Mechanize::Cookie.new(cookie_values(:domain => 'rubygems.org'))
@jar.add(url, cookie)
assert_equal(0, @jar.cookies(url).length)
end
def test_cookie_without_leading_dot_matches_subdomains
url = URI 'http://admin.rubygems.org/'
cookie = Mechanize::Cookie.new(cookie_values(:domain => 'rubygems.org'))
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
end
def test_cookies_with_leading_dot_match_subdomains
url = URI 'http://admin.rubygems.org/'
@jar.add(url, Mechanize::Cookie.new(cookie_values(:domain => '.rubygems.org')))
assert_equal(1, @jar.cookies(url).length)
end
def test_cookies_with_leading_dot_match_parent_domains
url = URI 'http://rubygems.org/'
@jar.add(url, Mechanize::Cookie.new(cookie_values(:domain => '.rubygems.org')))
assert_equal(1, @jar.cookies(url).length)
end
def test_cookies_with_leading_dot_match_parent_domains_exactly
url = URI 'http://arubygems.org/'
@jar.add(url, Mechanize::Cookie.new(cookie_values(:domain => '.rubygems.org')))
assert_equal(0, @jar.cookies(url).length)
end
def test_cookie_for_ipv4_address_matches_the_exact_ipaddress
url = URI 'http://192.168.0.1/'
cookie = Mechanize::Cookie.new(cookie_values(:domain => '192.168.0.1'))
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
end
def test_cookie_for_ipv4_address_does_not_cause_subdomain_match
url = URI 'http://192.168.0.1/'
cookie = Mechanize::Cookie.new(cookie_values(:domain => '.0.1'))
@jar.add(url, cookie)
assert_equal(0, @jar.cookies(url).length)
end
def test_cookie_for_ipv6_address_matches_the_exact_ipaddress
url = URI 'http://[fe80::0123:4567:89ab:cdef]/'
cookie = Mechanize::Cookie.new(cookie_values(:domain => '[fe80::0123:4567:89ab:cdef]'))
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
end
def test_cookies_dot
url = URI 'http://www.host.example/'
@jar.add(url,
Mechanize::Cookie.new(cookie_values(:domain => 'www.host.example')))
url = URI 'http://wwwxhost.example/'
assert_equal(0, @jar.cookies(url).length)
end
def test_clear_bang
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
@jar.add(url, cookie)
@jar.add(url, Mechanize::Cookie.new(cookie_values(:name => 'Baz')))
assert_equal(2, @jar.cookies(url).length)
@jar.clear!
assert_equal(0, @jar.cookies(url).length)
end
def test_save_cookies_yaml
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
s_cookie = Mechanize::Cookie.new(cookie_values(:name => 'Bar',
:expires => nil))
@jar.add(url, cookie)
@jar.add(url, s_cookie)
@jar.add(url, Mechanize::Cookie.new(cookie_values(:name => 'Baz')))
assert_equal(3, @jar.cookies(url).length)
in_tmpdir do
value = @jar.save_as("cookies.yml")
assert_same @jar, value
jar = Mechanize::CookieJar.new
jar.load("cookies.yml")
assert_equal(2, jar.cookies(url).length)
end
assert_equal(3, @jar.cookies(url).length)
end
def test_save_session_cookies_yaml
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
s_cookie = Mechanize::Cookie.new(cookie_values(:name => 'Bar',
:expires => nil))
@jar.add(url, cookie)
@jar.add(url, s_cookie)
@jar.add(url, Mechanize::Cookie.new(cookie_values(:name => 'Baz')))
assert_equal(3, @jar.cookies(url).length)
in_tmpdir do
@jar.save_as("cookies.yml", :format => :yaml, :session => true)
jar = Mechanize::CookieJar.new
jar.load("cookies.yml")
assert_equal(3, jar.cookies(url).length)
end
assert_equal(3, @jar.cookies(url).length)
end
def test_save_cookies_cookiestxt
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
s_cookie = Mechanize::Cookie.new(cookie_values(:name => 'Bar',
:expires => nil))
@jar.add(url, cookie)
@jar.add(url, s_cookie)
@jar.add(url, Mechanize::Cookie.new(cookie_values(:name => 'Baz')))
assert_equal(3, @jar.cookies(url).length)
in_tmpdir do
@jar.save_as("cookies.txt", :cookiestxt)
assert_match(/\A# (?:Netscape )?HTTP Cookie File$/, File.read("cookies.txt"))
jar = Mechanize::CookieJar.new
jar.load("cookies.txt", :cookiestxt)
assert_equal(2, jar.cookies(url).length)
end
in_tmpdir do
@jar.save_as("cookies.txt", :cookiestxt, :session => true)
assert_match(/\A# (?:Netscape )?HTTP Cookie File$/, File.read("cookies.txt"))
jar = Mechanize::CookieJar.new
jar.load("cookies.txt", :cookiestxt)
assert_equal(3, jar.cookies(url).length)
end
assert_equal(3, @jar.cookies(url).length)
end
def test_expire_cookies
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
# Add a second cookie
@jar.add(url, Mechanize::Cookie.new(cookie_values(:name => 'Baz')))
assert_equal(2, @jar.cookies(url).length)
# Make sure we can get the cookie from different paths
assert_equal(2, @jar.cookies(URI('http://rubygems.org/login')).length)
# Expire the first cookie
@jar.add(url, Mechanize::Cookie.new(
cookie_values(:expires => Time.now - (10 * 86400))))
assert_equal(1, @jar.cookies(url).length)
# Expire the second cookie
@jar.add(url, Mechanize::Cookie.new(
cookie_values( :name => 'Baz', :expires => Time.now - (10 * 86400))))
assert_equal(0, @jar.cookies(url).length)
end
def test_session_cookies
values = cookie_values(:expires => nil)
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(values)
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
# Add a second cookie
@jar.add(url, Mechanize::Cookie.new(values.merge(:name => 'Baz')))
assert_equal(2, @jar.cookies(url).length)
# Make sure we can get the cookie from different paths
assert_equal(2, @jar.cookies(URI('http://rubygems.org/login')).length)
# Expire the first cookie
@jar.add(url, Mechanize::Cookie.new(values.merge(:expires => Time.now - (10 * 86400))))
assert_equal(1, @jar.cookies(url).length)
# Expire the second cookie
@jar.add(url, Mechanize::Cookie.new(
values.merge(:name => 'Baz', :expires => Time.now - (10 * 86400))))
assert_equal(0, @jar.cookies(url).length)
# When given a URI with a blank path, CookieJar#cookies should return
# cookies with the path '/':
url = URI 'http://rubygems.org'
assert_equal '', url.path
assert_equal(0, @jar.cookies(url).length)
# Now add a cookie with the path set to '/':
@jar.add(url, Mechanize::Cookie.new(values.merge( :name => 'has_root_path',
:path => '/')))
assert_equal(1, @jar.cookies(url).length)
end
def test_paths
values = cookie_values(:path => "/login", :expires => nil)
url = URI 'http://rubygems.org/login'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(values)
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length)
# Add a second cookie
@jar.add(url, Mechanize::Cookie.new(values.merge( :name => 'Baz' )))
assert_equal(2, @jar.cookies(url).length)
# Make sure we don't get the cookie in a different path
assert_equal(0, @jar.cookies(URI('http://rubygems.org/hello')).length)
assert_equal(0, @jar.cookies(URI('http://rubygems.org/')).length)
# Expire the first cookie
@jar.add(url, Mechanize::Cookie.new(values.merge( :expires => Time.now - (10 * 86400))))
assert_equal(1, @jar.cookies(url).length)
# Expire the second cookie
@jar.add(url, Mechanize::Cookie.new(values.merge( :name => 'Baz',
:expires => Time.now - (10 * 86400))))
assert_equal(0, @jar.cookies(url).length)
end
def test_save_and_read_cookiestxt
url = URI 'http://rubygems.org/'
# Add one cookie with an expiration date in the future
cookie = Mechanize::Cookie.new(cookie_values)
@jar.add(url, cookie)
@jar.add(url, Mechanize::Cookie.new(cookie_values(:name => 'Baz')))
assert_equal(2, @jar.cookies(url).length)
in_tmpdir do
@jar.save_as("cookies.txt", :cookiestxt)
@jar.clear!
@jar.load("cookies.txt", :cookiestxt)
end
assert_equal(2, @jar.cookies(url).length)
end
def test_save_and_read_cookiestxt_with_session_cookies
url = URI 'http://rubygems.org/'
@jar.add(url, Mechanize::Cookie.new(cookie_values(:expires => nil)))
in_tmpdir do
@jar.save_as("cookies.txt", :cookiestxt)
@jar.clear!
@jar.load("cookies.txt", :cookiestxt)
end
assert_equal(0, @jar.cookies(url).length)
end
def test_prevent_command_injection_when_saving
skip if windows?
url = URI 'http://rubygems.org/'
path = '| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\''
@jar.add(url, Mechanize::Cookie.new(cookie_values))
in_tmpdir do
@jar.save_as(path, :cookiestxt)
assert_equal(false, File.exist?('vul.txt'))
end
end
def test_prevent_command_injection_when_loading
skip if windows?
url = URI 'http://rubygems.org/'
path = '| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\''
@jar.add(url, Mechanize::Cookie.new(cookie_values))
in_tmpdir do
@jar.save_as("cookies.txt", :cookiestxt)
@jar.clear!
assert_raises Errno::ENOENT do
@jar.load(path, :cookiestxt)
end
assert_equal(false, File.exist?('vul.txt'))
end
end
def test_save_and_read_expired_cookies
url = URI 'http://rubygems.org/'
@jar.jar['rubygems.org'] = {}
@jar.add url, Mechanize::Cookie.new(cookie_values)
# HACK no assertion
end
def test_ssl_cookies
# thanks to michal "ocher" ochman for reporting the bug responsible for this test.
values = cookie_values(:expires => nil)
values_ssl = values.merge(:name => 'Baz', :domain => "#{values[:domain]}:443")
url = URI 'https://rubygems.org/login'
cookie = Mechanize::Cookie.new(values)
@jar.add(url, cookie)
assert_equal(1, @jar.cookies(url).length, "did not handle SSL cookie")
cookie = Mechanize::Cookie.new(values_ssl)
@jar.add(url, cookie)
assert_equal(2, @jar.cookies(url).length, "did not handle SSL cookie with :443")
end
def test_secure_cookie
nurl = URI 'http://rubygems.org/login'
surl = URI 'https://rubygems.org/login'
ncookie = Mechanize::Cookie.new(cookie_values(:name => 'Foo1'))
scookie = Mechanize::Cookie.new(cookie_values(:name => 'Foo2', :secure => true))
@jar.add(nurl, ncookie)
@jar.add(nurl, scookie)
@jar.add(surl, ncookie)
@jar.add(surl, scookie)
assert_equal('Foo1', @jar.cookies(nurl).map { |c| c.name }.sort.join(' ') )
assert_equal('Foo1 Foo2', @jar.cookies(surl).map { |c| c.name }.sort.join(' ') )
end
def test_save_cookies_cookiestxt_subdomain
top_url = URI 'http://rubygems.org/'
subdomain_url = URI 'http://admin.rubygems.org/'
# cookie1 is for *.rubygems.org; cookie2 is only for rubygems.org, no subdomains
cookie1 = Mechanize::Cookie.new(cookie_values)
cookie2 = Mechanize::Cookie.new(cookie_values(:name => 'Boo', :for_domain => false))
@jar.add(top_url, cookie1)
@jar.add(top_url, cookie2)
assert_equal(2, @jar.cookies(top_url).length)
assert_equal(1, @jar.cookies(subdomain_url).length)
in_tmpdir do
@jar.save_as("cookies.txt", :cookiestxt)
jar = Mechanize::CookieJar.new
jar.load("cookies.txt", :cookiestxt) # HACK test the format
assert_equal(2, jar.cookies(top_url).length)
assert_equal(1, jar.cookies(subdomain_url).length)
# Check that we actually wrote the file correctly (not just that we were
# able to read what we wrote):
#
# * Cookies that only match exactly the domain specified must not have a
# leading dot, and must have FALSE as the second field.
# * Cookies that match subdomains may have a leading dot, and must have
# TRUE as the second field.
cookies_txt = File.readlines("cookies.txt")
assert_equal(1, cookies_txt.grep( /^rubygems\.org\tFALSE/ ).length)
assert_equal(1, cookies_txt.grep( /^\.rubygems\.org\tTRUE/ ).length)
end
assert_equal(2, @jar.cookies(top_url).length)
assert_equal(1, @jar.cookies(subdomain_url).length)
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_file_saver.rb | test/test_mechanize_file_saver.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeFileSaver < Mechanize::TestCase
def setup
super
@uri = URI 'http://example'
@io = StringIO.new 'hello world'
end
def test_initialize
in_tmpdir do
Mechanize::FileSaver.new @uri, nil, @io, 200
assert File.exist? 'example/index.html'
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_link.rb | test/test_mechanize_link.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeLink < Mechanize::TestCase
def test_search
page = @mech.get("http://localhost/find_link.html")
link = page.link_with(text: "Form Test")
assert_equal('Form Test', link.text)
link_with_search = page.link_with(search: "//*[text()='Form Test']")
assert_equal(link, link_with_search)
link_with_xpath = page.link_with(xpath: "//*[text()='Form Test']")
assert_equal(link, link_with_xpath)
link_with_css = page.link_with(css: ".formtest")
assert_equal(link, link_with_css)
link_with_class = page.link_with(class: "formtest")
assert_equal(link, link_with_class)
end
def test_click
page = @mech.get("http://localhost/frame_test.html")
link = page.link_with(:text => "Form Test")
assert_equal('Form Test', link.text)
page = link.click
assert_equal("http://localhost/form_test.html",
@mech.history.last.uri.to_s)
end unless RUBY_ENGINE == 'jruby' # NekoHTML does not parse body of NOFRAMES
def test_click_bang
page = @mech.get("http://localhost/frame_test.html")
link = page.link_with!(:text => "Form Test")
assert_equal('Form Test', link.text)
page = link.click
assert_equal("http://localhost/form_test.html",
@mech.history.last.uri.to_s)
end unless RUBY_ENGINE == 'jruby' # NekoHTML does not parse body of NOFRAMES
def test_click_base
page = @mech.get("http://google.com/tc_base_link.html")
page = page.links.first.click
assert @mech.visited?("http://localhost/index.html")
end
def test_click_unsupported_scheme
page = @mech.get("http://google.com/tc_links.html")
link = page.link_with(:text => 'javascript link')
assert_raises Mechanize::UnsupportedSchemeError do
begin
link.click
rescue Mechanize::UnsupportedSchemeError => error
assert_equal 'javascript', error.scheme
assert_equal "javascript:new_page('1')", error.uri.to_s
raise
end
end
@mech.scheme_handlers['javascript'] = lambda { |my_link, my_page|
URI.parse('http://localhost/tc_links.html')
}
link.click
# HACK no assertion
end
def test_click_unexiting_link
page = @mech.get("http://google.com/tc_links.html")
assert_raises NoMethodError do
page.link_with(:text => 'no link').click
end
begin
page.link_with!(:text => 'no link').click
rescue => e
assert_instance_of Mechanize::ElementNotFoundError, e
assert_kind_of Mechanize::Page, e.source
assert_equal :link, e.element
assert_kind_of Hash, e.conditions
assert_equal 'no link', e.conditions[:text]
end
end
def test_click_empty_href
page = @mech.get("http://google.com/tc_links.html?q=test#anchor")
link = page.link_with(:text => 'empty href')
new_page = link.click
assert_equal "http://google.com/tc_links.html?q=test", new_page.uri.to_s
end
def test_text_alt_text
page = @mech.get("http://localhost/alt_text.html")
assert_equal(5, page.links.length)
assert_equal(1, page.meta_refresh.length)
assert_equal '', page.meta_refresh.first.text
assert_equal 'alt text', page.link_with(:href => 'alt_text.html').text
assert_equal '', page.link_with(:href => 'no_alt_text.html').text
assert_equal 'no image', page.link_with(:href => 'no_image.html').text
assert_equal '', page.link_with(:href => 'no_text.html').text
assert_equal '', page.link_with(:href => 'nil_alt_text.html').text
end
def test_uri_escaped
doc = Nokogiri::HTML::Document.new
node = Nokogiri::XML::Node.new('foo', doc)
node['href'] = 'http://foo.bar/%20baz'
link = Mechanize::Page::Link.new(node, nil, nil)
assert_equal 'http://foo.bar/%20baz', link.uri.to_s
end
def test_uri_no_path
page = @mech.get("http://localhost/relative/tc_relative_links.html")
page = page.link_with(:text => 'just the query string').click
assert_equal('http://localhost/relative/tc_relative_links.html?a=b',
page.uri.to_s)
end unless RUBY_ENGINE == 'jruby' # NekoHTML does not parse IFRAME
def test_uri_weird
doc = Nokogiri::HTML::Document.new
node = Nokogiri::XML::Node.new('foo', doc)
node['href'] = 'http://foo.bar/ baz'
link = Mechanize::Page::Link.new(node, nil, nil)
assert_equal 'http://foo.bar/%20baz', link.uri.to_s
end
def test_uri_weird_with_fragment
doc = Nokogiri::HTML::Document.new
node = Nokogiri::XML::Node.new('foo', doc)
node['href'] = 'http://foo.bar/ baz#уважение'
link = Mechanize::Page::Link.new(node, nil, nil)
assert_equal '%D1%83%D0%B2%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5', link.uri.fragment
end
def test_bad_uri_raise_compatible_exception
doc = Nokogiri::HTML::Document.new
node = Nokogiri::XML::Node.new('foo', doc)
node['href'] = 'http://http:foo.bar/ baz'
link = Mechanize::Page::Link.new(node, nil, nil)
assert_raises URI::InvalidURIError do
link.uri
end
end
def test_resolving_full_uri
page = @mech.get("http://localhost/frame_test.html")
link = page.link_with(:text => "Form Test")
assert_equal "/form_test.html", link.uri.to_s
assert_equal "http://localhost/form_test.html", link.resolved_uri.to_s
end unless RUBY_ENGINE == 'jruby' # NekoHTML does not parse body of NOFRAMES
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_parser.rb | test/test_mechanize_parser.rb | # frozen_string_literal: true
require 'mechanize/test_case'
class TestMechanizeParser < Mechanize::TestCase
class P
include Mechanize::Parser
attr_accessor :filename
attr_accessor :response
attr_accessor :uri
def initialize
@uri = URI 'http://example'
@full_path = false
end
end
def setup
super
@parser = P.new
end
def test_extract_filename
@parser.response = {}
assert_equal 'index.html', @parser.extract_filename
end
def test_extract_filename_content_disposition
@parser.uri = URI 'http://example/foo'
@parser.response = {
'content-disposition' => 'attachment; filename=genome.jpeg'
}
assert_equal 'genome.jpeg', @parser.extract_filename
end
def test_extract_filename_content_disposition_bad
@parser.uri = URI 'http://example/foo'
@parser.response = {
'content-disposition' => "inline; filename*=UTF-8''X%20Y.jpg"
}
assert_equal 'foo.html', @parser.extract_filename
@parser.response = {
'content-disposition' => "inline; filename=\"\""
}
assert_equal 'foo.html', @parser.extract_filename
end
def test_extract_filename_content_disposition_path
@parser.uri = URI 'http://example'
@parser.response = {
'content-disposition' => 'attachment; filename="../genome.jpeg"'
}
assert_equal 'example/genome.jpeg', @parser.extract_filename(true)
@parser.response = {
'content-disposition' => 'attachment; filename="foo/genome.jpeg"'
}
assert_equal 'example/genome.jpeg', @parser.extract_filename(true)
end
def test_extract_filename_content_disposition_path_windows
@parser.uri = URI 'http://example'
@parser.response = {
'content-disposition' => 'attachment; filename="..\\\\genome.jpeg"'
}
assert_equal 'example/genome.jpeg', @parser.extract_filename(true)
@parser.response = {
'content-disposition' => 'attachment; filename="foo\\\\genome.jpeg"'
}
assert_equal 'example/genome.jpeg', @parser.extract_filename(true)
end
def test_extract_filename_content_disposition_full_path
@parser.uri = URI 'http://example/foo'
@parser.response = {
'content-disposition' => 'attachment; filename=genome.jpeg'
}
assert_equal 'example/genome.jpeg', @parser.extract_filename(true)
end
def test_extract_filename_content_disposition_quoted
@parser.uri = URI 'http://example'
@parser.response = {
'content-disposition' => 'attachment; filename="\"some \"file\""'
}
assert_equal '_some__file_', @parser.extract_filename
end
def test_extract_filename_content_disposition_special
@parser.uri = URI 'http://example/foo'
@parser.response = {
'content-disposition' => 'attachment; filename="/\\\\<>:\\"|?*"'
}
assert_equal '_______', @parser.extract_filename
chars = (0..12).map { |c| c.chr }.join
chars += "\\\r"
chars += (14..31).map { |c| c.chr }.join
@parser.response = {
'content-disposition' => "attachment; filename=\"#{chars}\""
}
assert_equal '_' * 32, @parser.extract_filename
end
def test_extract_filename_content_disposition_windows_special
@parser.uri = URI 'http://example'
windows_special = %w[
AUX
COM1
COM2
COM3
COM4
COM5
COM6
COM7
COM8
COM9
CON
LPT1
LPT2
LPT3
LPT4
LPT5
LPT6
LPT7
LPT8
LPT9
NUL
PRN
]
windows_special.each do |special|
@parser.response = {
'content-disposition' => "attachment; filename=#{special}"
}
assert_equal "_#{special}", @parser.extract_filename
end
end
def test_extract_filename_content_disposition_empty
@parser.uri = URI 'http://example'
@parser.response = {
'content-disposition' => 'inline; filename="/"'
}
assert_equal '', @parser.extract_filename
end
def test_extract_filename_host
@parser.response = {}
@parser.uri = URI 'http://example'
assert_equal 'example/index.html', @parser.extract_filename(true)
end
def test_extract_filename_special_character
@parser.response = {}
invisible = "\t\n\v\f\r"
invisible.chars.each do |char|
begin
@parser.uri = URI "http://example/#{char}"
assert_equal 'index.html', @parser.extract_filename, char.inspect
rescue URI::InvalidURIError
# ignore
end
end
escaped = "<>\"\\|"
escaped.chars.each do |char|
escaped_char = CGI.escape char
@parser.uri = URI "http://example/#{escaped_char}"
assert_equal "#{escaped_char}.html", @parser.extract_filename, char
end
@parser.uri = URI "http://example/?"
assert_equal 'index.html_', @parser.extract_filename, 'empty query'
@parser.uri = URI "http://example/:"
assert_equal '_.html', @parser.extract_filename, 'colon'
@parser.uri = URI "http://example/*"
assert_equal '_.html', @parser.extract_filename, 'asterisk'
end
def test_extract_filename_uri
@parser.response = {}
@parser.uri = URI 'http://example/foo'
assert_equal 'foo.html', @parser.extract_filename
@parser.uri += '/foo.jpg'
assert_equal 'foo.jpg', @parser.extract_filename
end
def test_extract_filename_uri_full_path
@parser.response = {}
@parser.uri = URI 'http://example/foo'
assert_equal 'example/foo.html', @parser.extract_filename(true)
@parser.uri += '/foo.jpg'
assert_equal 'example/foo.jpg', @parser.extract_filename(true)
end
def test_extract_filename_uri_query
@parser.response = {}
@parser.uri = URI 'http://example/?id=5'
assert_equal 'index.html_id=5', @parser.extract_filename
@parser.uri += '/foo.html?id=5'
assert_equal 'foo.html_id=5', @parser.extract_filename
end
def test_extract_filename_uri_slash
@parser.response = {}
@parser.uri = URI 'http://example/foo/'
assert_equal 'example/foo/index.html', @parser.extract_filename(true)
@parser.uri += '/foo///'
assert_equal 'example/foo/index.html', @parser.extract_filename(true)
end
def test_extract_filename_windows_special
@parser.uri = URI 'http://example'
@parser.response = {}
windows_special = %w[
AUX
COM1
COM2
COM3
COM4
COM5
COM6
COM7
COM8
COM9
CON
LPT1
LPT2
LPT3
LPT4
LPT5
LPT6
LPT7
LPT8
LPT9
NUL
PRN
]
windows_special.each do |special|
@parser.uri += "/#{special}"
assert_equal "_#{special}.html", @parser.extract_filename
end
end
def test_fill_header
@parser.fill_header 'a' => 'b'
expected = { 'a' => 'b' }
assert_equal expected, @parser.response
end
def test_fill_header_nil
@parser.fill_header nil
assert_empty @parser.response
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
sparklemotion/mechanize | https://github.com/sparklemotion/mechanize/blob/4e192760df6c2311d54e527c2b07a5fa4826c5fb/test/test_mechanize_page_encoding.rb | test/test_mechanize_page_encoding.rb | # -*- coding: utf-8 -*-
# frozen_string_literal: true
require 'mechanize/test_case'
# tests for Page encoding and charset and parsing
class TestMechanizePageEncoding < Mechanize::TestCase
MECH_ASCII_ENCODING = 'US-ASCII'
def setup
super
@uri = URI('http://localhost/')
@response_headers = { 'content-type' => 'text/html' }
@body = +'<title>hi</title>'
end
def util_page body = @body, headers = @response_headers
Mechanize::Page.new @uri, headers, body && body.force_encoding(Encoding::BINARY), 200, @mech
end
def test_page_charset
charset = Mechanize::Page.charset 'text/html;charset=vAlue'
assert_equal 'vAlue', charset
charset = Mechanize::Page.charset 'text/html;charset=vaLue, text/html'
assert_equal 'vaLue', charset
charset = Mechanize::Page.charset 'text/html ; charset = valUe, text/html'
assert_equal 'valUe', charset
end
def test_page_charset_upcase
charset = Mechanize::Page.charset 'TEXT/HTML;CHARSET=UTF-8'
assert_equal 'UTF-8', charset
end
def test_page_charset_semicolon
charset = Mechanize::Page.charset 'text/html;charset=UTF-8;'
assert_equal 'UTF-8', charset
end
def test_page_charset_no_chaset_token
charset = Mechanize::Page.charset 'text/html'
assert_nil charset
end
def test_page_charset_returns_nil_when_charset_says_none
charset = Mechanize::Page.charset 'text/html;charset=none'
assert_nil charset
end
def test_page_charset_multiple
charset = Mechanize::Page.charset 'text/html;charset=111;charset=222'
assert_equal '111', charset
end
def test_page_response_header_charset
headers = { 'content-type' => 'text/html;charset=HEADER' }
charsets = Mechanize::Page.response_header_charset(headers)
assert_equal ['HEADER'], charsets
end
def test_page_response_header_charset_no_token
headers = {'content-type' => 'text/html'}
charsets = Mechanize::Page.response_header_charset(headers)
assert_equal [], charsets
headers = {'X-My-Header' => 'hello'}
charsets = Mechanize::Page.response_header_charset(headers)
assert_equal [], charsets
end
def test_page_response_header_charset_wrong_header
headers = { 'x-content-type' => 'text/html;charset=bogus' }
charsets = Mechanize::Page.response_header_charset(headers)
assert_equal [], charsets
end
def test_response_header_charset
page = util_page nil, {'content-type' => 'text/html;charset=HEADER'}
assert_equal ['HEADER'], page.response_header_charset
end
def test_page_meta_charset
body = '<meta http-equiv="content-type" content="text/html;charset=META">'
charsets = Mechanize::Page.meta_charset(body)
assert_equal ['META'], charsets
end
def test_page_meta_charset_is_empty_when_no_charset_meta
body = '<meta http-equiv="refresh" content="5; url=index.html">'
charsets = Mechanize::Page.meta_charset(body)
assert_equal [], charsets
end
def test_page_meta_charset_no_content
body = '<meta http-equiv="content-type">'
charsets = Mechanize::Page.meta_charset(body)
assert_empty charsets
end
# Test to fix issue: https://github.com/sparklemotion/mechanize/issues/143
def test_page_meta_charset_handles_whitespace
body = '<meta http-equiv = "Content-Type" content = "text/html; charset=iso-8859-1">'
charsets = Mechanize::Page.meta_charset(body)
assert_equal ["iso-8859-1"], charsets
end
def test_meta_charset
body = +'<meta http-equiv="content-type" content="text/html;charset=META">'
page = util_page body
assert_equal ['META'], page.meta_charset
end
def test_detected_encoding
page = util_page
assert_equal MECH_ASCII_ENCODING, page.detected_encoding
end
def test_encodings
response = {'content-type' => 'text/html;charset=HEADER'}
body = +'<meta http-equiv="content-type" content="text/html;charset=META">'
@mech.default_encoding = 'DEFAULT'
page = util_page body, response
assert_equal true, page.encodings.include?('HEADER')
assert_equal true, page.encodings.include?('META')
assert_equal true, page.encodings.include?(MECH_ASCII_ENCODING)
assert_equal true, page.encodings.include?('DEFAULT')
end
def test_parser_with_default_encoding
# pre test
assert_equal false, util_page.encodings.include?('Windows-1252')
@mech.default_encoding = 'Windows-1252'
page = util_page
assert_equal true, page.encodings.include?('Windows-1252')
end
def test_parser_force_default_encoding
@mech.default_encoding = 'Windows-1252'
@mech.force_default_encoding = true
page = util_page
assert page.encodings.include? 'Windows-1252'
end
def test_parser_encoding_equals_overwrites_force_default_encoding
@mech.default_encoding = 'Windows-1252'
@mech.force_default_encoding = true
page = util_page
assert_equal 'Windows-1252', page.encoding
page.encoding = 'ISO-8859-2'
assert_equal 'ISO-8859-2', page.encoding
end
def test_parser_encoding_when_searching_elements
skip "Encoding not implemented" unless have_encoding?
body = +'<span id="latin1">hi</span>'
page = util_page body, 'content-type' => 'text/html,charset=ISO-8859-1'
result = page.search('#latin1')
assert_equal Encoding::UTF_8, result.text.encoding
end
def test_parser_error_message_containing_encoding_errors
skip if RUBY_ENGINE == 'jruby' # this is a libxml2-specific condition
# https://github.com/sparklemotion/mechanize/issues/553
body = +<<~EOF
<html>
<body>
<!--
## メモ
処理の一般化, 二重ループ, 多重ループ
wzxhzdk:25
-->
EOF
page = util_page body
# this should not raise an "invalid byte sequence in UTF-8" error while processing parsing errors
page.search("body")
# let's assert on the setup: a libxml2-returned parsing error itself contains an invalid character
# note that this problem only appears in libxml <= 2.9.10
error = page.parser.errors.find { |e| e.message.include?("Comment not terminated") }
if error
exception = assert_raises(ArgumentError) do
error.message =~ /any regex just to trigger encoding error/
end
assert_includes(exception.message, "invalid byte sequence in UTF-8")
end
end
end
| ruby | MIT | 4e192760df6c2311d54e527c2b07a5fa4826c5fb | 2026-01-04T15:46:19.932284Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.