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 |
|---|---|---|---|---|---|---|---|---|
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/time.rb | lib/coercible/coercer/time.rb | module Coercible
class Coercer
# Coerce Time values
class Time < Object
include TimeCoercions
primitive ::Time
# Passthrough the value
#
# @example
# coercer[DateTime].to_time(time) # => Time object
#
# @param [DateTime] value
#
# @return [Date]
#
# @api public
def to_time(value)
value
end
# Creates a Fixnum instance from a Time object
#
# @example
# Coercible::Coercion::Time.to_integer(time) # => Fixnum object
#
# @param [Time] value
#
# @return [Fixnum]
#
# @api public
def to_integer(value)
value.to_i
end
end # class Time
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/float.rb | lib/coercible/coercer/float.rb | module Coercible
class Coercer
# Coerce Float values
class Float < Numeric
primitive ::Float
# Passthrough the value
#
# @example
# coercer[Float].to_float(1.0) # => 1.0
#
# @param [Float] value
#
# @return [Integer]
#
# @api public
def to_float(value)
value
end
# Coerce given value to a DateTime
#
# @example
# datetime = Coercible::Coercion::Float.to_datetime(1000000000.999) # => Sun, 09 Sep 2001 01:46:40 +0000
# datetime.to_f # => 1000000000.999
#
# @param [Float] value
#
# @return [DateTime]
#
# @api public
def to_datetime(value)
::DateTime.strptime((value * 10**3).to_s, "%Q")
end
end # class Float
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/string.rb | lib/coercible/coercer/string.rb | module Coercible
class Coercer
# Coerce String values
class String < Object
extend Configurable
primitive ::String
config_keys [ :boolean_map ]
TRUE_VALUES = %w[ 1 on t true y yes ].freeze
FALSE_VALUES = %w[ 0 off f false n no ].freeze
BOOLEAN_MAP = ::Hash[ TRUE_VALUES.product([ true ]) + FALSE_VALUES.product([ false ]) ].freeze
INTEGER_REGEXP = /[-+]?(?:[0-9]\d*)/.freeze
EXPONENT_REGEXP = /(?:[eE][-+]?\d+)/.freeze
FRACTIONAL_REGEXP = /(?:\.\d+)/.freeze
NUMERIC_REGEXP = /\A(
#{INTEGER_REGEXP}#{FRACTIONAL_REGEXP}?#{EXPONENT_REGEXP}? |
#{FRACTIONAL_REGEXP}#{EXPONENT_REGEXP}?
)\z/x.freeze
# Return default configuration for string coercer type
#
# @return [Configuration]
#
# @api private
def self.config
super { |config| config.boolean_map = BOOLEAN_MAP }
end
# Return boolean map from the config
#
# @return [::Hash]
#
# @api private
attr_reader :boolean_map
# Initialize a new string coercer instance
#
# @param [Coercer]
#
# @param [Configuration]
#
# @return [undefined]
#
# @api private
def initialize(coercer = Coercer.new, config = self.class.config)
super(coercer)
@boolean_map = config.boolean_map
end
# Coerce give value to a constant
#
# @example
# coercer[String].to_constant('String') # => String
#
# @param [String] value
#
# @return [Object]
#
# @api public
def to_constant(value)
names = value.split('::')
names.shift if names.first.empty?
names.inject(::Object) { |*args| constant_lookup(*args) }
end
# Coerce give value to a symbol
#
# @example
# coercer[String].to_symbol('string') # => :string
#
# @param [String] value
#
# @return [Symbol]
#
# @api public
def to_symbol(value)
value.to_sym
end
# Coerce given value to Time
#
# @example
# coercer[String].to_time(string) # => Time object
#
# @param [String] value
#
# @return [Time]
#
# @api public
def to_time(value)
parse_value(::Time, value, __method__)
end
# Coerce given value to Date
#
# @example
# coercer[String].to_date(string) # => Date object
#
# @param [String] value
#
# @return [Date]
#
# @api public
def to_date(value)
parse_value(::Date, value, __method__)
end
# Coerce given value to DateTime
#
# @example
# coercer[String].to_datetime(string) # => DateTime object
#
# @param [String] value
#
# @return [DateTime]
#
# @api public
def to_datetime(value)
parse_value(::DateTime, value, __method__)
end
# Coerce value to TrueClass or FalseClass
#
# @example with "T"
# coercer[String].to_boolean('T') # => true
#
# @example with "F"
# coercer[String].to_boolean('F') # => false
#
# @param [#to_s]
#
# @return [Boolean]
#
# @api public
def to_boolean(value)
boolean_map.fetch(value.downcase) {
raise_unsupported_coercion(value, __method__)
}
end
# Coerce value to integer
#
# @example
# coercer[String].to_integer('1') # => 1
#
# @param [Object] value
#
# @return [Integer]
#
# @api public
def to_integer(value)
if value =~ /\A#{INTEGER_REGEXP}\z/
value.to_i
else
# coerce to a Float first to evaluate scientific notation (if any)
# that may change the integer part, then convert to an integer
to_float(value).to_i
end
rescue UnsupportedCoercion
raise_unsupported_coercion(value, __method__)
end
# Coerce value to float
#
# @example
# coercer[String].to_float('1.2') # => 1.2
#
# @param [Object] value
#
# @return [Float]
#
# @api public
def to_float(value)
to_numeric(value, :to_f)
rescue UnsupportedCoercion
raise_unsupported_coercion(value, __method__)
end
# Coerce value to decimal
#
# @example
# coercer[String].to_decimal('1.2') # => #<BigDecimal:b72157d4,'0.12E1',8(8)>
#
# @param [Object] value
#
# @return [BigDecimal]
#
# @api public
def to_decimal(value)
to_numeric(value, :to_d)
rescue UnsupportedCoercion
raise_unsupported_coercion(value, __method__)
end
private
# Lookup a constant within a module
#
# @param [Module] mod
#
# @param [String] name
#
# @return [Object]
#
# @api private
def constant_lookup(mod, name)
if mod.const_defined?(name, *EXTRA_CONST_ARGS)
mod.const_get(name, *EXTRA_CONST_ARGS)
else
mod.const_missing(name)
end
end
# Match numeric string
#
# @param [String] value
# value to typecast
# @param [Symbol] method
# method to typecast with
#
# @return [Numeric]
# number if matched, value if no match
#
# @api private
def to_numeric(value, method)
if value =~ NUMERIC_REGEXP
$1.public_send(method)
else
raise_unsupported_coercion(value, method)
end
end
# Parse the value or return it as-is if it is invalid
#
# @param [#parse] parser
#
# @param [String] value
#
# @return [Time]
#
# @api private
def parse_value(parser, value, method)
parser.parse(value)
rescue ArgumentError
raise_unsupported_coercion(value, method)
end
end # class String
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/false_class.rb | lib/coercible/coercer/false_class.rb | module Coercible
class Coercer
# Coerce false values
class FalseClass < Object
primitive ::FalseClass
# Coerce given value to String
#
# @example
# coercer[FalseClass].to_string(false) # => "false"
#
# @param [FalseClass] value
#
# @return [String]
#
# @api public
def to_string(value)
value.to_s
end
end # class FalseClass
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/object.rb | lib/coercible/coercer/object.rb | module Coercible
class Coercer
# Coerce Object values
class Object
extend TypeLookup, Options
accept_options :primitive
primitive ::Object
COERCION_METHOD_REGEXP = /\Ato_/.freeze
# Return coercers object
#
# @return [Coercer]
#
# @api private
attr_reader :coercers
# Initialize a new coercer instance
#
# @param [Coercer] coercers
#
# @return [undefined]
#
# @api private
def initialize(coercers = Coercer.new)
@coercers = coercers
end
# Inspect the coercer object
#
# @example
# coercer[Object].inspect # => "<Coercer::Object primitive=Object>"
#
# @return [String]
#
# @api public
def inspect
"#<#{self.class} primitive=#{self.class.primitive}>"
end
# Create an Array from any Object
#
# @example with an object that does not respond to #to_a or #to_ary
# coercer[Object].to_array(value) # => [ value ]
#
# @example with an object that responds to #to_a
# coercer[Object].to_array(Set[ value ]) # => [ value ]
#
# @example with n object that responds to #to_ary
# coercer[Object].to_array([ value ]) # => [ value ]
#
# @param [#to_a,#to_ary,Object] value
# @param [#to_a,#to_ary,Object] value
#
# @return [Array]
#
# @api public
def to_array(value)
Array(value)
end
# Create a Hash from the Object if possible
#
# @example with a coercible object
# coercer[Object].to_hash(key => value) # => { key => value }
#
# @example with an object that is not coercible
# coercer[Object].to_hash(value) # => value
#
# @param [#to_hash, Object] value
#
# @return [Hash]
# returns a Hash when the object can be coerced
# @return [Object]
# returns the value when the object cannot be coerced
#
# @api public
def to_hash(value)
coerce_with_method(value, :to_hash, __method__)
end
# Create a String from the Object if possible
#
# @example with a coercible object
# coercer[Object].to_string("string") # => "string"
#
# @example with an object that is not coercible
# coercer[Object].to_string(value) # => value
#
# @param [#to_str, Object] value
#
# @return [String]
# returns a String when the object can be coerced
# @return [Object]
# returns the value when the object cannot be coerced
#
# @api public
def to_string(value)
coerce_with_method(value, :to_str, __method__)
end
# Create an Integer from the Object if possible
#
# @example with a coercible object
# coercer[Object].to_integer(1) # => 1
#
# @example with an object that is not coercible
# coercer[Object].to_integer(value) # => value
#
# @param [#to_int, Object] value
#
# @return [Integer]
# returns an Integer when the object can be coerced
# @return [Object]
# returns the value when the object cannot be coerced
#
# @api public
def to_integer(value)
coerce_with_method(value, :to_int, __method__)
end
# Return if the value was successfuly coerced
#
# @example when coercion was successful
# coercer[String].coerced?(1) # => true
#
# @example when coercion was NOT successful
# coercer[String].coerced?("foo") # => false
#
# @return [TrueClass,FalseClass]
#
# @api public
def coerced?(value)
value.kind_of?(self.class.primitive)
end
private
# Raise an unsupported coercion error
#
# @raises [UnsupportedCoercion]
#
# @return [undefined]
#
# @api private
def raise_unsupported_coercion(value, method)
raise(
UnsupportedCoercion,
"#{self.class}##{method} doesn't know how to coerce #{value.inspect}"
)
end
# Passthrough given value
#
# @param [Object] value
#
# @return [Object]
#
# @api private
def method_missing(method, *args)
if method.to_s =~ COERCION_METHOD_REGEXP && args.size == 1
args.first
else
super
end
end
# Try to use native coercion method on the given value
#
# @param [Object] value
#
# @param [Symbol] method
#
# @return [Object]
#
# @api private
def coerce_with_method(value, method, ref_method)
value.respond_to?(method) ? value.public_send(method) : raise_unsupported_coercion(value, ref_method)
end
end # class Object
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/integer.rb | lib/coercible/coercer/integer.rb | module Coercible
class Coercer
# Coerce Fixnum values
class Integer < Numeric
extend Configurable
primitive ::Integer
config_keys [ :datetime_format, :datetime_proc, :boolean_map ]
# Return default config for Integer coercer type
#
# @return [Configuration]
#
# @see Configurable#config
#
# @api private
def self.config
super do |config|
# FIXME: Remove after Rubinius 2.0 is released
config.datetime_format, config.datetime_proc =
if Coercible.rbx?
[ '%Q', Proc.new { |value| "#{value * 10**3}" } ]
else
[ '%s', Proc.new { |value| "#{value}" } ]
end
config.boolean_map = { 0 => false, 1 => true }
end
end
# Return datetime format from config
#
# @return [::String]
#
# @api private
attr_reader :datetime_format
# Return datetime proc from config
#
# @return [Proc]
#
# @api private
attr_reader :datetime_proc
# Return boolean map from config
#
# @return [::Hash]
#
# @api private
attr_reader :boolean_map
# Initialize a new Integer coercer instance and set its configuration
#
# @return [undefined]
#
# @api private
def initialize(coercer = Coercer.new, config = self.class.config)
super(coercer)
@boolean_map = config.boolean_map
@datetime_format = config.datetime_format
@datetime_proc = config.datetime_proc
end
# Coerce given value to String
#
# @example
# coercer[Integer].to_string(1) # => "1"
#
# @param [Fixnum] value
#
# @return [String]
#
# @api public
def to_string(value)
value.to_s
end
# Passthrough the value
#
# @example
# coercer[Integer].to_integer(1) # => 1
#
# @param [Fixnum] value
#
# @return [Float]
#
# @api public
def to_integer(value)
value
end
# Coerce given value to a Boolean
#
# @example with a 1
# coercer[Integer].to_boolean(1) # => true
#
# @example with a 0
# coercer[Integer].to_boolean(0) # => false
#
# @param [Fixnum] value
#
# @return [BigDecimal]
#
# @api public
def to_boolean(value)
boolean_map.fetch(value) {
raise_unsupported_coercion(value, __method__)
}
end
# Coerce given value to a DateTime
#
# @example
# coercer[Integer].to_datetime(0) # => Thu, 01 Jan 1970 00:00:00 +0000
#
# @param [Integer] value
#
# @return [DateTime]
#
# @api public
def to_datetime(value)
::DateTime.strptime(datetime_proc.call(value), datetime_format)
end
end # class Fixnum
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/time_coercions.rb | lib/coercible/coercer/time_coercions.rb | module Coercible
class Coercer
# Common time coercion methods
module TimeCoercions
# Coerce given value to String
#
# @example
# coercer[Time].to_string(time) # => "Wed Jul 20 10:30:41 -0700 2011"
#
# @param [Date,Time,DateTime] value
#
# @return [String]
#
# @api public
def to_string(value)
value.to_s
end
# Coerce given value to Time
#
# @example
# coercer[DateTime].to_time(datetime) # => Time object
#
# @param [Date,DateTime] value
#
# @return [Time]
#
# @api public
def to_time(value)
coerce_with_method(value, :to_time)
end
# Coerce given value to DateTime
#
# @example
# coercer[Time].to_datetime(time) # => DateTime object
#
# @param [Date,Time] value
#
# @return [DateTime]
#
# @api public
def to_datetime(value)
coerce_with_method(value, :to_datetime)
end
# Coerce given value to Date
#
# @example
# coercer[Time].to_date(time) # => Date object
#
# @param [Time,DateTime] value
#
# @return [Date]
#
# @api public
def to_date(value)
coerce_with_method(value, :to_date)
end
private
# Try to use native coercion method on the given value
#
# Falls back to String-based parsing
#
# @param [Date,DateTime,Time] value
# @param [Symbol] method
#
# @return [Date,DateTime,Time]
#
# @api private
def coerce_with_method(value, method)
if value.respond_to?(method)
value.public_send(method)
else
coercers[::String].public_send(method, to_string(value))
end
end
end # module TimeCoercions
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/configurable.rb | lib/coercible/coercer/configurable.rb | module Coercible
class Coercer
module Configurable
# Add configuration-specific option keys to the descendant
#
# @return [self]
#
# @api private
def self.extended(coercer)
coercer.accept_options :config_keys
super
end
# Build configuration object for the coercer class
#
# @example
#
# coercer_class = Class.new(Coercer::Object) do
# extend Configurable
#
# config_keys [ :foo, :bar ]
# end
#
# coercer_class.config do |config|
# config.foo = '1'
# config.bar = '2'
# end
#
# @yieldparam [Configuration]
#
# @return [Configuration]
#
# @api public
def config(&block)
configuration = configuration_class.build(config_keys)
yield configuration
configuration
end
# Return configuration name in the global config
#
# @return [Symbol]
#
# @api private
def config_name
name.downcase.split('::').last.to_sym
end
# Return configuration class
#
# @return [Class:Configuration]
#
# @api private
def configuration_class
Configuration
end
end # module Configurable
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/date_time.rb | lib/coercible/coercer/date_time.rb | module Coercible
class Coercer
# Coerce DateTime values
class DateTime < Object
primitive ::DateTime
include TimeCoercions
# Passthrough the value
#
# @example
# coercer[DateTime].to_datetime(datetime) # => DateTime object
#
# @param [DateTime] value
#
# @return [Date]
#
# @api public
def to_datetime(value)
value
end
end # class DateTime
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/hash.rb | lib/coercible/coercer/hash.rb | module Coercible
class Coercer
# Coerce Hash values
class Hash < Object
primitive ::Hash
TIME_SEGMENTS = [ :year, :month, :day, :hour, :min, :sec ].freeze
# Creates a Time instance from a Hash
#
# Valid keys are: :year, :month, :day, :hour, :min, :sec
#
# @param [Hash] value
#
# @return [Time]
#
# @api private
def to_time(value)
::Time.local(*extract(value))
end
# Creates a Date instance from a Hash
#
# Valid keys are: :year, :month, :day, :hour
#
# @param [Hash] value
#
# @return [Date]
#
# @api private
def to_date(value)
::Date.new(*extract(value).first(3))
end
# Creates a DateTime instance from a Hash
#
# Valid keys are: :year, :month, :day, :hour, :min, :sec
#
# @param [Hash] value
#
# @return [DateTime]
#
# @api private
def to_datetime(value)
::DateTime.new(*extract(value))
end
private
# Extracts the given args from a Hash
#
# If a value does not exist, it uses the value of Time.now
#
# @param [Hash] value
#
# @return [Array]
#
# @api private
def extract(value)
now = ::Time.now
TIME_SEGMENTS.map do |segment|
val = value.fetch(segment, now.public_send(segment))
coercers[val.class].to_integer(val)
end
end
end # class Hash
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/date.rb | lib/coercible/coercer/date.rb | module Coercible
class Coercer
# Coerce Date values
class Date < Object
include TimeCoercions
primitive ::Date
# Passthrough the value
#
# @example
# coercer[DateTime].to_date(date) # => Date object
#
# @param [DateTime] value
#
# @return [Date]
#
# @api public
def to_date(value)
value
end
end # class Date
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/symbol.rb | lib/coercible/coercer/symbol.rb | module Coercible
class Coercer
# Coerce Symbol values
class Symbol < Object
primitive ::Symbol
# Coerce given value to String
#
# @example
# coercer[Symbol].to_string(:name) # => "name"
#
# @param [Symbol] value
#
# @return [String]
#
# @api public
def to_string(value)
value.to_s
end
end # class Symbol
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer/numeric.rb | lib/coercible/coercer/numeric.rb | module Coercible
class Coercer
# Base class for all numeric Coercion classes
class Numeric < Object
primitive ::Numeric
# Coerce given value to String
#
# @example
# coercer[Numeric].to_string(Rational(2, 2)) # => "1.0"
#
# @param [Numeric] value
#
# @return [String]
#
# @api public
def to_string(value)
value.to_s
end
# Creates an Integer instance from a numeric object
#
# @example
# coercer[Numeric].to_integer(Rational(2, 2)) # => 1
#
# @param [Numeric] value
#
# @return [Integer]
#
# @api public
def to_integer(value)
value.to_i
end
# Creates a Float instance from a numeric object
#
# @example
# coercer[Numeric].to_float(Rational(2, 2)) # => 1.0
#
# @param [Numeric] value
#
# @return [Float]
#
# @api public
def to_float(value)
value.to_f
end
# Coerce a BigDecimal instance from a numeric object
#
# @example
# coercer[Numeric].to_decimal(Rational(2, 2)) # => BigDecimal('1.0')
#
# @param [Numeric] value
#
# @return [BigDecimal]
#
# @api public
def to_decimal(value)
to_string(value).to_d
end
end # class Numeric
end # class Coercer
end # module Coercible
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/support/options.rb | lib/support/options.rb | module Coercible
# A module that adds class and instance level options
module Options
Undefined = Class.new.freeze
# Hook called when descendant was extended
#
# @param [Class,Module] descendant
#
# @return [undefined]
#
# @api private
def self.extended(descendant)
descendant.extend(DescendantsTracker)
end
# Returns default options hash for a given attribute class
#
# @example
# Virtus::Attribute::String.options
# # => {:primitive => String}
#
# @return [Hash]
# a hash of default option values
#
# @api public
def options
accepted_options.each_with_object({}) do |option_name, options|
option_value = send(option_name)
options[option_name] = option_value unless option_value.nil?
end
end
# Returns an array of valid options
#
# @example
# Virtus::Attribute::String.accepted_options
# # => [:primitive, :accessor, :reader, :writer]
#
# @return [Array]
# the array of valid option names
#
# @api public
def accepted_options
@accepted_options ||= []
end
# Defines which options are valid for a given attribute class
#
# @example
# class MyAttribute < Virtus::Attribute::Object
# accept_options :foo, :bar
# end
#
# @return [self]
#
# @api public
def accept_options(*new_options)
add_accepted_options(new_options)
new_options.each { |option| define_option_method(option) }
descendants.each { |descendant| descendant.add_accepted_options(new_options) }
self
end
protected
# Adds a reader/writer method for the give option name
#
# @return [undefined]
#
# @api private
def define_option_method(option)
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{option}(value = Undefined) # def self.primitive(value = Undefined)
return @#{option} if value.equal?(Undefined) # return @primitive if value.equal?(Undefined)
@#{option} = value # @primitive = value
self # self
end # end
RUBY
end
# Sets default options
#
# @param [#each] new_options
# options to be set
#
# @return [self]
#
# @api private
def set_options(new_options)
new_options.each { |pair| send(*pair) }
self
end
# Adds new options that an attribute class can accept
#
# @param [#to_ary] new_options
# new options to be added
#
# @return [self]
#
# @api private
def add_accepted_options(new_options)
accepted_options.concat(new_options)
self
end
private
# Adds descendant to descendants array and inherits default options
#
# @param [Class] descendant
#
# @return [undefined]
#
# @api private
def inherited(descendant)
super
descendant.add_accepted_options(accepted_options).set_options(options)
end
end # module Options
end # module Virtus
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
solnic/coercible | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/support/type_lookup.rb | lib/support/type_lookup.rb | module Coercible
# A module that adds type lookup to a class
module TypeLookup
TYPE_FORMAT = /\A[A-Z]\w*\z/.freeze
# Set cache ivar on the model
#
# @param [Class] model
#
# @return [undefined]
#
# @api private
def self.extended(model)
model.instance_variable_set('@type_lookup_cache', {})
end
# Returns a descendant based on a name or class
#
# @example
# MyClass.determine_type('String') # => MyClass::String
#
# @param [Class, #to_s] class_or_name
# name of a class or a class itself
#
# @return [Class]
# a descendant
#
# @return [nil]
# nil if the type cannot be determined by the class_or_name
#
# @api public
def determine_type(class_or_name)
@type_lookup_cache[class_or_name] ||= determine_type_and_cache(class_or_name)
end
# Return the default primitive supported
#
# @return [Class]
#
# @api private
def primitive
raise NotImplementedError, "#{self}.primitive must be implemented"
end
private
# Determine type and cache the class
#
# @return [Class]
#
# @api private
def determine_type_and_cache(class_or_name)
case class_or_name
when singleton_class
determine_type_from_descendant(class_or_name)
when Class
determine_type_from_primitive(class_or_name)
else
determine_type_from_string(class_or_name.to_s)
end
end
# Return the class given a descendant
#
# @param [Class] descendant
#
# @return [Class]
#
# @api private
def determine_type_from_descendant(descendant)
descendant if descendant < self
end
# Return the class given a primitive
#
# @param [Class] primitive
#
# @return [Class]
#
# @return [nil]
# nil if the type cannot be determined by the primitive
#
# @api private
def determine_type_from_primitive(primitive)
type = nil
descendants.reverse_each do |descendant|
descendant_primitive = descendant.primitive
next unless primitive <= descendant_primitive
type = descendant if type.nil? or type.primitive > descendant_primitive
end
type
end
# Return the class given a string
#
# @param [String] string
#
# @return [Class]
#
# @return [nil]
# nil if the type cannot be determined by the string
#
# @api private
def determine_type_from_string(string)
if string =~ TYPE_FORMAT and const_defined?(string, *EXTRA_CONST_ARGS)
const_get(string, *EXTRA_CONST_ARGS)
end
end
end # module TypeLookup
end # module Virtus
| ruby | MIT | c076869838531abb5783280da108aa3cbddbd61a | 2026-01-04T17:44:40.075543Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/spec/response_spec.rb | spec/response_spec.rb | require File.dirname(__FILE__) + '/spec_helper'
require File.dirname(__FILE__) + '/../lib/clickatell'
module Clickatell
describe "Response parser" do
before do
Clickatell::API::Error.stubs(:parse).returns(Clickatell::API::Error.new('', ''))
end
before(:each) do
API.test_mode = false
end
it "should return hash for one-line success response" do
Response.parse(stub('response', :body => 'k1: foo k2: bar')).should == {'k1' => 'foo', 'k2' => 'bar'}
end
it "should return array of hashes for multi-line success response" do
Response.parse(stub('response', :body => "k1: foo\nk2: bar")).should == [{'k1' => 'foo'}, {'k2' => 'bar'}]
end
it "should raise API::Error if response contains an error message" do
proc { Response.parse(stub('response', :body => 'ERR: 001, Authentication failed')) }.should raise_error(Clickatell::API::Error)
end
{
'001' => 1, '002' => 2, '003' => 3, '004' => 4,
'005' => 5, '006' => 6, '007' => 7, '008' => 8,
'009' => 9, '010' => 10, '011' => 11, '012' => 12
}.each do |status_str, status_int|
it "should parse a message status code of #{status_int} when the response body contains a status code of #{status_str}" do
Response.parse(stub('response', :body => "ID: 0d1d7dda17d5a24edf1555dc0b679d0e Status: #{status_str}")).should == {'ID' => '0d1d7dda17d5a24edf1555dc0b679d0e', 'Status' => status_int}
end
end
describe "in test mode" do
before(:each) do
API.test_mode = true
end
it "should return something approximating a session_id" do
Response.parse("pretty much anything").should == { 'OK' => 'session_id' }
end
end
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/spec/api_spec.rb | spec/api_spec.rb | require File.dirname(__FILE__) + '/spec_helper'
require File.dirname(__FILE__) + '/../lib/clickatell'
class FakeHttp
def start(&block)
yield self
end
end
module Clickatell
describe "API Command" do
before do
@command = API::Command.new('cmdname')
end
after do
Clickatell::API.api_service_host = nil
end
it "should return encoded URL for the specified command and parameters" do
url = @command.with_params(:param_one => 'abc', :param_two => '123')
url.should == URI.parse("http://api.clickatell.com/http/cmdname?param_one=abc¶m_two=123")
end
it "should URL encode any special characters in parameters" do
url = @command.with_params(:param_one => 'abc', :param_two => 'hello world & goodbye cruel world <grin>')
url.should == URI.parse("http://api.clickatell.com/http/cmdname?param_one=abc¶m_two=hello+world+%26+goodbye+cruel+world+%3Cgrin%3E")
end
it "should use a custom host when constructing command URLs if specified" do
Clickatell::API.api_service_host = 'api.clickatell-custom.co.uk'
url = @command.with_params(:param_one => 'abc', :param_two => '123')
url.should == URI.parse("http://api.clickatell-custom.co.uk/http/cmdname?param_one=abc¶m_two=123")
end
it "should use the default host if specified custom host is nil" do
Clickatell::API.api_service_host = nil
url = @command.with_params(:param_one => 'abc', :param_two => '123')
url.should == URI.parse("http://api.clickatell.com/http/cmdname?param_one=abc¶m_two=123")
end
it "should use the default host if specified custom host is an empty string" do
Clickatell::API.api_service_host = ''
url = @command.with_params(:param_one => 'abc', :param_two => '123')
url.should == URI.parse("http://api.clickatell.com/http/cmdname?param_one=abc¶m_two=123")
end
end
describe "Secure API Command" do
before do
@command = API::Command.new('cmdname', 'http', :secure => true)
end
it "should use HTTPS" do
url = @command.with_params(:param_one => 'abc', :param_two => '123')
url.should == URI.parse("https://api.clickatell.com/http/cmdname?param_one=abc¶m_two=123")
end
end
describe "Command executor" do
it "should create an API command with the given params" do
executor = API::CommandExecutor.new(:session_id => '12345')
executor.stubs(:get_response).returns([])
API::Command.expects(:new).with('cmdname', 'http', :secure => false).returns(command = stub('Command'))
command.expects(:with_params).with(:param_one => 'foo', :session_id => '12345').returns(stub_everything('URI'))
executor.execute('cmdname', 'http', :param_one => 'foo')
end
it "should send the URI generated by the created command via HTTP get and return the response" do
executor = API::CommandExecutor.new(:session_id => '12345')
command_uri = URI.parse('http://clickatell.com:8080/path?foo=bar')
API::Command.stubs(:new).returns(command = stub('Command', :with_params => command_uri))
Net::HTTP.stubs(:new).with(command_uri.host, command_uri.port).returns(http = FakeHttp.new)
http.stubs(:use_ssl=)
http.stubs(:get).with('/path?foo=bar').returns([response = stub('HTTP Response'), 'response body'])
executor.execute('cmdname', 'http').should == response
end
it "should send the command over a secure HTTPS connection if :secure option is set to true" do
executor = API::CommandExecutor.new({:session_id => '12345'}, secure = true)
Net::HTTP.stubs(:new).returns(http = mock('HTTP'))
http.expects(:use_ssl=).with(true)
http.stubs(:start).returns([])
executor.execute('cmdname', 'http')
end
end
describe "API" do
before do
API.debug_mode = false
API.secure_mode = false
API.test_mode = false
@executor = mock('command executor')
@api = API.new(:session_id => '1234')
API::CommandExecutor.stubs(:new).with({:session_id => '1234'}, false, false, false).returns(@executor)
end
it "should use the api_id, username and password to authenticate and return the new session id" do
@executor.expects(:execute).with('auth', 'http',
:api_id => '1234',
:user => 'joebloggs',
:password => 'superpass'
).returns(response = stub('response'))
Response.stubs(:parse).with(response).returns('OK' => 'new_session_id')
@api.authenticate('1234', 'joebloggs', 'superpass').should == 'new_session_id'
end
it "should support ping, using the current session_id" do
@executor.expects(:execute).with('ping', 'http', :session_id => 'abcdefg').returns(response = stub('response'))
@api.ping('abcdefg').should == response
end
it "should support sending messages to a specified number, returning the message id" do
@executor.expects(:execute).with('sendmsg', 'http',
:to => '4477791234567',
:text => 'hello world & goodbye'
).returns(response = stub('response'))
Response.stubs(:parse).with(response).returns('ID' => 'message_id')
@api.send_message('4477791234567', 'hello world & goodbye').should == 'message_id'
end
it "should support sending messages to a multiple numbers, returning the message ids" do
@executor.expects(:execute).with('sendmsg', 'http',
:to => '4477791234567,447779999999',
:text => 'hello world & goodbye'
).returns(response = stub('response'))
Response.stubs(:parse).with(response).returns([{'ID' => 'message_1_id'}, {'ID' => 'message_2_id'}])
@api.send_message(['4477791234567', '447779999999'], 'hello world & goodbye').should == ['message_1_id', 'message_2_id']
end
it "should set the :from parameter and set the :req_feat to 48 when using a custom from string when sending a message" do
@executor.expects(:execute).with('sendmsg', 'http', has_entries(:from => 'LUKE', :req_feat => '48')).returns(response = stub('response'))
Response.stubs(:parse).with(response).returns('ID' => 'message_id')
@api.send_message('4477791234567', 'hello world', :from => 'LUKE')
end
it "should set the :concat parameter when the message is longer than 160 characters" do
@executor.expects(:execute).with('sendmsg', 'http', has_entries(:concat => 2)).returns(response = stub('response'))
Response.stubs(:parse).with(response).returns('ID' => 'message_id')
@api.send_message('4477791234567', 't'*180)
end
it "should set the callback flag to the number passed in the options hash" do
@executor.expects(:execute).with('sendmsg', 'http', has_entry(:callback => 1)).returns(response=mock('response'))
Response.stubs(:parse).with(response).returns('ID' => 'message_id')
@api.send_message('4477791234567', 'hello world', :callback => 1)
end
it "should set the client message id to the number passed in the options hash" do
@executor.expects(:execute).with('sendmsg', 'http', has_entry(:climsgid => 12345678)).returns(response=mock('response'))
Response.stubs(:parse).with(response).returns('ID' => 'message_id')
@api.send_message('4477791234567', 'hello world', :client_message_id => 12345678)
end
it "should set the concat flag to the number passed in the options hash" do
@executor.expects(:execute).with('sendmsg', 'http', has_entry(:concat => 3)).returns(response=mock('response'))
Response.stubs(:parse).with(response).returns('ID' => 'message_id')
@api.send_message('4477791234567', 'hello world', :concat => 3)
end
it "should ignore any invalid parameters when sending a message" do
@executor.expects(:execute).with('sendmsg', 'http', Not(has_key(:any_old_param))).returns(response = stub('response'))
Response.stubs(:parse).returns('ID' => 'foo')
@api.send_message('4477791234567', 'hello world', :from => 'LUKE', :any_old_param => 'test')
end
it "should support message status query for a given message id, returning the message status" do
@executor.expects(:execute).with('querymsg', 'http', :apimsgid => 'messageid').returns(response = stub('response'))
Response.expects(:parse).with(response).returns('ID' => 'message_id', 'Status' => 'message_status')
@api.message_status('messageid').should == 'message_status'
end
it "should support balance query, returning number of credits as a float" do
@executor.expects(:execute).with('getbalance', 'http', {}).returns(response=mock('response'))
Response.stubs(:parse).with(response).returns('Credit' => '10.0')
@api.account_balance.should == 10.0
end
it "should raise an API::Error if the response parser raises" do
@executor.stubs(:execute)
Response.stubs(:parse).raises(Clickatell::API::Error.new('', ''))
proc { @api.account_balance }.should raise_error(Clickatell::API::Error)
end
end
describe API, ' when authenticating' do
it "should authenticate to retrieve a session_id and return a new API instance using that session id" do
API.stubs(:new).returns(api = mock('api'))
api.stubs(:authenticate).with('my_api_key', 'joebloggs', 'mypassword').returns('new_session_id')
api.expects(:auth_options=).with(:session_id => 'new_session_id')
API.authenticate('my_api_key', 'joebloggs', 'mypassword')
end
end
describe API, ' with no authentication options set' do
it "should build commands with no authentication options" do
api = API.new
API::CommandExecutor.stubs(:new).with({}, false, false, false).returns(executor = stub('command executor'))
executor.stubs(:execute)
api.ping('1234')
end
end
describe API, ' in secure mode' do
it "should execute commands securely" do
API.secure_mode = true
api = API.new
API::CommandExecutor.expects(:new).with({}, true, false, false).returns(executor = stub('command executor'))
executor.stubs(:execute)
api.ping('1234')
end
end
describe "API Error" do
it "should parse http response string to create error" do
response_string = "ERR: 001, Authentication error"
error = Clickatell::API::Error.parse(response_string)
error.code.should == '001'
error.message.should == 'Authentication error'
end
end
describe API, "#test_mode" do
before(:each) do
API.secure_mode = false
API.test_mode = true
@api = API.new
end
it "should create a new CommandExecutor with test_mode parameter set to true" do
API::CommandExecutor.expects(:new).with({}, false, false, true).once.returns(executor = mock('command executor'))
executor.stubs(:execute)
executor.stubs(:sms_requests).returns([])
@api.ping('1234')
end
it "should record all commands" do
@api.ping('1234')
@api.sms_requests.should_not be_empty
end
it "should return the recorded commands in a flattened array" do
@api.ping('1234')
@api.sms_requests.size.should == 1
@api.sms_requests.first.should_not be_instance_of(Array)
end
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/spec/command_executor_spec.rb | spec/command_executor_spec.rb | require File.dirname(__FILE__) + '/spec_helper'
require File.dirname(__FILE__) + '/../lib/clickatell'
module Clickatell
describe "API::CommandExecutor" do
it "should have test mode" do
executor = API::CommandExecutor.new({}, false, false, :test_mode)
executor.should be_in_test_mode
end
it "should default to not test mode" do
executor = API::CommandExecutor.new({})
executor.should_not be_in_test_mode
end
describe "#execute" do
describe "in non-test mode" do
before(:each) do
@executor = API::CommandExecutor.new({})
end
it "should not record requests" do
@executor.should_not respond_to(:sms_requests)
end
describe "without a proxy" do
before do
@http = mock()
@http.expects(:use_ssl=).with(false)
@http.expects(:start).returns([])
Net::HTTP.expects(:new).with(API::Command::API_SERVICE_HOST, 80).returns(@http)
end
it "should execute commands through the proxy" do
@executor.execute("foo", "http")
end
end
describe "with a proxy" do
before do
API.proxy_host = @proxy_host = "proxy.example.com"
API.proxy_port = @proxy_port = "1234"
API.proxy_username = @proxy_username = "joeschlub"
API.proxy_password = @proxy_password = "secret"
@http = mock()
@http.expects(:start).with(API::Command::API_SERVICE_HOST).returns([])
Net::HTTP.expects(:Proxy).with(@proxy_host, @proxy_port, @proxy_username, @proxy_password).returns(@http)
end
it "should execute commands through the proxy" do
@executor.execute("foo", "http")
end
end
end
describe "in test mode" do
before(:each) do
@params = {:foo => 1, :bar => 2}
@executor = API::CommandExecutor.new(@params, false, false, :test_mode)
end
it "should not make any network calls" do
Net::HTTP.expects(:new).never
@executor.execute("foo", "http")
end
it "should start with an empty request collection" do
@executor.sms_requests.should be_empty
end
it "should record sms requests" do
@executor.execute("bar", "http")
@executor.sms_requests.should_not be_empty
end
it "should record a request for each call" do
@executor.execute("wibble", "http")
@executor.sms_requests.size.should == 1
@executor.execute("foozle", "http")
@executor.sms_requests.size.should == 2
end
it "should return a response that approximates a true Net::HttpResponse" do
response = @executor.execute("throat-warbler", "http")
response.body.should == "test"
end
describe "each recorded request" do
it "should return the command information" do
command = "rum_tum_tum"
@executor.execute(command, "http")
uri = @executor.sms_requests.first
uri.host.should == "api.clickatell.com"
uri.path.should include(command)
@params.collect { |k, v| "#{k}=#{v}"}.each do |query_parameter|
uri.query.should include(query_parameter)
end
end
end
end
end
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/spec/cli_options_spec.rb | spec/cli_options_spec.rb | require File.dirname(__FILE__) + '/spec_helper'
require File.dirname(__FILE__) + '/../lib/clickatell/utility'
describe "CLI options" do
context "when sending a message" do
it "should allow single recipients" do
options = Clickatell::Utility::Options.parse(%w{07944123456 testing})
options.recipient.should include("07944123456")
end
it "should allow multiple, comma-separated recipients" do
options = Clickatell::Utility::Options.parse(%w{07944123456,07944123457 testing})
options.recipient.should include(*%w{07944123456 07944123457})
end
it "should strip + symbols from the beginning of numbers" do
options = Clickatell::Utility::Options.parse(%w{+447944123456 testing})
options.recipient.should include("447944123456")
end
end
context "when checking balance" do
it "should not require a recipient" do
options = Clickatell::Utility::Options.parse(%w{-b})
options.recipient.should be_nil
end
end
end
| ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/spec/hash_ext_spec.rb | spec/hash_ext_spec.rb | require File.dirname(__FILE__) + '/spec_helper'
require File.dirname(__FILE__) + '/../lib/clickatell'
describe Hash do
it "should return only the keys specified" do
hash = {:a => 'foo', :b => 'bar', :c => 'baz'}
hash.only(:a, :b).should == {:a => 'foo', :b => 'bar'}
end
it "should return only the keys specified, ignoring keys that do not exist" do
hash = {:a => 'foo', :b => 'bar', :c => 'baz'}
hash.only(:a, :d).should == {:a => 'foo'}
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/spec/spec_helper.rb | spec/spec_helper.rb | require 'rubygems'
require 'spec'
require 'mocha'
require 'test/unit'
Spec::Runner.configure do |config|
config.mock_with :mocha
end
| ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell.rb | lib/clickatell.rb | module Clickatelll end
%w( core-ext/hash
clickatell/version
clickatell/api
clickatell/response
).each do |lib|
require File.join(File.dirname(__FILE__), lib)
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/core-ext/hash.rb | lib/core-ext/hash.rb | class Hash
# Returns a new hash containing only the keys specified
# that exist in the current hash.
#
# {:a => '1', :b => '2', :c => '3'}.only(:a, :c)
# # => {:a => '1', :c => '3'}
#
# Keys that do not exist in the original hash are ignored.
def only(*keys)
inject( {} ) do |new_hash, (key, value)|
new_hash[key] = value if keys.include?(key)
new_hash
end
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/version.rb | lib/clickatell/version.rb | module Clickatell #:nodoc:
module VERSION #:nodoc:
MAJOR = 0
MINOR = 9
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
def self.to_s
STRING
end
end
end
| ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/utility.rb | lib/clickatell/utility.rb | module Clickatell
module Utility
end
end
require File.join(File.dirname(__FILE__), *%w[utility/options]) | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/response.rb | lib/clickatell/response.rb | require 'yaml'
module Clickatell
# Used to parse HTTP responses returned from Clickatell API calls.
class Response
class << self
PARSE_REGEX = /[A-Za-z0-9]+:.*?(?:(?=[A-Za-z0-9]+:)|$)/
# Returns the HTTP response body data as a hash.
def parse(http_response)
return { 'OK' => 'session_id' } if API.test_mode
if http_response.body.scan(/ERR/).any?
raise Clickatell::API::Error.parse(http_response.body)
end
results = http_response.body.split("\n").map do |line|
# YAML.load converts integer strings that have leading zeroes into integers
# using octal rather than decimal. This isn't what we want, so we'll strip out any
# leading zeroes in numbers here.
response_fields = line.scan(PARSE_REGEX)
response_fields = response_fields.collect { |field| field.gsub(/\b0+(\d+)\b/, '\1') }
YAML.load(response_fields.join("\n"))
end
results.length == 1 ? results.first : results
end
end
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/api.rb | lib/clickatell/api.rb | module Clickatell
# This module provides the core implementation of the Clickatell
# HTTP service.
class API
attr_accessor :auth_options
class << self
# Authenticates using the given credentials and returns an
# API instance with the authentication options set to use the
# resulting session_id.
def authenticate(api_id, username, password)
api = self.new
session_id = api.authenticate(api_id, username, password)
api.auth_options = { :session_id => session_id }
api
end
# Set to true to enable debugging (off by default)
attr_accessor :debug_mode
# Enable secure mode (SSL)
attr_accessor :secure_mode
# Allow customizing URL
attr_accessor :api_service_host
# Set to your HTTP proxy details (off by default)
attr_accessor :proxy_host, :proxy_port, :proxy_username, :proxy_password
# Set to true to test message sending; this will not actually send
# messages but will collect sent messages in a testable collection.
# (off by default)
attr_accessor :test_mode
end
self.debug_mode = false
self.secure_mode = false
self.test_mode = false
# Creates a new API instance using the specified +auth options+.
# +auth_options+ is a hash containing either a :session_id or
# :username, :password and :api_key.
#
# Some API calls (authenticate, ping etc.) do not require any
# +auth_options+. +auth_options+ can be updated using the accessor methods.
def initialize(auth_options={})
@auth_options = auth_options
end
# Authenticates using the specified credentials. Returns
# a session_id if successful which can be used in subsequent
# API calls.
def authenticate(api_id, username, password)
response = execute_command('auth', 'http',
:api_id => api_id,
:user => username,
:password => password
)
parse_response(response)['OK']
end
# Pings the service with the specified session_id to keep the
# session alive.
def ping(session_id)
execute_command('ping', 'http', :session_id => session_id)
end
# Sends a message +message_text+ to +recipient+. Recipient
# number should have an international dialing prefix and
# no leading zeros (unless you have set a default prefix
# in your clickatell account centre).
#
# Messages over 160 characters are split into multiple messages automatically,
# and the :concat option will be set, overwriting any manual value of this option.
#
# You normally wouldn't need to set :concat manually and can rely on the automatica
# splitting behaviour.
#
# Additional options:
# :from - the from number/name
# :set_mobile_originated - mobile originated flag
# :client_message_id - user specified message id that can be used in place of Clickatell issued API message ID for querying message
# :concat - number of concatenations allowed. I.E. how long is a message allowed to be.
# Returns a new message ID if successful.
def send_message(recipient, message_text, opts={})
valid_options = opts.only(:from, :mo, :callback, :climsgid, :concat)
valid_options.merge!(:req_feat => '48') if valid_options[:from]
valid_options.merge!(:mo => '1') if opts[:set_mobile_originated]
valid_options.merge!(:climsgid => opts[:client_message_id]) if opts[:client_message_id]
if message_text.length > 160
valid_options.merge!(:concat => (message_text.length.to_f / 160).ceil)
end
recipient = recipient.join(",")if recipient.is_a?(Array)
response = execute_command('sendmsg', 'http',
{:to => recipient, :text => message_text}.merge(valid_options)
)
response = parse_response(response)
response.is_a?(Array) ? response.map { |r| r['ID'] } : response['ID']
end
def send_wap_push(recipient, media_url, notification_text='', opts={})
valid_options = opts.only(:from)
valid_options.merge!(:req_feat => '48') if valid_options[:from]
response = execute_command('si_push', 'mms',
{:to => recipient, :si_url => media_url, :si_text => notification_text, :si_id => 'foo'}.merge(valid_options)
)
parse_response(response)['ID']
end
# Returns the status of a message. Use message ID returned
# from original send_message call.
def message_status(message_id)
response = execute_command('querymsg', 'http', :apimsgid => message_id)
parse_response(response)['Status']
end
def message_charge(message_id)
response = execute_command('getmsgcharge', 'http', :apimsgid => message_id)
parse_response(response)['charge'].to_f
end
# Returns the number of credits remaining as a float.
def account_balance
response = execute_command('getbalance', 'http')
parse_response(response)['Credit'].to_f
end
def sms_requests
@sms_requests ||= []
end
protected
def execute_command(command_name, service, parameters={}) #:nodoc:
executor = CommandExecutor.new(auth_hash, self.class.secure_mode, self.class.debug_mode, self.class.test_mode)
result = executor.execute(command_name, service, parameters)
(sms_requests << executor.sms_requests).flatten! if self.class.test_mode
result
end
def parse_response(raw_response) #:nodoc:
Clickatell::Response.parse(raw_response)
end
def auth_hash #:nodoc:
if @auth_options[:session_id]
{ :session_id => @auth_options[:session_id] }
elsif @auth_options[:api_id]
{ :user => @auth_options[:username],
:password => @auth_options[:password],
:api_id => @auth_options[:api_key] }
else
{}
end
end
end
end
%w( api/command
api/command_executor
api/error
api/message_status
).each do |lib|
require File.join(File.dirname(__FILE__), lib)
end
| ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/api/command.rb | lib/clickatell/api/command.rb | require "cgi"
module Clickatell
class API
# Represents a Clickatell HTTP gateway command in the form
# of a complete URL (the raw, low-level request).
class Command
API_SERVICE_HOST = 'api.clickatell.com'
def initialize(command_name, service = 'http', opts={})
@command_name = command_name
@service = service
@options = { :secure => false }.merge(opts)
end
# Returns a URL for the given parameters (a hash).
def with_params(param_hash)
param_string = '?' + param_hash.map { |key, value| "#{::CGI.escape(key.to_s)}=#{::CGI.escape(value.to_s)}" }.sort.join('&')
return URI.parse(File.join(api_service_uri, @command_name + param_string))
end
protected
def api_service_uri
protocol = @options[:secure] ? 'https' : 'http'
api_service_host = ((Clickatell::API.api_service_host.nil? || Clickatell::API.api_service_host.empty?) ? API_SERVICE_HOST : Clickatell::API.api_service_host)
return "#{protocol}://#{api_service_host}/#{@service}/"
end
end
end
end
| ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/api/message_status.rb | lib/clickatell/api/message_status.rb | module Clickatell
class API
class MessageStatus
STATUS_MAP = {
'001' => 'Message unknown',
'002' => 'Message queued',
'003' => 'Delivered to gateway',
'004' => 'Received by recipient',
'005' => 'Error with message',
'006' => 'User cancelled messaged delivery',
'007' => 'Error delivering message',
'008' => 'OK',
'009' => 'Routing error',
'010' => 'Message expired',
'011' => 'Message queued for later delivery',
'012' => 'Out of credit'
}
def self.[](code)
STATUS_MAP[code]
end
end
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/api/command_executor.rb | lib/clickatell/api/command_executor.rb | require 'net/http'
require 'net/https'
module Clickatell
class API
class FakeHttpResponse
def body
"test"
end
end
# Used to run commands agains the Clickatell gateway.
class CommandExecutor
def initialize(authentication_hash, secure=false, debug=false, test_mode=false)
@authentication_hash = authentication_hash
@debug = debug
@secure = secure
@test_mode = test_mode
allow_request_recording if @test_mode
end
def in_test_mode?
@test_mode
end
# Builds a command object and sends it using HTTP GET.
# Will output URLs as they are requested to stdout when
# debugging is enabled.
def execute(command_name, service, parameters={})
request_uri = command(command_name, service, parameters)
puts "[debug] Sending request to #{request_uri}" if @debug
result = get_response(request_uri)
if result.is_a?(Array)
result = result.first
end
result
end
protected
def command(command_name, service, parameters) #:nodoc:
Command.new(command_name, service, :secure => @secure).with_params(
parameters.merge(@authentication_hash)
)
end
def get_response(uri)
if in_test_mode?
sms_requests << uri
[FakeHttpResponse.new]
else
request = [uri.path, uri.query].join('?')
if API.proxy_host
http = Net::HTTP::Proxy(API.proxy_host, API.proxy_port, API.proxy_username, API.proxy_password)
http.start(uri.host) do |http|
resp, body = http.get(request)
end
else
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')
http.start do |http|
resp, body = http.get(request)
end
end
end
end
private
def allow_request_recording
class << self
define_method :sms_requests do
@sms_requests ||= []
end
end
end
end
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/api/error.rb | lib/clickatell/api/error.rb | module Clickatell
class API
# Clickatell API Error exception.
class Error < StandardError
attr_reader :code, :message
def initialize(code, message)
@code, @message = code, message
end
# Creates a new Error from a Clickatell HTTP response string
# e.g.:
#
# Error.parse("ERR: 001, Authentication error")
# # => #<Clickatell::API::Error code='001' message='Authentication error'>
def self.parse(error_string)
error_details = error_string.split(':').last.strip
code, message = error_details.split(',').map { |s| s.strip }
self.new(code, message)
end
end
end
end | ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
lukeredpath/clickatell | https://github.com/lukeredpath/clickatell/blob/46c792fe2428a371fc01aff87a67e6dd853e8ca2/lib/clickatell/utility/options.rb | lib/clickatell/utility/options.rb | require 'optparse'
require 'ostruct'
module Clickatell
module Utility
class Options #:nodoc:
class << self
def parse(args)
@options = self.default_options
parser = OptionParser.new do |opts|
opts.banner = "Usage: sms [options] recipient(s) message"
opts.separator " Recipients can be a comma-separated list, up to 100 max."
opts.separator ""
opts.separator "Specific options:"
opts.on('-u', '--username USERNAME',
"Specify the clickatell username (overrides ~/.clickatell setting)") do |username|
@options.username = username
end
opts.on('-p', '--password PASSWORD',
"Specify the clickatell password (overrides ~/.clickatell setting)") do |password|
@options.password = password
end
opts.on('-k', '--apikey API_KEY',
"Specify the clickatell API key (overrides ~/.clickatell setting)") do |key|
@options.api_key = key
end
opts.on('-f', '--from NAME_OR_NUMBER',
"Specify the name or number that the SMS will appear from") do |from|
@options.from = from
end
opts.on('-b', '--show-balance',
"Shows the total number of credits remaining on your account") do
@options.show_balance = true
end
opts.on('-s', '--status MESSAGE_ID',
"Displays the status of the specified message.") do |message_id|
@options.message_id = message_id
@options.show_status = true
end
opts.on('-S', '--secure',
"Sends request using HTTPS") do
Clickatell::API.secure_mode = true
end
opts.on('-d', '--debug') do
Clickatell::API.debug_mode = true
end
opts.on_tail('-h', '--help', "Show this message") do
puts opts
exit
end
opts.on_tail('-v', '--version') do
puts "Ruby Clickatell SMS Utility #{Clickatell::VERSION}"
exit
end
end
@options.recipient = args[-2].split(',').map { |r| r.gsub(/^\+/, '') } rescue nil
@options.message = args[-1]
parser.parse!(args)
if (@options.message.nil? || @options.recipient.nil?) && send_message?
puts "You must specify a recipient and message!"
puts parser
exit
end
return @options
rescue OptionParser::MissingArgument => e
switch_given = e.message.split(':').last.strip
puts "The #{switch_given} option requires an argument."
puts parser
exit
end
def default_options
options = OpenStruct.new
config_file = File.open(File.join(ENV['HOME'], '.clickatell'))
config = YAML.load(config_file)
options.username = config['username']
options.password = config['password']
options.api_key = config['api_key']
options.from = config['from']
return options
rescue Errno::ENOENT
return options
end
def send_message?
(@options.show_status.nil? &&
@options.show_balance.nil?)
end
end
end
end
end
| ruby | MIT | 46c792fe2428a371fc01aff87a67e6dd853e8ca2 | 2026-01-04T17:44:39.972988Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/spec/gems_spec.rb | spec/gems_spec.rb | require 'helper'
describe Gems do
after do
Gems.reset
end
context 'when delegating to a client' do
before do
stub_get('/api/v1/gems/rails.json').
to_return(:body => fixture('rails.json'))
end
it 'gets the correct resource' do
Gems.info('rails')
expect(a_get('/api/v1/gems/rails.json')).to have_been_made
end
it 'returns the same results as a client' do
expect(Gems.info('rails')).to eq Gems::Client.new.info('rails')
end
end
describe '.respond_to?' do
it 'returns true if a method exists' do
expect(Gems).to respond_to(:new)
end
it "returns false if a method doesn't exist" do
expect(Gems).not_to respond_to(:foo)
end
end
describe '.new' do
it 'returns a Gems::Client' do
expect(Gems.new).to be_a Gems::Client
end
end
describe '.host' do
it 'returns the default host' do
expect(Gems.host).to eq Gems::Configuration::DEFAULT_HOST
end
end
describe '.host=' do
it 'sets the host' do
Gems.host = 'http://localhost:3000'
expect(Gems.host).to eq 'http://localhost:3000'
end
end
describe '.user_agent' do
it 'returns the default user agent' do
expect(Gems.user_agent).to eq Gems::Configuration::DEFAULT_USER_AGENT
end
end
describe '.user_agent=' do
it 'sets the user agent' do
Gems.user_agent = 'Custom User Agent'
expect(Gems.user_agent).to eq 'Custom User Agent'
end
end
describe '.configure' do
Gems::Configuration::VALID_OPTIONS_KEYS.each do |key|
it "sets the #{key}" do
Gems.configure do |config|
config.send("#{key}=", key)
expect(Gems.send(key)).to eq key
end
end
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/spec/helper.rb | spec/helper.rb | require 'simplecov'
require 'coveralls'
SimpleCov.formatters = [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter]
SimpleCov.start do
add_filter '/spec/'
minimum_coverage(100) unless RUBY_PLATFORM =~ /java/
end
require 'gems'
require 'rspec'
require 'webmock/rspec'
WebMock.disable_net_connect!(:allow => 'coveralls.io')
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
def rubygems_url(url)
url =~ /^http/ ? url : 'https://rubygems.org' + url
end
def a_delete(url)
a_request(:delete, rubygems_url(url))
end
def a_get(url)
a_request(:get, rubygems_url(url))
end
def a_post(url)
a_request(:post, rubygems_url(url))
end
def a_put(url)
a_request(:put, rubygems_url(url))
end
def stub_delete(url)
stub_request(:delete, rubygems_url(url))
end
def stub_get(url)
stub_request(:get, rubygems_url(url))
end
def stub_post(url)
stub_request(:post, rubygems_url(url))
end
def stub_put(url)
stub_request(:put, rubygems_url(url))
end
def fixture_path
File.expand_path('../fixtures', __FILE__)
end
def fixture(file)
File.new(fixture_path + '/' + file)
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/spec/gems/client_v2_spec.rb | spec/gems/client_v2_spec.rb | require 'helper'
describe Gems::V2::Client do
after do
Gems.reset
end
describe '#info' do
context 'when gem exists' do
before do
stub_get('/api/v2/rubygems/rails/versions/7.0.6.json').to_return(body: fixture('v2/rails-7.0.6.json'))
end
it 'returns some basic information about the given gem' do
info = Gems::V2.info 'rails', '7.0.6'
expect(a_get('/api/v2/rubygems/rails/versions/7.0.6.json')).to have_been_made
expect(info['name']).to eq 'rails'
expect(info['version']).to eq '7.0.6'
end
end
context 'when gem version does not exist' do
before do
stub_get('/api/v2/rubygems/rails/versions/7.0.99.json').to_return(body: 'This version could not be found.')
end
it 'returns error message' do
info = Gems::V2.info 'rails', '7.0.99'
expect(a_get('/api/v2/rubygems/rails/versions/7.0.99.json')).to have_been_made
expect(info['name']).to be_nil
end
end
context 'when gem does not exist' do
before do
stub_get('/api/v2/rubygems/nonexistentgem/versions/1.0.0.json').to_return(body: 'This gem could not be found')
end
it 'returns error message' do
info = Gems::V2.info 'nonexistentgem', '1.0.0'
expect(a_get('/api/v2/rubygems/nonexistentgem/versions/1.0.0.json')).to have_been_made
expect(info['name']).to be_nil
end
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/spec/gems/request_spec.rb | spec/gems/request_spec.rb | require 'helper'
describe Gems::Request do
after do
Gems.reset
end
describe '#get with redirect' do
before do
response_body = '<html>\r\n<head><title>302 Found</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>302 Found</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n'
response_location = 'https://bundler.rubygems.org/api/v1/dependencies?gems=rails,thor'
stub_get('/api/v1/dependencies').
with(:query => {'gems' => 'rails,thor'}).
to_return(:body => response_body, :status => 302, :headers => {:location => response_location})
stub_request(:get, 'https://bundler.rubygems.org/api/v1/dependencies').
with(:query => {'gems' => 'rails,thor'}).
to_return(:body => fixture('dependencies'), :status => 200, :headers => {})
end
it 'returns an array of hashes for all versions of given gems' do
dependencies = Gems.dependencies 'rails', 'thor'
expect(a_get('/api/v1/dependencies').with(:query => {'gems' => 'rails,thor'})).to have_been_made
expect(a_get('https://bundler.rubygems.org/api/v1/dependencies').with(:query => {'gems' => 'rails,thor'})).to have_been_made
expect(dependencies.first[:number]).to eq '3.0.9'
end
end
describe '#get with 404' do
before do
response_body = 'This rubygem could not be found.'
stub_get('/api/v1/dependencies').
with(:query => {'gems' => 'rails,thor'}).
to_return(:body => response_body, :status => 404)
end
it 'raise a Gems::NotFound error' do
expect { Gems.dependencies('rails', 'thor') }.to raise_error(Gems::NotFound)
end
end
describe "#get with a non-200" do
before do
response_body = 'Internal Server Error'
stub_get('/api/v1/dependencies').
with(:query => {'gems' => 'rails,thor'}).
to_return(:body => response_body, :status => 500)
end
it 'raise a wrapped Gems::Error' do
expect { Gems.dependencies('rails', 'thor') }.to raise_error(Gems::GemError)
expect(a_get('/api/v1/dependencies').with(:query => {'gems' => 'rails,thor'})).to have_been_made
end
end
describe 'request behind proxy' do
before do
allow(ENV).to receive(:[]).with('no_proxy').and_return('')
allow(ENV).to receive(:[]).with('https_proxy').and_return('http://proxy_user:proxy_pass@192.168.1.99:9999')
stub_get('/api/v1/gems/rails.json').
to_return(:body => fixture('rails.json'))
gems = Gems.new
gems.info 'rails'
@connection = gems.instance_variable_get(:@connection)
end
it { expect(@connection.proxy_address).to eq '192.168.1.99' }
it { expect(@connection.proxy_user).to eq 'proxy_user' }
it { expect(@connection.proxy_pass).to eq 'proxy_pass' }
it { expect(@connection.proxy_port).to eq 9999 }
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/spec/gems/abstract_client_spec.rb | spec/gems/abstract_client_spec.rb | require 'helper'
describe Gems::AbstractClient do
it "raises NotImplementedError if new isn't overritten" do
FooClient = Class.new do
include Gems::AbstractClient
end
expect { FooClient.new }.to raise_error(NotImplementedError)
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/spec/gems/client_v1_spec.rb | spec/gems/client_v1_spec.rb | require 'helper'
describe Gems::Client do
after do
Gems.reset
end
describe '#new' do
it 'creates a new v1 client' do
client = Gems::V1.new
expect(client).to_not be_nil
expect(client.class).to eq(Gems::V1::Client)
end
end
describe '#info' do
context 'when gem exists' do
before do
stub_get('/api/v1/gems/rails.json').
to_return(:body => fixture('rails.json'))
end
it 'returns some basic information about the given gem' do
info = Gems.info 'rails'
expect(a_get('/api/v1/gems/rails.json')).to have_been_made
expect(info['name']).to eq 'rails'
end
end
context 'when gem does not exist' do
before do
stub_get('/api/v1/gems/nonexistentgem.json').
to_return(:body => 'This rubygem could not be found.')
end
it 'returns some basic information about the given gem' do
info = Gems.info 'nonexistentgem'
expect(a_get('/api/v1/gems/nonexistentgem.json')).to have_been_made
expect(info['name']).to be_nil
end
end
end
describe '#search' do
before do
stub_get('/api/v1/search.json').
with(:query => {'query' => 'cucumber'}).
to_return(:body => fixture('search.json'))
stub_get('/api/v1/search.json').
with(:query => {'query' => 'cucumber', 'page' => '2'}).
to_return(:body => fixture('search.json'))
end
it 'returns an array of active gems that match the query' do
search = Gems.search 'cucumber'
expect(a_get('/api/v1/search.json').with(:query => {'query' => 'cucumber'})).to have_been_made
expect(search.first['name']).to eq 'cucumber'
end
it 'allows passing a page parameter' do
Gems.search 'cucumber', :page => 2
expect(a_get('/api/v1/search.json').with(:query => {'query' => 'cucumber', 'page' => '2'})).to have_been_made
end
end
describe '#gems' do
context 'with no user handle specified' do
before do
stub_get('/api/v1/gems.json').
to_return(:body => fixture('gems.json'))
end
it 'lists all gems that you own' do
gems = Gems.gems
expect(a_get('/api/v1/gems.json')).to have_been_made
expect(gems.first['name']).to eq 'exchb'
end
end
context 'with a user handle specified' do
before do
stub_get('/api/v1/owners/sferik/gems.json').
to_return(:body => fixture('gems.json'))
end
it 'lists all gems that the specified user owns' do
gems = Gems.gems('sferik')
expect(a_get('/api/v1/owners/sferik/gems.json')).to have_been_made
expect(gems.first['name']).to eq 'exchb'
end
end
end
describe '#push' do
context 'without the host parameter' do
before do
stub_post('/api/v1/gems').
to_return(:body => fixture('push'))
end
it 'submits a gem to RubyGems.org' do
push = Gems.push(File.new(File.expand_path('../../fixtures/gems-0.0.8.gem', __FILE__), 'rb'))
expect(a_post('/api/v1/gems')).to have_been_made
expect(push).to eq 'Successfully registered gem: gems (0.0.8)'
end
end
context 'with the host parameter' do
before do
stub_post('http://example.com/api/v1/gems').
to_return(:body => fixture('push'))
end
it 'submits a gem to the passed host' do
push = Gems.push(File.new(File.expand_path('../../fixtures/gems-0.0.8.gem', __FILE__), 'rb'), 'http://example.com')
expect(a_post('http://example.com/api/v1/gems'))
expect(push).to eq 'Successfully registered gem: gems (0.0.8)'
end
end
end
describe '#yank' do
context 'with no version specified' do
before do
stub_get('/api/v1/gems/gems.json').
to_return(:body => fixture('rails.json'))
stub_delete('/api/v1/gems/yank').
with(:query => {:gem_name => 'gems', :version => '3.0.9'}).
to_return(:body => fixture('yank'))
end
it "removes a gem from RubyGems.org's index" do
yank = Gems.yank('gems')
expect(a_delete('/api/v1/gems/yank').with(:query => {:gem_name => 'gems', :version => '3.0.9'})).to have_been_made
expect(yank).to eq 'Successfully yanked gem: gems (0.0.8)'
end
end
context 'with a version specified' do
before do
stub_delete('/api/v1/gems/yank').
with(:query => {:gem_name => 'gems', :version => '0.0.8'}).
to_return(:body => fixture('yank'))
end
it "removes a gem from RubyGems.org's index" do
yank = Gems.yank('gems', '0.0.8')
expect(a_delete('/api/v1/gems/yank').with(:query => {:gem_name => 'gems', :version => '0.0.8'})).to have_been_made
expect(yank).to eq 'Successfully yanked gem: gems (0.0.8)'
end
end
end
describe '#unyank' do
context 'with no version specified' do
before do
stub_get('/api/v1/gems/gems.json').
to_return(:body => fixture('rails.json'))
stub_put('/api/v1/gems/unyank').
with(:body => {:gem_name => 'gems', :version => '3.0.9'}).
to_return(:body => fixture('unyank'))
end
it "updates a previously yanked gem back into RubyGems.org's index" do
unyank = Gems.unyank('gems')
expect(a_put('/api/v1/gems/unyank').with(:body => {:gem_name => 'gems', :version => '3.0.9'})).to have_been_made
expect(unyank).to eq 'Successfully unyanked gem: gems (0.0.8)'
end
end
context 'with a version specified' do
before do
stub_put('/api/v1/gems/unyank').
with(:body => {:gem_name => 'gems', :version => '0.0.8'}).
to_return(:body => fixture('unyank'))
end
it "updates a previously yanked gem back into RubyGems.org's index" do
unyank = Gems.unyank('gems', '0.0.8')
expect(a_put('/api/v1/gems/unyank').with(:body => {:gem_name => 'gems', :version => '0.0.8'})).to have_been_made
expect(unyank).to eq 'Successfully unyanked gem: gems (0.0.8)'
end
end
end
describe '#versions' do
before do
stub_get('/api/v1/versions/script_helpers.json').
to_return(:body => fixture('script_helpers.json'))
end
it 'returns an array of gem version details' do
versions = Gems.versions 'script_helpers'
expect(a_get('/api/v1/versions/script_helpers.json')).to have_been_made
expect(versions.first['number']).to eq '0.1.0'
end
end
describe '#latest_version' do
before do
stub_get('/api/v1/versions/script_helpers/latest.json').
to_return(:body => fixture('script_helpers/latest.json'))
end
it 'returns an hash of gem latest version' do
latest_version = Gems.latest_version 'script_helpers'
expect(a_get('/api/v1/versions/script_helpers/latest.json')).to have_been_made
expect(latest_version['version']).to eq '0.3.0'
end
end
describe '#total_downloads' do
context 'with no version or gem name specified' do
before do
stub_get('/api/v1/downloads.json').
to_return(:body => fixture('total_downloads.json'))
end
it 'returns the total number of downloads on RubyGems.org' do
downloads = Gems.total_downloads
expect(a_get('/api/v1/downloads.json')).to have_been_made
expect(downloads[:total]).to eq 244_368_950
end
end
context 'with no version specified' do
before do
stub_get('/api/v1/gems/rails_admin.json').
to_return(:body => fixture('rails.json'))
stub_get('/api/v1/downloads/rails_admin-3.0.9.json').
to_return(:body => fixture('rails_admin-0.0.0.json'))
end
it 'returns the total number of downloads for the specified gem' do
downloads = Gems.total_downloads('rails_admin')
expect(a_get('/api/v1/gems/rails_admin.json')).to have_been_made
expect(a_get('/api/v1/downloads/rails_admin-3.0.9.json')).to have_been_made
expect(downloads[:version_downloads]).to eq 3142
expect(downloads[:total_downloads]).to eq 3142
end
end
context 'with a version specified' do
before do
stub_get('/api/v1/downloads/rails_admin-0.0.0.json').
to_return(:body => fixture('rails_admin-0.0.0.json'))
end
it 'returns the total number of downloads for the specified gem' do
downloads = Gems.total_downloads('rails_admin', '0.0.0')
expect(a_get('/api/v1/downloads/rails_admin-0.0.0.json')).to have_been_made
expect(downloads[:version_downloads]).to eq 3142
expect(downloads[:total_downloads]).to eq 3142
end
end
end
describe '#most_downloaded' do
context 'with nothing specified' do
before do
stub_get('/api/v1/downloads/all.json').
to_return(:body => fixture('most_downloaded.json'))
end
it 'returns the most downloaded versions' do
most_downloaded = Gems.most_downloaded
expect(a_get('/api/v1/downloads/all.json')).to have_been_made
expect(most_downloaded.first.first['full_name']).to eq 'abstract-1.0.0'
expect(most_downloaded.first.last).to eq 1
end
end
end
describe '#downloads' do
context 'with no dates or version specified' do
before do
stub_get('/api/v1/gems/coulda.json').
to_return(:body => fixture('rails.json'))
stub_get('/api/v1/versions/coulda-3.0.9/downloads.json').
to_return(:body => fixture('downloads.json'))
end
it 'returns the number of downloads by day for a particular gem version' do
downloads = Gems.downloads 'coulda'
expect(a_get('/api/v1/gems/coulda.json')).to have_been_made
expect(a_get('/api/v1/versions/coulda-3.0.9/downloads.json')).to have_been_made
expect(downloads['2011-06-22']).to eq 8
end
end
context 'with no dates specified' do
before do
stub_get('/api/v1/versions/coulda-0.6.3/downloads.json').
to_return(:body => fixture('downloads.json'))
end
it 'returns the number of downloads by day for a particular gem version' do
downloads = Gems.downloads 'coulda', '0.6.3'
expect(a_get('/api/v1/versions/coulda-0.6.3/downloads.json')).to have_been_made
expect(downloads['2011-06-22']).to eq 8
end
end
context 'with from date specified' do
before do
stub_get('/api/v1/versions/coulda-0.6.3/downloads/search.json').
with(:query => {'from' => '2011-01-01', 'to' => Date.today.to_s}).
to_return(:body => fixture('downloads.json'))
end
it 'returns the number of downloads by day for a particular gem version' do
downloads = Gems.downloads 'coulda', '0.6.3', Date.parse('2011-01-01')
expect(a_get('/api/v1/versions/coulda-0.6.3/downloads/search.json').with(:query => {'from' => '2011-01-01', 'to' => Date.today.to_s})).to have_been_made
expect(downloads['2011-06-22']).to eq 8
end
end
context 'with from and to dates specified' do
before do
stub_get('/api/v1/versions/coulda-0.6.3/downloads/search.json').
with(:query => {'from' => '2011-01-01', 'to' => '2011-06-28'}).
to_return(:body => fixture('downloads.json'))
end
it 'returns the number of downloads by day for a particular gem version' do
downloads = Gems.downloads 'coulda', '0.6.3', Date.parse('2011-01-01'), Date.parse('2011-06-28')
expect(a_get('/api/v1/versions/coulda-0.6.3/downloads/search.json').with(:query => {'from' => '2011-01-01', 'to' => '2011-06-28'})).to have_been_made
expect(downloads['2011-06-22']).to eq 8
end
end
end
describe '#owners' do
before do
stub_get('/api/v1/gems/gems/owners.json').
to_return(:body => fixture('owners.json'))
end
it 'lists all owners of a gem' do
owners = Gems.owners('gems')
expect(a_get('/api/v1/gems/gems/owners.json')).to have_been_made
expect(owners.first['email']).to eq 'sferik@gmail.com'
end
end
describe '#add_owner' do
before do
stub_post('/api/v1/gems/gems/owners').
with(:body => {:email => 'sferik@gmail.com'}).
to_return(:body => fixture('add_owner'))
end
it 'adds an owner to a RubyGem' do
owner = Gems.add_owner('gems', 'sferik@gmail.com')
expect(a_post('/api/v1/gems/gems/owners').with(:body => {:email => 'sferik@gmail.com'})).to have_been_made
expect(owner).to eq 'Owner added successfully.'
end
end
describe '#remove_owner' do
before do
stub_delete('/api/v1/gems/gems/owners').
with(:query => {:email => 'sferik@gmail.com'}).
to_return(:body => fixture('remove_owner'))
end
it 'removes an owner from a RubyGem' do
owner = Gems.remove_owner('gems', 'sferik@gmail.com')
expect(a_delete('/api/v1/gems/gems/owners').with(:query => {:email => 'sferik@gmail.com'})).to have_been_made
expect(owner).to eq 'Owner removed successfully.'
end
end
describe '#web_hooks' do
before do
stub_get('/api/v1/web_hooks.json').
to_return(:body => fixture('web_hooks.json'))
end
it 'lists the web hooks registered under your account' do
web_hooks = Gems.web_hooks
expect(a_get('/api/v1/web_hooks.json')).to have_been_made
expect(web_hooks['all gems'].first['url']).to eq 'http://example.com'
end
end
describe '#add_web_hook' do
before do
stub_post('/api/v1/web_hooks').
with(:body => {:gem_name => '*', :url => 'http://example.com'}).
to_return(:body => fixture('add_web_hook'))
end
it 'adds a web hook' do
add_web_hook = Gems.add_web_hook('*', 'http://example.com')
expect(a_post('/api/v1/web_hooks').with(:body => {:gem_name => '*', :url => 'http://example.com'})).to have_been_made
expect(add_web_hook).to eq 'Successfully created webhook for all gems to http://example.com'
end
end
describe '#remove_web_hook' do
before do
stub_delete('/api/v1/web_hooks/remove').
with(:query => {:gem_name => '*', :url => 'http://example.com'}).
to_return(:body => fixture('remove_web_hook'))
end
it 'removes a web hook' do
remove_web_hook = Gems.remove_web_hook('*', 'http://example.com')
expect(a_delete('/api/v1/web_hooks/remove').with(:query => {:gem_name => '*', :url => 'http://example.com'})).to have_been_made
expect(remove_web_hook).to eq 'Successfully removed webhook for all gems to http://example.com'
end
end
describe '#fire_web_hook' do
before do
stub_post('/api/v1/web_hooks/fire').
with(:body => {:gem_name => '*', :url => 'http://example.com'}).
to_return(:body => fixture('fire_web_hook'))
end
it 'fires a web hook' do
fire_web_hook = Gems.fire_web_hook('*', 'http://example.com')
expect(a_post('/api/v1/web_hooks/fire').with(:body => {:gem_name => '*', :url => 'http://example.com'})).to have_been_made
expect(fire_web_hook).to eq 'Successfully deployed webhook for gemcutter to http://example.com'
end
end
describe '#latest' do
before do
stub_get('/api/v1/activity/latest.json').
to_return(:body => fixture('latest.json'))
end
it 'returns some basic information about the given gem' do
latest = Gems.latest
expect(a_get('/api/v1/activity/latest.json')).to have_been_made
expect(latest.first['name']).to eq 'seanwalbran-rpm_contrib'
end
end
describe '#just_updated' do
before do
stub_get('/api/v1/activity/just_updated.json').
to_return(:body => fixture('just_updated.json'))
end
it 'returns some basic information about the given gem' do
just_updated = Gems.just_updated
expect(a_get('/api/v1/activity/just_updated.json')).to have_been_made
expect(just_updated.first['name']).to eq 'rspec-tag_matchers'
end
end
describe '#api_key' do
before do
Gems.configure do |config|
config.username = 'nick@gemcutter.org'
config.password = 'schwwwwing'
end
stub_get('https://rubygems.org/api/v1/api_key').
to_return(:body => fixture('api_key'))
end
it 'retrieves an API key' do
api_key = Gems.api_key
expect(a_get('https://rubygems.org/api/v1/api_key')).to have_been_made
expect(api_key).to eq '701243f217cdf23b1370c7b66b65ca97'
end
end
describe '#dependencies' do
before do
stub_get('/api/v1/dependencies').
with(:query => {'gems' => 'rails,thor'}).
to_return(:body => fixture('dependencies'))
end
it 'returns an array of hashes for all versions of given gems' do
dependencies = Gems.dependencies 'rails', 'thor'
expect(a_get('/api/v1/dependencies').with(:query => {'gems' => 'rails,thor'})).to have_been_made
expect(dependencies.first[:number]).to eq '3.0.9'
end
end
describe '#reverse_dependencies' do
before do
stub_get('/api/v1/gems/rspec/reverse_dependencies.json').
to_return(:body => fixture('reverse_dependencies_short.json'))
end
it 'returns an array of names for all gems which are reverse dependencies to the given gem' do
reverse_dependencies = Gems.reverse_dependencies 'rspec'
expect(a_get('/api/v1/gems/rspec/reverse_dependencies.json')).to have_been_made
expect(reverse_dependencies).to be_an_instance_of Array
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems.rb | lib/gems.rb | require 'gems/abstract_client'
require 'gems/v1'
require 'gems/v2'
require 'gems/client'
require 'gems/configuration'
module Gems
extend Configuration
include AbstractClient
# Alias for Gems::Client.new
#
# @return [Gems::Client]
def self.new(options = {})
Gems::Client.new(options)
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/version.rb | lib/gems/version.rb | module Gems
class Version
MAJOR = 1 unless defined? Gems::Version::MAJOR
MINOR = 3 unless defined? Gems::Version::MINOR
PATCH = 0 unless defined? Gems::Version::PATCH
PRE = nil unless defined? Gems::Version::PRE
class << self
# @return [String]
def to_s
[MAJOR, MINOR, PATCH, PRE].compact.join('.')
end
end
end
VERSION = Version.to_s
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/errors.rb | lib/gems/errors.rb | module Gems
class GemError < StandardError; end
class NotFound < GemError; end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/v1.rb | lib/gems/v1.rb | require 'gems/v1/client'
module Gems
module V1
include AbstractClient
# Alias for Gems::V1::Client.new
#
# @return [Gems::V1::Client]
def self.new(options = {})
Gems::V1::Client.new(options)
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/configuration.rb | lib/gems/configuration.rb | require 'gems/version'
require 'rubygems'
require 'yaml'
module Gems
module Configuration
# An array of valid keys in the options hash when configuring a {Gems::Client}
VALID_OPTIONS_KEYS = %i[
host
key
password
user_agent
username
].freeze
# Set the default API endpoint
DEFAULT_HOST = ENV['RUBYGEMS_HOST'] ? ENV['RUBYGEMS_HOST'] : 'https://rubygems.org'
# Set the default credentials
DEFAULT_KEY = Gem.configuration.rubygems_api_key
# Set the default 'User-Agent' HTTP header
DEFAULT_USER_AGENT = "Gems #{Gems::VERSION}".freeze
attr_accessor(*VALID_OPTIONS_KEYS)
# When this module is extended, set all configuration options to their default values
def self.extended(base)
base.reset
end
# Convenience method to allow configuration options to be set in a block
def configure
yield self
end
# Create a hash of options and their values
def options
options = {}
VALID_OPTIONS_KEYS.each { |k| options[k] = send(k) }
options
end
# Reset all configuration options to defaults
def reset
self.username = nil
self.password = nil
self.host = DEFAULT_HOST
self.key = DEFAULT_KEY
self.user_agent = DEFAULT_USER_AGENT
self
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/v2.rb | lib/gems/v2.rb | require 'gems/v2/client'
module Gems
module V2
include AbstractClient
# Alias for Gems::V2::Client.new
#
# @return [Gems::V2::Client]
def self.new(options = {})
Gems::V2::Client.new(options)
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/abstract_client.rb | lib/gems/abstract_client.rb | module Gems
module AbstractClient
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def new(options = {})
raise NotImplementedError.new
end
# Delegate to Gems::Client
def method_missing(method, *args, &block)
return super unless new.respond_to?(method)
new.send(method, *args, &block)
end
def respond_to?(method_name, include_private = false)
new.respond_to?(method_name, include_private) || super(method_name, include_private)
end
def respond_to_missing?(method_name, include_private = false)
new.respond_to?(method_name, include_private) || super(method_name, include_private)
end
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/client.rb | lib/gems/client.rb | module Gems
class Client < V1::Client
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/request.rb | lib/gems/request.rb | require 'net/http'
require 'rubygems'
require 'open-uri'
require 'gems/errors'
module Gems
module Request
def delete(path, data = {}, content_type = 'application/x-www-form-urlencoded', request_host = host)
request(:delete, path, data, content_type, request_host)
end
def get(path, data = {}, content_type = 'application/x-www-form-urlencoded', request_host = host)
request(:get, path, data, content_type, request_host)
end
def post(path, data = {}, content_type = 'application/x-www-form-urlencoded', request_host = host)
request(:post, path, data, content_type, request_host)
end
def put(path, data = {}, content_type = 'application/x-www-form-urlencoded', request_host = host)
request(:put, path, data, content_type, request_host)
end
private
def request(method, path, data, content_type, request_host = host) # rubocop:disable AbcSize, CyclomaticComplexity, MethodLength, ParameterLists, PerceivedComplexity
path += hash_to_query_string(data) if %i[delete get].include? method
uri = URI.parse [request_host, path].join
request_class = Net::HTTP.const_get method.to_s.capitalize
request = request_class.new uri.request_uri
request.add_field 'Authorization', key if key
request.add_field 'Connection', 'keep-alive'
request.add_field 'Keep-Alive', '30'
request.add_field 'User-Agent', user_agent
request.basic_auth username, password if username && password
request.content_type = content_type
case content_type
when 'application/x-www-form-urlencoded'
request.form_data = data if %i[post put].include? method
when 'application/octet-stream'
request.body = data
request.content_length = data.size
end
proxy = uri.find_proxy
@connection = if proxy
Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password).new(uri.host, uri.port)
else
Net::HTTP.new uri.host, uri.port
end
if uri.scheme == 'https'
require 'net/https'
@connection.use_ssl = true
@connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
@connection.start
response = @connection.request request
body_from_response(response, method, content_type)
end
def hash_to_query_string(hash)
return '' if hash.empty?
'?' + URI.encode_www_form(hash)
end
def body_from_response(response, method, content_type)
case response
when Net::HTTPRedirection
uri = URI.parse(response['location'])
host_with_scheme = [uri.scheme, uri.host].join('://')
request(method, uri.request_uri, {}, content_type, host_with_scheme)
when Net::HTTPNotFound
raise Gems::NotFound.new(response.body)
when Net::HTTPSuccess
response.body
else
raise Gems::GemError.new(response.body)
end
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/v1/client.rb | lib/gems/v1/client.rb | require 'date'
require 'gems/configuration'
require 'gems/request'
require 'json'
module Gems
module V1
class Client
include Gems::Request
attr_accessor(*Configuration::VALID_OPTIONS_KEYS)
def initialize(options = {})
options = Gems.options.merge(options)
Configuration::VALID_OPTIONS_KEYS.each do |key|
send("#{key}=", options[key])
end
end
# Returns some basic information about the given gem
#
# @authenticated false
# @param gem_name [String] The name of a gem.
# @return [Hash]
# @example
# Gems.info 'rails'
def info(gem_name)
response = get("/api/v1/gems/#{gem_name}.json")
JSON.parse(response)
rescue JSON::ParserError
{}
end
# Returns an array of active gems that match the query
#
# @authenticated false
# @param query [String] A term to search for.
# @param options [Hash] A customizable set of options.
# @option options [Integer] :page
# @return [Array<Hash>]
# @example
# Gems.search 'cucumber'
def search(query, options = {})
response = get('/api/v1/search.json', options.merge(:query => query))
JSON.parse(response)
end
# List all gems that you own
#
# @authenticated true
# @param user_handle [String] The handle of a user.
# @return [Array]
# @example
# Gems.gems
def gems(user_handle = nil)
response = user_handle ? get("/api/v1/owners/#{user_handle}/gems.json") : get('/api/v1/gems.json')
JSON.parse(response)
end
# Submit a gem to RubyGems.org or another host
#
# @authenticated true
# @param gem [File] A built gem.
# @param host [String] A RubyGems compatible host to use.
# @return [String]
# @example
# Gems.push File.new 'pkg/gemcutter-0.2.1.gem'
def push(gem, host = Configuration::DEFAULT_HOST)
post('/api/v1/gems', gem.read, 'application/octet-stream', host)
end
# Remove a gem from RubyGems.org's index
#
# @authenticated true
# @param gem_name [String] The name of a gem.
# @param gem_version [String] The version of a gem.
# @param options [Hash] A customizable set of options.
# @option options [String] :platform
# @return [String]
# @example
# Gems.yank "gemcutter", "0.2.1", {:platform => "x86-darwin-10"}
def yank(gem_name, gem_version = nil, options = {})
gem_version ||= info(gem_name)['version']
delete('/api/v1/gems/yank', options.merge(:gem_name => gem_name, :version => gem_version))
end
# Update a previously yanked gem back into RubyGems.org's index
#
# @authenticated true
# @param gem_name [String] The name of a gem.
# @param gem_version [String] The version of a gem.
# @param options [Hash] A customizable set of options.
# @option options [String] :platform
# @return [String]
# @example
# Gems.unyank "gemcutter", "0.2.1", {:platform => "x86-darwin-10"}
def unyank(gem_name, gem_version = nil, options = {})
gem_version ||= info(gem_name)['version']
put('/api/v1/gems/unyank', options.merge(:gem_name => gem_name, :version => gem_version))
end
# Returns an array of gem version details
#
# @authenticated false
# @param gem_name [String] The name of a gem.
# @return [Hash]
# @example
# Gems.versions 'coulda'
def versions(gem_name)
response = get("/api/v1/versions/#{gem_name}.json")
JSON.parse(response)
end
# Returns an hash of gem latest version
#
# @authenticated false
# @param gem_name [String] The name of a gem.
# @return [Hash]
# @example
# Gems.latest_version 'coulda'
def latest_version(gem_name)
response = get("/api/v1/versions/#{gem_name}/latest.json")
JSON.parse(response)
end
# Returns the total number of downloads for a particular gem
#
# @authenticated false
# @param gem_name [String] The name of a gem.
# @param gem_version [String] The version of a gem.
# @return [Hash]
# @example
# Gems.total_downloads 'rails_admin', '0.0.1'
def total_downloads(gem_name = nil, gem_version = nil)
response = gem_name ? get("/api/v1/downloads/#{gem_name}-#{gem_version || info(gem_name)['version']}.json") : get('/api/v1/downloads.json')
JSON.parse(response, :symbolize_names => true)
end
# Returns an array containing the top 50 downloaded gem versions of all time
#
# @authenticated false
# @return [Array]
# @example
# Gems.most_downloaded
def most_downloaded
response = get('/api/v1/downloads/all.json')
JSON.parse(response)['gems']
end
# Returns the number of downloads by day for a particular gem version
#
# @authenticated false
# @param gem_name [String] The name of a gem.
# @param gem_version [String] The version of a gem.
# @param from [Date] Search start date.
# @param to [Date] Search end date.
# @return [Hash]
# @example
# Gems.downloads 'coulda', '0.6.3', Date.today - 30, Date.today
def downloads(gem_name, gem_version = nil, from = nil, to = Date.today)
gem_version ||= info(gem_name)['version']
response = from ? get("/api/v1/versions/#{gem_name}-#{gem_version}/downloads/search.json", :from => from.to_s, :to => to.to_s) : get("/api/v1/versions/#{gem_name}-#{gem_version}/downloads.json")
JSON.parse(response)
end
# View all owners of a gem that you own
#
# @authenticated true
# @param gem_name [String] The name of a gem.
# @return [Array]
# @example
# Gems.owners 'gemcutter'
def owners(gem_name)
response = get("/api/v1/gems/#{gem_name}/owners.json")
JSON.parse(response)
end
# Add an owner to a RubyGem you own, giving that user permission to manage it
#
# @authenticated true
# @param gem_name [String] The name of a gem.
# @param owner [String] The email address of the user you want to add.
# @return [String]
# @example
# Gems.add_owner 'gemcutter', 'josh@technicalpickles.com'
def add_owner(gem_name, owner)
post("/api/v1/gems/#{gem_name}/owners", :email => owner)
end
# Remove a user's permission to manage a RubyGem you own
#
# @authenticated true
# @param gem_name [String] The name of a gem.
# @param owner [String] The email address of the user you want to remove.
# @return [String]
# @example
# Gems.remove_owner 'gemcutter', 'josh@technicalpickles.com'
def remove_owner(gem_name, owner)
delete("/api/v1/gems/#{gem_name}/owners", :email => owner)
end
# List the webhooks registered under your account
#
# @authenticated true
# @return [Hash]
# @example
# Gems.web_hooks
def web_hooks
response = get('/api/v1/web_hooks.json')
JSON.parse(response)
end
# Create a webhook
#
# @authenticated true
# @param gem_name [String] The name of a gem. Specify "*" to add the hook to all gems.
# @param url [String] The URL of the web hook.
# @return [String]
# @example
# Gems.add_web_hook 'rails', 'http://example.com'
def add_web_hook(gem_name, url)
post('/api/v1/web_hooks', :gem_name => gem_name, :url => url)
end
# Remove a webhook
#
# @authenticated true
# @param gem_name [String] The name of a gem. Specify "*" to remove the hook from all gems.
# @param url [String] The URL of the web hook.
# @return [String]
# @example
# Gems.remove_web_hook 'rails', 'http://example.com'
def remove_web_hook(gem_name, url)
delete('/api/v1/web_hooks/remove', :gem_name => gem_name, :url => url)
end
# Test fire a webhook
#
# @authenticated true
# @param gem_name [String] The name of a gem. Specify "*" to fire the hook for all gems.
# @param url [String] The URL of the web hook.
# @return [String]
# @example
# Gems.fire_web_hook 'rails', 'http://example.com'
def fire_web_hook(gem_name, url)
post('/api/v1/web_hooks/fire', :gem_name => gem_name, :url => url)
end
# Returns the 50 gems most recently added to RubyGems.org (for the first time)
#
# @authenticated false
# @param options [Hash] A customizable set of options.
# @return [Array]
# @example
# Gem.latest
def latest(options = {})
response = get('/api/v1/activity/latest.json', options)
JSON.parse(response)
end
# Returns the 50 most recently updated gems
#
# @authenticated false
# @param options [Hash] A customizable set of options.
# @return [Array]
# @example
# Gem.just_updated
def just_updated(options = {})
response = get('/api/v1/activity/just_updated.json', options)
JSON.parse(response)
end
# Retrieve your API key using HTTP basic auth
#
# @authenticated true
# @return [String]
# @example
# Gems.configure do |config|
# config.username = 'nick@gemcutter.org'
# config.password = 'schwwwwing'
# end
# Gems.api_key
def api_key
get('/api/v1/api_key')
end
# Returns an array of hashes for all versions of given gems
#
# @authenticated false
# @param gems [Array] A list of gem names
# @return [Array]
# @example
# Gems.dependencies 'rails', 'thor'
def dependencies(*gems)
response = get('/api/v1/dependencies', :gems => gems.join(','))
Marshal.load(response)
end
# Returns an array of all the reverse dependencies to the given gem.
#
# @authenticated false
# @param gem_name [String] The name of a gem
# @param options [Hash] A customizable set of options.
# @return [Array]
# @example
# Gems.reverse_dependencies 'money'
def reverse_dependencies(gem_name, options = {})
response = get("/api/v1/gems/#{gem_name}/reverse_dependencies.json", options)
JSON.parse(response)
end
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
rubygems/gems | https://github.com/rubygems/gems/blob/6f3e1a6534b135b97b526fb646780d1270fe5c4e/lib/gems/v2/client.rb | lib/gems/v2/client.rb | require 'date'
require 'gems/configuration'
require 'gems/request'
require 'json'
module Gems
module V2
class Client
include Gems::Request
attr_accessor(*Configuration::VALID_OPTIONS_KEYS)
def initialize(options = {})
options = Gems.options.merge(options)
Configuration::VALID_OPTIONS_KEYS.each do |key|
send("#{key}=", options[key])
end
end
# Returns information about the given gem for a sepcific version
#
# @authenticated false
# @param gem_name [String] The name of a gem.
# @param version [String] The requested version of the gem.
# @return [Hash]
# @example
# Gems::V2.info 'rails', '7.0.6'
def info(gem_name, version)
response = get("/api/v2/rubygems/#{gem_name}/versions/#{version}.json")
JSON.parse(response)
rescue JSON::ParserError
{}
end
end
end
end
| ruby | MIT | 6f3e1a6534b135b97b526fb646780d1270fe5c4e | 2026-01-04T17:44:39.948067Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/rtrace.rb | rtrace.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
require 'ffi'
require 'lib/rtrace'
| ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/examples/hit_tracer_example.rb | examples/hit_tracer_example.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
## Rtrace example hit tracer
## Please see Eucalyptus for a more comprehensive
## example of what is possible with rtrace
$: << File.dirname(__FILE__)
require 'rtrace'
pid = ARGV[0].to_i
bits = ARGV[1].to_i
if ARGV.size < 1 or pid == 0
puts "hit_tracer_example.rb <PID>"
exit
end
## Create an Rtrace instance
## by passing it a PID
d = Rtrace.new(pid)
## 32 or 64 process
d.bits = bits
## Attach to the PID
d.attach
## Create a block to run when our breakpoint is hit
f = Proc.new do |regs,rtrace|
puts "Breakpoint Hit!"
rtrace.print_registers
puts "--------------------"
end
## Set the breakpoint
if d.bits == 64
d.breakpoint_set(0x00000000004005bd, "foo", f)
else
d.breakpoint_set(0x0804847d, "foo", f)
end
## Install all breakpoints
d.install_bps
## Continue the process
d.continue
## Loop using wait
catch(:throw) { d.loop } | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/examples/syscall_tracer.rb | examples/syscall_tracer.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
## Rtrace example syscall tracer
require 'ffi'
$: << File.dirname(__FILE__)
require 'rtrace'
pid = ARGV[0].to_i
bits = 64
if ARGV.size < 1 or pid == 0
puts "syscall_tracer_example.rb <PID>"
exit
end
## Create an Rtrace instance
## by passing it a PID
d = Rtrace.new(pid)
## 32 or 64 process
d.bits = bits
## Attach to the PID
d.attach
d.syscall_tracing = true
## Instruct rtrace to trace syscalls
d.syscall_trace(Proc.new do |regs,rtrace|
puts "Syscall Executed"
rtrace.print_registers
puts "--------------------------------------"
d.syscall_tracing = false
end)
puts "Continuing Process"
d.continue
catch(:throw) { d.loop } | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/lib/rtrace.rb | lib/rtrace.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
RTRACE_VERSION = "1.4"
## This ugly code is from the Ragweed project. It is
## required to support struct style access of FFI fields
module FFIStructInclude
## Ruby 1.9 no longer supported but this will remain
## for a few versions just in case anyone is using it
if RUBY_VERSION < "1.9"
def methods regular=true
(super + self.members.map{|x| [x.to_s, x.to_s+"="]}).flatten
end
else
def methods regular=true
(super + self.members.map{|x| [x, (x.to_s+"=").intern]}).flatten
end
end
def method_missing meth, *args
super unless self.respond_to? meth
if meth.to_s =~ /=$/
self.__send__(:[]=, meth.to_s.gsub(/=$/,'').intern, *args)
else
self.__send__(:[], meth, *args)
end
end
def respond_to? meth, include_priv=false
# mth = meth.to_s.gsub(/=$/,'')
!((self.methods & [meth, meth.to_s]).empty?) || super
end
end
NULL = nil
## x86 registers
class PTRegs32 < FFI::Struct
include FFIStructInclude
layout :ebx, :ulong,
:ecx, :ulong,
:edx, :ulong,
:esi, :ulong,
:edi, :ulong,
:ebp, :ulong,
:eax, :ulong,
:xds, :ulong,
:xes, :ulong,
:xfs, :ulong,
:xgs, :ulong,
:orig_eax, :ulong,
:eip, :ulong,
:xcs, :ulong,
:eflags, :ulong,
:esp, :ulong,
:xss, :ulong
end
## x64 Registers
class PTRegs64 < FFI::Struct
include FFIStructInclude
layout :r15, :ulong,
:r14, :ulong,
:r13, :ulong,
:r12, :ulong,
:rbp, :ulong,
:rbx, :ulong,
:r11, :ulong,
:r10, :ulong,
:r9, :ulong,
:r8, :ulong,
:rax, :ulong,
:rcx, :ulong,
:rdx, :ulong,
:rsi, :ulong,
:rdi, :ulong,
:orig_rax, :ulong,
:rip, :ulong,
:cs, :ulong,
:eflags, :ulong,
:rsp, :ulong,
:ss, :ulong,
## There is something very wrong here. FFI/Ruby
## will clobber the structure at the end of this
## and cause heap checks to fail. I don't think
## this is an rtrace bug because PTRegs64 has
## .size() and we use FFI::MemoryPointer
:pad1, :ulong,
:pad2, :ulong,
:pad3, :ulong,
:pad4, :ulong
end
## __ptrace_peeksiginfo_args Structure
class PeekSigInfoArgs < FFI::Struct
include FFIStructInclude
layout :off, :uint64,
:flags, :uint32,
:nr, :int
end
module PeekSigInfoFlags
PEEKSIGINFO_SHARED = (1 << 0)
end
module Ptrace
TRACE_ME = 0
PEEK_TEXT = 1
PEEK_DATA = 2
PEEK_USER = 3
POKE_TEXT = 4
POKE_DATA = 5
POKE_USER = 6
CONTINUE = 7
KILL = 8
STEP = 9
GETREGS = 12
SETREGS = 13
GETFPREGS = 14
SETFPREGS = 15
ATTACH = 16
DETACH = 17
GETFPXREGS = 18
SETFPXREGS = 19
SYSCALL = 24
SETOPTIONS = 0x4200
GETEVENTMSG = 0x4201
GETSIGINFO = 0x4202
SETSIGINFO = 0x4203
GETREGSET = 0x4204
SETREGSET = 0x4205
SEIZE = 0x4206
INTERRUPT = 0x4207
LISTEN = 0x4208
PEEKSIGINFO = 0x4209
end
# Use ::Signal
module Signal
SIGHUP = 1
SIGINT = 2
SIGQUIT = 3
SIGILL = 4
SIGTRAP = 5
SIGSYSTRAP = (SIGTRAP | 0x80)
SIGABRT = 6
SIGIOT = 6
SIGBUS = 7
SIGFPE = 8
SIGKILL = 9
SIGUSR1 = 10
SIGSEGV = 11
SIGUSR2 = 12
SIGPIPE = 13
SIGALRM = 14
SIGTERM = 15
SIGSTKFLT = 16
SIGCHLD = 17
SIGCONT = 18
SIGSTOP = 19
SIGTSTP = 20
SIGTTIN = 21
SIGTTOU = 22
SIGURG = 23
SIGXCPU = 24
SIGXFSZ = 25
SIGVTALRM = 26
SIGPROF = 27
SIGWINCH = 28
SIGIO = 29
SIGPOLL = SIGIO
SIGPWR = 30
SIGSYS = 31
SIGUNUSED = 31
end
module Ptrace::SetOptions
TRACESYSGOOD = 0x00000001
TRACEFORK = 0x00000002
TRACEVFORK = 0x00000004
TRACECLONE = 0x00000008
TRACEEXEC = 0x00000010
TRACEVFORKDONE = 0x00000020
TRACEEXIT = 0x00000040
TRACESECCOMP = 0x00000080 ## Kernel 3.x
EXITKILL = 0x00100000 ## Kernel 3.x
MASK = 0x0000007f
end
module Ptrace::EventCodes
FORK = (Signal::SIGTRAP | (1 << 8))
VFORK = (Signal::SIGTRAP | (2 << 8))
CLONE = (Signal::SIGTRAP | (3 << 8))
EXEC = (Signal::SIGTRAP | (4 << 8))
VFORK_DONE = (Signal::SIGTRAP | (5 << 8))
EXIT = (Signal::SIGTRAP | (6 << 8))
SECCOMP = (Signal::SIGTRAP | (7 << 8))
end
module Wait
NOHANG = 0x00000001
UNTRACED = 0x00000002
EXITED = 0x00000004
STOPPED = 0x00000002
CONTINUED = 0x00000008
NOWAIT = 0x01000000
NOTHREAD = 0x20000000
WALL = 0x40000000
CLONE = 0x80000000
end
module PagePermissions
PROT_NONE = 0x0
PROT_READ = 0x1
PROT_WRITE = 0x2
PROT_EXEC = 0x4
PROT_GROWSDOWN = 0x01000000
PROT_GROWSUP = 0x02000000
end
module Libc
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_function 'ptrace', [ :ulong, :pid_t, :ulong, :ulong ], :long
attach_function 'wait', [ :pointer ], :int
attach_function 'waitpid', [ :int, :pointer, :int ], :int
attach_function 'kill', [ :int, :int ], :int
end
class Native
def initialize
## empty
end
## pid_t wait(int *status);
def wait
p = FFI::MemoryPointer.new(:int, 1)
FFI.errno = 0
pid = Libc.wait p
raise SystemCallError.new "wait", FFI.errno if pid == -1
status = p.get_int32(0)
[pid, status]
end
## pid_t waitpid(pid_t pid, int *status, int options);
## OLD DEPRECATED BUSTED UP JUNK
def waitpid pid, opts = 0
p = FFI::MemoryPointer.new(:int, 1)
FFI.errno = 0
r = Libc.waitpid pid, p, opts
raise SystemCallError.new "waitpid", FFI.errno if r == -1
status = p.get_int32(0)
[r, status]
end
## int kill(pid_t pid, int sig);
def kill pid, sig
FFI.errno = 0
r = Libc.kill pid, sig
raise SystemCallError.new "kill", FFI.errno if r == -1
r
end
## long native.ptrace(enum __ptrace_request request, pid_t pid, void *addr, void *data);
def ptrace req, pid, addr, data
FFI.errno = 0
r = Libc.ptrace req, pid, addr, data
raise SystemCallError.new "ptrace", FFI.errno if r == -1 and !FFI.errno.zero?
self.kill(pid, Signal::SIGCONT)
r
end
end
## The Rtrace class. See examples directory or the
## Eucalyptus tool for how to use this class
class Rtrace
attr_reader :status, :exited, :signal
attr_accessor :breakpoints, :memory_map, :process, :use_ptrace_for_search,
:bits, :native, :syscall_tracing, :syscall_block, :pid, :tids,
:smap
## Each breakpoint is represented by one of these class instances.
class Breakpoint
INT3 = 0xCC
attr_accessor :orig, :bppid, :function, :installed, :native
attr_reader :addr
## ip: address to set a breakpoint on
## callable: Proc to be called when your breakpoint executes
## p: process ID
## name: name of breakpoint
## n: class instance for calling into Libc
def initialize(ip, callable, p, name = "", n)
@bppid = p
@function = name
@addr = ip
@callable = callable
@installed = false
@orig = 0
@native = n
end
def install
@orig = native.ptrace(Ptrace::PEEK_TEXT, @bppid, @addr, 0)
if @orig != -1
n = (@orig & ~0xff) | INT3;
native.ptrace(Ptrace::POKE_TEXT, @bppid, @addr, n)
@installed = true
else
@installed = false
end
end
def uninstall
if @orig != INT3
a = native.ptrace(Ptrace::POKE_TEXT, @bppid, @addr, @orig)
@installed = false
end
end
def installed?; @installed; end
def call(*args); @callable.call(*args) if @callable != nil; end
end ## end Breakpoint
## p: pid of process to be debugged
def initialize(pid)
if p.to_i.kind_of? Fixnum
@pid = pid.to_i
else
raise "Please supply a PID"
end
@bits = 32 ## defaults to 32
@installed = false
@attached = false
@use_ptrace_for_search = false
@syscall_tracing = false
@syscall_block = nil
@exited = false
@tids = []
@memory_map = Hash.new
@smap = Hash.new
@breakpoints = Hash.new
@native = Native.new
end
def try_method(m, *a)
send m, *a if respond_to? m
end
## Find a PID by string/regex
def self.find_by_regex(rx)
rx = /#{rx}/ if rx.kind_of?(String)
my_pid = Process.pid
Dir.glob("/proc/*/cmdline").each do |x|
x_pid = x.match(/\d+/).to_s.to_i
next if x =~ /self/ or x_pid == my_pid
begin
File.read(x).each_line do |ln|
return x_pid if ln =~ rx
end
rescue SystemCallError => e
## Processes die, we don't care
end
end
nil
end
## Returns an array of all PIDs
## currently in procfs
def self.get_pids
pids = []
rx = /#{rx}/ if rx.kind_of?(String)
my_pid = Process.pid
Dir.glob("/proc/*").each do |x|
next if x =~ /self/ or x.match(/\d+/) == nil
begin
pids.push(x.match(/\d+/).to_s.to_i)
rescue SystemCallError => e
## Processes die, we don't care
end
end
pids
end
def install_bps
@breakpoints.each do |k,v|
v.install
end
@installed = true
end
def uninstall_bps
@breakpoints.each do |k,v|
v.uninstall
end
@installed = false
end
def installed?; @installed; end
def attached?; @attached; end
## This has not been fully tested yet
def set_options(option)
r = native.ptrace(Ptrace::SETOPTIONS, @pid, 0, option)
end
## Attach calls install_bps so dont forget to call breakpoint_set
## BEFORE attach or explicitly call install_bps
def attach
r = native.ptrace(Ptrace::ATTACH, @pid, 0, 0)
s, q = Process.waitpid2(@pid, Wait::WALL|Wait::UNTRACED|Wait::NOHANG)
if r != -1
@attached = true
on_attach
self.install_bps if @installed == false
else
raise "Attach failed!"
end
return r
end
## A helper for tracing syscalls
## flag - true if we want to trace syscalls
## f - The block to execute when
def syscall_trace(f)
@syscall_block = f
native.ptrace(Ptrace::SETOPTIONS, @pid, 0, Ptrace::SetOptions::TRACESYSGOOD)
## By calling this helper we assume you
## want to trace syscalls. When you want
## to stop just set Rtrace.syscall_tracing = false
@syscall_tracing = true
while @syscall_tracing == true
native.ptrace(Ptrace::SYSCALL, @pid, 0, 0)
self.wait
end
## Reaching here means you set syscall_tracing
## to false, so we clear all that for you. However
## you will have to call Rtrace::continue
@syscall_tracing = false
@syscall_block = nil
native.ptrace(Ptrace::SETOPTIONS, @pid, 0, 0)
end
## Returns an array of TID's from procfs
def self.threads(pid)
a = []
begin
a = Dir.entries("/proc/#{pid}/task/")
a.delete_if do |x|
x == '.' or x == '..'
end
rescue SystemCallError => e
puts "No such PID: #{pid}"
end
a
end
## Parse smaps and return a hash of its content
## key = Start address of region
## value = An array of hashes for each member
## The fields might vary by kernel version so
## we have to do some dirty work to find out
## how many members there are for each mapping
def smaps
@smap.clear if @smaps
sm = File.read("/proc/#{pid}/smaps")
return if sm.size == 0
sz = sm.each_line.count / sm.scan(/[0-9a-f]{8,16}\-[0-9a-f]{8,16}/).count
sm.each_line.to_a.each_slice(sz) do |s|
addr = s[0].split('-').first
h = {}
s.each_with_index do |p,i|
if i == 0
k = "Mapping"
v = p
else
k,v = p.split(':')
end
h.store(k, v.chomp.strip)
end
@smap.store(addr.to_i(16), h)
end
end
def smap_for_address(addr, r=false)
smaps if r == true
addr = addr.to_i(16) if addr.kind_of?(String)
@smap.each_pair do |k,v|
base_addr, end_addr = v["Mapping"].split(/[\-\s+]/)
return @smap[k] if addr >= base_addr.to_i(16) and addr <= end_addr.to_i(16)
end
return nil
end
# This method returns a hash of mapped regions
# The hash is also stored as @map
# key = Start address of region
# value = Size of the region
def maps
@memory_map.clear if @memory_map
File.open("/proc/#{pid}/maps") do |f|
f.each_line do |l|
e = l.split(' ',2).first
s,e = e.split('-').map {|x| x.to_i(16)}
sz = e - s
@memory_map.store(s, sz)
end
end
@memory_map
end
alias :mapped_regions :memory_map
alias_method :mapped, :maps
## Return a name for a range if possible. greedy match
## returns the first found
def get_mapping_name(val)
File.open("/proc/#{pid}/maps") do |f|
f.each_line do |l|
range, perms, offset, dev, inode, pathname = l.chomp.split(" ")
## Dirty temporary hack to determine if
## process is 32 or 64 bit. Ideally the
## consumer of Rtrace should set (Rtrace.bits)
@bits = 64 if @bits == 0 and pathname =~ /\/lib\/x86_64/
base, max = range.split('-').map{|x| x.to_i(16)}
return pathname if base <= val and val <= max
end
end
nil
end
## Return a range via mapping name
def get_mapping_by_name(name)
File.open("/proc/#{pid}/maps") do |f|
f.each_line do |l|
res = l.scan(name)
if res.empty? == false
res = res.first
range = l.chomp.split(" ").first
if res == name
return range.split('-').map{|x| x.to_i(16)}
end
end
end
end
return []
end
## Returns the permissions for an address
## e.g. r-x, rwx rw-
def get_mapping_permissions(addr)
File.open("/proc/#{pid}/maps") do |f|
f.each_line do |l|
range, perms, offset, dev, inode, pathname = l.chomp.split(" ",6)
base, max = range.split('-').map{|x| x.to_i(16)}
return perms if addr >= base and addr <= max
end
end
return ""
end
## Helper method for retrieving stack range
def get_stack_range
get_mapping_by_name('[stack]')
end
## Newer kernels (>3.4) will label a tid's stack
def get_thread_stack(tid)
get_mapping_by_name('[stack:#{tid}]')
end
## Helper method for retrieving heap range
def get_heap_range
get_mapping_by_name('[heap]')
end
## Parse procfs and create a hash containing
## a listing of each mapped shared object
def self.shared_libraries(p)
raise "pid is 0" if p.to_i == 0
if @shared_objects
@shared_objects.clear
else
@shared_objects = Hash.new
end
File.open("/proc/#{p}/maps") do |f|
f.each_line do |l|
if l =~ /[a-zA-Z0-9].so/# and l =~ /xp /
lib = l.split(' ', 6)
sa = l.split('-', 0)
next if lib[5] =~ /vdso/
lib = lib[5].strip
lib.gsub!(/[\s\n]+/, "")
@shared_objects.store(sa[0].to_i(16), lib)
end
end
end
@shared_objects
end
## instance method for above
## returns a hash of the mapped
## shared libraries
def shared_libraries
self.shared_libraries(@pid)
end
## Search a specific page for a value
## Should be used by most search methods
def search_page(base, max, val, &block)
loc = []
if self.use_ptrace_for_search == true
while base.to_i < max.to_i
r = native.ptrace(Ptrace::PEEK_TEXT, @pid, base, 0)
loc << base if r == val
base += 4
yield loc if block_given?
end
else
sz = max.to_i - base.to_i
d = File.new("/proc/#{pid}/mem")
d.seek(base.to_i, IO::SEEK_SET)
b = d.read(sz)
i = 0
while i < sz
if val == b[i,4].unpack('L')
loc << base.to_i + i
yield(base.to_i + i) if block_given?
end
i += 4
end
d.close
end
loc
end
def search_mem_by_name(name, val, &block)
loc = []
File.open("/proc/#{pid}/maps") do |f|
f.each_line do |l|
if l =~ /\[#{name}\]/
s,e = l.split('-')
e = e.split(' ').first
s = s.to_i(16)
e = e.to_i(16)
sz = e - s
max = s + sz
loc << search_page(s, max, val, &block)
end
end
end
loc
end
## Searches all pages with permissions matching perm
## e.g. r-x rwx rw-
## for val, and executes block when found
def search_mem_by_permission(perm, val, &block)
loc = []
File.open("/proc/#{pid}/maps") do |f|
f.each_line do |l|
if l.split(' ')[1] =~ /#{perm}/
s,e = l.split('-')
e = e.split(' ').first
s = s.to_i(16)
e = e.to_i(16)
sz = e - s
max = s + sz
loc << search_page(s, max, val, &block)
end
end
end
loc
end
## Search the heap for a value, returns an array of matches
def search_heap(val, &block)
search_mem_by_name('heap', val, &block)
end
## Search the stack for a value, returns an array of matches
def search_stack(val, &block)
search_mem_by_name('stack', val, &block)
end
## Search all mapped regions for a value
def search_process(val, &block)
loc = []
self.mapped
@memory_map.each_pair do |k,v|
next if k == 0 or v == 0
max = k+v
loc << search_page(k, max, val, &block)
end
loc
end
def continue
on_continue
native.ptrace(Ptrace::CONTINUE, @pid, 0, 0)
end
def detach
on_detach
## If we are detaching then we need to
## uninstall any breakpoints we set
uninstall_bps
native.ptrace(Ptrace::DETACH, @pid, 0, 0)
end
def single_step
on_single_step
native.ptrace(Ptrace::STEP, @pid, 1, 0)
end
## Adds a breakpoint to be installed
## ip: Address to set breakpoint on
## name: name of breakpoint
## callable: Proc to .call at breakpoint
def breakpoint_set(ip, name="", callable=nil, &block)
callable = block if not callable and block_given?
@breakpoints.each_key {|k| return if k == ip }
bp = Breakpoint.new(ip, callable, @pid, name, @native)
@breakpoints[ip] = bp
end
## Remove a breakpoint by ip
def breakpoint_clear(ip)
bp = @breakpoints[ip]
return nil if bp.nil?
bp.uninstall
end
## loop for wait()
## times: the number of wait calls to make
def loop(times=nil)
if times.kind_of? Numeric
times.times do
self.wait
end
elsif times.nil?
self.wait while not @exited
end
end
## TODO - define these as constants
def wifsignaled(status)
(((((status) & 0x7f) + 1) >> 1) > 0)
end
def wifexited(status)
wtermsig(status) == 0
end
def wifstopped(status)
(((status) & 0xff) == 0x7f)
end
def wstopsig(status)
wexitstatus(status)
end
def wexitstatus(status)
(((status) & 0xff00) >> 8)
end
def wtermsig(status)
((status) & 0x7f)
end
def wcoredump(status)
((status) & 0x80)
end
## Writing a wait loop on Linux is difficult. There are
## a lot of corner cases to account for and much of it
## is poorly documented. This method handles signals and
## ptrace events, and then invokes Ruby callbacks to
## handle them. This is not complete yet, unfortunately.
## You can pass an optional PID to this method which is
## the only PID we will wait() on. If you have any interest
## in hacking on Rtrace to improve it then this is the
## one of the best places to get started
def wait(p = -1)
status = nil
begin
r, status = Process.waitpid2(p, Wait::WALL)
rescue SystemCallError => e
## TODO: handle this better
raise Exception, "Errno::ECHILD" if e.kind_of?(Errno::ECHILD)
return
end
## We only care about pid and thread ids
return if r != @pid and @tids.include?(r) == false
## Ruby Status object gives us this
## via stopped?. We don't need the
## wifstopped macro anymore
#wstop = #wifstopped(status)
wstop = status.stopped?
## Ruby Status object gives us the
## signal so we don't need to use
## wstopsig macro anymore
#@signal = wstopsig(status)
if status.stopped?
@signal = status.stopsig
else
@signal = status.termsig
end
status = status.to_i
return r if r == -1
if wifexited(status) == true and wexitstatus(status) == 0
## Don't exit if only a tid died
@exited = true if r == @pid
try_method :on_exit, wexitstatus(status), r
#exit if r == @pid
@tids.delete(r)
return
elsif wifexited(status) == true
## Don't exit if only a tid died
@exited = true if r == @pid
try_method :on_exit, wexitstatus(status), r
@tids.delete(r)
#exit if r == @pid
return
elsif wifsignaled(status) == true
## uncaught signal?
end
if wstop == true ## STOP
try_method :on_stop
else
## The process was not stopped
## due to a signal... It is possible
## that a thread died we weren't
## tracing...
end
## Here we handle all signals and event codes.
## Most of these have event handlers associated
## with them, we invoke those via 'try_method'
## Some of them require thread specific operations
## such as segv or sigill where the process cannot
## continue. In those cases we override @pid with
## the offending tid and then restore it later.
ppid = @pid
@pid = r if r != nil and r > 0
try_method :on_signal, @signal
case @signal
when Signal::SIGINT
try_method :on_sigint
self.continue
when Signal::SIGSEGV
try_method :on_segv
when Signal::SIGILL
try_method :on_illegal_instruction
when Signal::SIGIOT
try_method :on_iot_trap
self.continue
when Signal::SIGSYSTRAP
try_method :on_syscall
when Signal::SIGTRAP
event_code = (status >> 8)
try_method :on_sigtrap
regs = self.get_registers
ip = get_ip(regs)
ip -= 1
## Let user defined breakpoint handlers run
try_method :on_breakpoint if @breakpoints.has_key?(ip)
case event_code
## TODO: should work the same way as CLONE
when Ptrace::EventCodes::VFORK, Ptrace::EventCodes::FORK
p = FFI::MemoryPointer.new(:int, 1)
native.ptrace(Ptrace::GETEVENTMSG, @pid, 0, p.to_i)
## Fix up the PID in each breakpoint
if (1..65535) === p.get_int32(0)
@breakpoints.each_pair do |k,v|
v.each do |b|
b.bppid = p.get_int32(0).to_i
end
end
## detach will handle calling uninstall_bps
self.detach
ppid = @pid = p.get_int32(0).to_i
try_method :on_fork_child, @pid
end
when Ptrace::EventCodes::CLONE
## Get the new TID
tid = FFI::MemoryPointer.new(:int, 1)
native.ptrace(Ptrace::GETEVENTMSG, @pid, 0, tid.to_i)
tid = tid.get_int32(0).to_i
@tids.push(tid)
try_method :on_clone, tid
## Tell the new TID to continue. We are automatically already
## tracing it. This is totally ghetto but ptrace might
## fail here so we need to call waitpid and try again...
begin
native.ptrace(Ptrace::CONTINUE, tid, 0, 0)
rescue SystemCallError => e
Process.waitpid2(tid, (Wait::WALL|Wait::NOHANG))
native.ptrace(Ptrace::CONTINUE, tid, 0, 0)
end
when Ptrace::EventCodes::EXEC
try_method :on_execve
when Ptrace::EventCodes::VFORK_DONE
try_method :on_vfork_done
when Ptrace::EventCodes::EXIT
@exited = true if r == @pid
p = FFI::MemoryPointer.new(:int, 1)
native.ptrace(Ptrace::GETEVENTMSG, @pid, 0, p.to_i)
@exited = true if r == @pid
try_method :on_exit, p.get_int32(0), r
@tids.delete(r)
## This is the main PID dieing
#exit if r == @pid
when Ptrace::EventCodes::SECCOMP
try_method :on_seccomp
end
## We either handled our breakpoint
## or we handled an event code
self.continue
when Signal::SIGCHLD
try_method :on_sigchild
when Signal::SIGTERM
try_method :on_sigterm
when Signal::SIGCONT
try_method :on_continue
self.continue
when Signal::SIGSTOP
try_method :on_sigstop
self.continue
when Signal::SIGKILL
try_method :on_kill
self.continue
when Signal::SIGABRT
try_method :on_abort
self.continue
when Signal::SIGBUS
try_method :on_sigbus
self.continue
when Signal::SIGWINCH, Signal::SIGHUP, Signal::SIGQUIT,
Signal::SIGFPE, Signal::SIGUSR1, Signal::SIGUSR2, Signal::SIGPIPE, Signal::SIGALRM,
Signal::SIGSTKFLT, Signal::SIGTSTP, Signal::SIGTTIN, Signal::SIGTTOU, Signal::SIGURG,
Signal::SIGXCPU, Signal::SIGXFSZ, Signal::SIGVTALRM, Signal::SIGPROF, Signal::SIGIO,
Signal::SIGPOLL, Signal::SIGPWR, Signal::SIGSYS, Signal::SIGUNUSED
try_method :unhandled_signal, @signal
self.continue
else
raise "You are missing a handler for signal (#{@signal})"
end
@pid = ppid
return @signal
end
## Here we need to do something about the bp
## we just hit. We have a block to execute.
## Remember if you implement this on your own
## make sure to call super, and also realize
## IP won't look correct until this runs
def on_breakpoint
r = get_registers
ip = get_ip(r)
ip -= 1
## Call the block associated with the breakpoint
@breakpoints[ip].call(r, self)
## The block may have called breakpoint_clear
del = true if !@breakpoints[ip].installed?
## Uninstall and single step the bp
@breakpoints[ip].uninstall
r.eip = ip if @bits == 32
r.rip = ip if @bits == 64
set_registers(r)
single_step
if del == true
## The breakpoint block may have called breakpoint_clear
@breakpoints.delete(ip)
else
@breakpoints[ip].install
end
end
def on_attach() end
def on_detach() end
def on_single_step() end
def on_syscall_continue() end
def on_continue() end
def on_exit(exit_code, pid) end
def on_signal(signal) end
def on_sigint() end
def on_segv() end
def on_illegal_instruction() end
def on_sigtrap() end
def on_fork_child(pid) end
def on_clone(tid) end
def on_sigchild() end
def on_sigterm() end
def on_sigstop() end
def on_iot_trap() end
def on_stop() end
def on_execve() end
def on_vfork_done() end
def on_seccomp() end
def on_kill() end
def on_abort() end
def on_sigbus() end
def unhandled_signal(signal) end
def on_syscall
syscall_block.call get_registers, self
end
def get_registers
return get_registers_32 if @bits == 32
return get_registers_64 if @bits == 64
end
def print_registers
return print_registers_32 if @bits == 32
return print_registers_64 if @bits == 64
end
def get_machine_word
return 4 if @bits == 32
return 8 if @bits == 64
end
def get_ip(r)
return r.eip if @bits == 32
return r.rip if @bits == 64
end
def get_sp(r)
return r.esp if @bits == 32
return r.rsp if @bits == 64
end
def get_registers_32
regs = FFI::MemoryPointer.new(PTRegs32, 1)
native.ptrace(Ptrace::GETREGS, @pid, 0, regs.address)
return PTRegs32.new regs
end
def get_registers_64
regs = FFI::MemoryPointer.new(PTRegs64, 1)
native.ptrace(Ptrace::GETREGS, @pid, 0, regs.address)
return PTRegs64.new regs
end
def set_registers(regs)
native.ptrace(Ptrace::SETREGS, @pid, 0, regs.to_ptr.address)
end
def print_registers_32
regs = get_registers_32
r = "eip 0x%08x\n" % regs.eip
r += "ebp 0x%08x\n" % regs.ebp
r += "esi 0x%08x\n" % regs.esi
r += "edi 0x%08x\n" % regs.edi
r += "esp 0x%08x\n" % regs.esp
r += "eax 0x%08x\n" % regs.eax
r += "ebx 0x%08x\n" % regs.ebx
r += "ecx 0x%08x\n" % regs.ecx
r += "edx 0x%08x" % regs.edx
end
def print_registers_64
regs = get_registers_64
r = "rip 0x%16x\n" % regs.rip
r += "rbp 0x%16x\n" % regs.rbp
r += "rsi 0x%16x\n" % regs.rsi
r += "rdi 0x%16x\n" % regs.rdi
r += "rsp 0x%16x\n" % regs.rsp
r += "rax 0x%16x\n" % regs.rax
r += "rbx 0x%16x\n" % regs.rbx
r += "rcx 0x%16x\n" % regs.rcx
r += "rdx 0x%16x\n" % regs.rdx
r += "r8 0x%16x\n" % regs.r8
r += "r9 0x%16x\n" % regs.r9
r += "r10 0x%16x\n" % regs.r10
r += "r11 0x%16x\n" % regs.r11
r += "r12 0x%16x\n" % regs.r12
r += "r13 0x%16x\n" % regs.r13
r += "r14 0x%16x\n" % regs.r14
r += "r15 0x%16x" % regs.r15
end
## Read process memory using procfs
def read_procfs(off, sz=4096)
p = File.open("/proc/#{pid}/mem", "r")
p.seek(off)
r = p.read(sz)
p.close
return r
end
## Write to process memory using procfs
def write_procfs(off, data)
p = File.open("/proc/#{pid}/mem", "w+")
p.seek(off)
r = p.write(data)
p.close
return r
end
## Read process memory using ptrace
def read(off, sz=4096)
a = []
max = off+sz
while off < max
a.push(native.ptrace(Ptrace::PEEK_TEXT, @pid, off, 0))
return a.pack('L*') if a.last == -1 and FFI.errno != 0
off+=4
end
a.pack('L*')
end
## Write process memory using ptrace
def write(off, data)
while off < data.size
native.ptrace(Ptrace::POKE_TEXT, @pid, off, data[off,4].unpack('L').first)
off += 4
end
end
def read64(off); read(off, 8).unpack("Q").first; end
def read32(off); read(off, 4).unpack("L").first; end
def read16(off); read(off, 2).unpack("v").first; end
def read8(off); read(off, 1)[0]; end
def write64(off, v); write(off, [v].pack("Q")); end
def write32(off, v); write(off, [v].pack("L")); end
def write16(off, v); write(off, [v].pack("v")); end
def write8(off, v); write(off, v.chr); end
end
| ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/crash.rb | Eucalyptus/crash.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
## Crash is a partial MSEC (!exploitable) WinDbg extension
## reimplementation which uses the Rtrace debugging library.
##
## Usage:
##
## Catch a debug event like segfault or illegal instruction
## then pass your rtrace instance to this class:
##
## Crash.new(@rtrace).exploitable?
##
## Thats it! The class will use your rtrace instance to
## determine the state of the process. This is done examining
## the last signal or debug event the process received and
## the register states.
## This code is far from complete. It needs a lot of work...
require 'rtrace'
class Crash
EXPLOITABLE = 1
POSSIBLY_EXPLOITABLE = 2
NOT_EXPLOITABLE = 3
UNKNOWN = 4
attr_accessor :state, :status, :rtrace
## TOOD: make status a bitmask so we can report
## on several things at once
def initialize(rw)
@rtrace = rw
status = UNKNOWN
r = @rtrace.get_registers
if @rtrace.bits == 32
status = reg_check(r.eip)
status = reg_check(r.ebp)
else
status = reg_check(r.rip)
status = reg_check(r.rbp)
end
case @rtrace.signal
when Signal::SIGILL
puts "Illegal instruction indicates attacker controlled code flow - EXPLOITABLE"
status = EXPLOITABLE
when Signal::SIGIOT
puts "IOT Trap may indicate an exploitable crash (stack cookie?) - POSSIBLY EXPLOITABLE"
status = POSSIBLY_EXPLOITABLE
when Signal::SIGSEGV
puts "A segmentation fault may be exploitable, needs further analysis - POSSIBLY EXPLOITABLE"
status = POSSIBLY_EXPLOITABLE
end
end
## Crash.exploitable?
## Who needs !exploitable when you've got exploitable?
def exploitable?
return true if status == EXPLOITABLE or status == POSSIBLY_EXPLOITABLE
return false
end
def get_stack_trace
## TODO: Not implemented yet
end
def reg_check(reg)
stack_range = @rtrace.get_stack_range
heap_range = @rtrace.get_heap_range
stack_range.each do |s|
if reg == s.first..s.last
puts "Executing instructions from the stack - EXPLOITABLE"
return EXPLOITABLE
end
end
heap_range.each do |h|
if reg == h.first..h.last
puts "Executing instructions from the heap - EXPLOITABLE"
return EXPLOITABLE
end
end
case reg
when 0x41414141
puts "Register is controllable AAAA... - EXPLOITABLE"
return EXPLOITABLE
when 0x0..0x1000
puts "NULL Pointer dereference - NOT EXPLOITABLE (unless you control the offset from NULL)"
return NOT_EXPLOITABLE
end
end
end
| ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/eucalyptus.rb | Eucalyptus/eucalyptus.rb | #!/usr/bin/env ruby
## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
$: << File.dirname(__FILE__)
require 'ffi'
require 'rtrace'
require 'optparse'
require 'ostruct'
require 'open3'
require 'crash'
require 'common/config'
require 'common/output'
require 'common/common'
EUCALYPTUS_VERSION = "1.0"
class Eucalyptus
attr_accessor :opts, :rtrace, :pid, :threads, :breakpoints, :so, :log,
:event_handlers, :exec_proc, :rtrace_breakpoints, :bits,
:pid_stdin, :pid_stdout, :target_binary
def initialize(opts)
@opts = opts
## PID wont be nil here, we checked
## before ever creating this class.
## It may be a numeric PID or a string
## matching the name of the process
@pid = opts[:pid]
@target_binary = @pid if @pid.to_i == 0
@bits = opts[:bits]
@exec_proc = OpenStruct.new
@breakpoints = []
@threads = []
@event_handlers = {}
@so = {}
@out = opts[:out]
@log = EucalyptusLog.new(@out)
@pid_stdin = nil
@pid_stdout = nil
## Parse Eucalyptus execute file
parse_exec_proc(opts[:ep_file]) if opts[:ep_file]
## Configure Eucalyptus using the DSL
eval(File.read(opts[:dsl_file])) if opts[:dsl_file]
if opts[:bp_file]
if opts[:bp_file] !~ /\.rb/
## Configure Eucalyptus with a config file
parse_config_file(opts[:bp_file])
else
## Configure Eucalyptus with Ruby code
config_dsl(opts[:bp_file])
end
end
## @pid is set from the return value of popen
launch_process if exec_proc.target.nil? == false
if pid.kind_of?(String) or pid.to_i == 0
@pid = EucalyptusImpl.find_by_regex(/#{pid}/).to_i
else
@pid = pid.to_i
end
if pid.nil? or pid == 0
puts "Failed to find process: #{pid}"
exit
end
## We need to attach to the target ASAP
## if we called launch_process. We don't
## want it to exit before we trace it
@rtrace = EucalyptusImpl.new(pid, log)
@rtrace.bits = bits
@rtrace.attach
## We have to invoke this one manually because
## we havent called save_handlers yet
@event_handlers["on_attach"].call if @event_handlers["on_attach"].nil? == false
## Execute the code block supplied in the config
exec_proc.code.call if exec_proc.code.kind_of?(Proc)
@so = EucalyptusImpl.shared_libraries(pid)
@threads = EucalyptusImpl.threads(pid)
#self.which_threads
@rtrace.save_threads(@threads)
@rtrace.save_handlers(@event_handlers)
self.set_breakpoints
bp_count = 0
@breakpoints.each {|b| bp_count+=1 if b.flag == true }
@rtrace.save_breakpoints(@breakpoints)
@rtrace.install_bps
log.str "#{bp_count} Breakpoint(s) installed ..." if bp_count > 0
## TODO: This should be more configurable
o = 0
o |= Ptrace::SetOptions::TRACEFORK if opts[:fork] == true
o |= Ptrace::SetOptions::TRACEVFORK if opts[:fork] == true
o |= Ptrace::SetOptions::TRACEVFORKDONE
o |= Ptrace::SetOptions::TRACECLONE
o |= Ptrace::SetOptions::TRACEEXIT
o |= Ptrace::SetOptions::TRACEEXEC
@rtrace.set_options(o) if o != 0
@rtrace.continue
trap("INT") do
@rtrace.uninstall_bps
@rtrace.dump_stats
log.finalize
@rtrace.native.kill(@rtrace.pid, Signal::SIGKILL) if opts[:kill]
exit
end
## You probably want to save this somewhere.
## Leave it commented if you're just hacking
## on Eucalyptus
#@pid_stdout.close if @pid_stdout != nil
## Not catching exceptions here will
## help catch bugs in Rtrace :)
#begin
@rtrace.loop
#rescue Exception => e
# puts "Eucalyptus: #{e}"
#end
## This is commented out because the stats should
## have been dumped already if we reached this
## point through some debugger event
#@rtrace.dump_stats
end
def set_breakpoints
@breakpoints.each do |bp|
if bp.addr.nil?
bp.flag = false
next
end
## Some breakpoints are position independent
## and require knowing a library load address
## before they can be set in the process
if bp.lib
so.each_pair do |k,v|
puts "#{k.to_s(16)} => #{v} (#{rtrace.get_mapping_permissions(k)})"
if v =~ /#{bp.lib}/ and rtrace.get_mapping_permissions(k) =~ /r\-x/
bp.base = k
break
end
end
if bp.base != 0
## We assume hex 0x string...
bp.base = bp.base.to_i(16) if bp.base.kind_of?(String)
bp.addr = bp.addr.to_i(16) if bp.addr.kind_of?(String)
## Modify address now that we know base
bp.addr = bp.base+bp.addr
else
log.str "Breakpoint #{bp.addr.to_s(16)} cannot be set because #{bp.lib} is not mapped"
bp.flag = false
next
end
end
log.str "Setting breakpoint: 0x#{bp.addr.to_s(16)} #{bp.name} #{bp.lib}"
## The block we pass breakpoint_set will
## automagically call our Ruby code provided
## via a config and check if we have hit our
## maximum hit count. If we have then then
## it is uninstalled for us
@rtrace.breakpoint_set(bp.addr, bp.name, (Proc.new do
eval(bp.code) if bp.code.kind_of?(String)
bp.code.call if bp.code.kind_of?(Proc)
bp.hits += 1
if !bp.count.nil? and bp.hits.to_i >= bp.count.to_i
log.str "Uninstalling breakpoint #{bp.name} at 0x#{bp.addr.to_s(16)}"
bp.flag = false
regs = @rtrace.get_registers
@rtrace.breakpoint_clear(regs.eip-1) if @bits == 32
@rtrace.breakpoint_clear(regs.rip-1) if @bits == 64
end
end ))
bp.flag = true
end
end
## Run the process specified in a config
def launch_process
## TODO: popen with env
exec_proc.env.each_pair { |k,v| ENV[k] = v }
@pid_stdin, @pid_stdout, t = Open3::popen2e("#{exec_proc.target} #{exec_proc.args}")
@pid = t.pid
end
def check_bp_max(bp, ctx)
if !bp.count.nil? and bp.hits.to_i >= bp.count.to_i
r = @rtrace.breakpoint_clear(ctx.eip-1)
bp.flag = false
end
end
end
## This class is how we inherit from Rtrace and control it
class EucalyptusImpl < Rtrace
attr_accessor :log, :threads, :event_handlers, :rtrace_breakpoints
def initialize(p, l)
super(p)
@log = l
@threads = []
@rtrace_breakpoints = []
@event_handlers = {}
end
def save_breakpoints(b) @rtrace_breakpoints = b; end
def save_threads(t) @threads = t; end
def save_handlers(h) @event_handlers = h end
def exec_eh_script(name)
begin
eval(@event_handlers[name]) if @event_handlers[name].kind_of?(String)
@event_handlers[name].call if @event_handlers[name].kind_of?(Proc)
rescue Exception => e
puts "Error executing event handler script #{name} (#{e})"
end
end
def dump_stats
@rtrace_breakpoints.each do |bp|
log.str "#{bp.addr.to_s(16)} - #{bp.name} was hit #{bp.hits} times"
end
end
def on_fork_child(pid)
@pid = pid
exec_eh_script("on_fork_child")
log.str "Parent process forked a child with pid #{pid}"
super
end
def on_clone(tid)
exec_eh_script("on_clone")
log.str "New thread created with tid #{tid}"
super
end
def on_sigchild
exec_eh_script("on_sigchild")
log.str "Got sigchild"
super
end
def on_sigterm
log.str "Process Terminated!"
exec_eh_script("on_sigterm")
dump_stats
super
end
def on_segv
log.str "Segmentation Fault!"
exec_eh_script("on_segv")
puts self.print_registers
dump_stats
Crash.new(self).exploitable?
super
end
def on_breakpoint
exec_eh_script("on_breakpoint")
super
end
def on_exit(exit_code, pid)
log.str "Thread (#{pid}) exited with return code: #{exit_code}!"
exec_eh_script("on_exit")
super(exit_code, pid)
dump_stats
end
def on_illegal_instruction
log.str "Illegal Instruction!"
exec_eh_script("on_illegal_instruction")
dump_stats
puts self.print_registers
Crash.new(self).exploitable?
super
end
def on_iot_trap
log.str "IOT Trap!"
exec_eh_script("on_iot_trap")
dump_stats
puts self.print_registers
Crash.new(self).exploitable?
super
end
def on_sigbus
log.str "SIGBUS"
exec_eh_script("on_sigbus")
dump_status
puts self.print_registers
Crash.new(self).exploitable?
super
end
def on_attach
exec_eh_script("on_attach")
super
end
def on_detach
exec_eh_script("on_detach")
super
end
def on_sigtrap
exec_eh_script("on_sigtrap")
super
end
def on_continue
## This would get noisy
#log.str "Continuing..."
exec_eh_script("on_continue")
super
end
def on_sigstop
exec_eh_script("on_sigstop")
log.str "got sigstop"
super
end
def on_signal(signal)
exec_eh_script("on_signal")
super
end
def on_single_step
exec_eh_script("on_singlestep")
super
end
def on_execve
exec_eh_script("on_execve")
super
end
def on_vfork_done
exec_eh_script("on_vfork_done")
super
end
def on_seccomp
exec_eh_script("on_seccomp")
super
end
def on_kill
exec_eh_script("on_kill")
super
end
def on_abort
exec_eh_script("on_abort")
super
end
def unhandled_signal(signal)
exec_eh_script("unhandled_signal")
super
end
end
EUCALYPTUS_OPTS = {
pid: nil,
bits: 64,
ep_file: nil,
bp_file: nil,
dsl_file: nil,
out: STDOUT,
fork: false,
kill: false
}
opts = OptionParser.new do |opts|
opts.banner = "Eucalyptus #{EUCALYPTUS_VERSION} | Yahoo 2014/2015\n\n"
opts.on("-p", "--pid PID/Name", "Attach to this pid OR process name (ex: -p 12345 | -p gcalctool)") do |o|
EUCALYPTUS_OPTS[:pid] = o
end
opts.on("-i", "--bits 32/64", "Is the target process 32 or 64 bit?") do |o|
EUCALYPTUS_OPTS[:bits] = o.to_i
end
opts.on("-x", "--exec_proc [FILE]", "Launch a process according to the configuration found in this file") do |o|
EUCALYPTUS_OPTS[:ep_file] = o
end
opts.on("-b", "--config_file [FILE]", "Read all breakpoints and handler event configurations from this file") do |o|
EUCALYPTUS_OPTS[:bp_file] = o
end
opts.on("-d", "--dsl [FILE]", "Configure Eucalyptus using Ruby code (please see the README)") do |o|
EUCALYPTUS_OPTS[:dsl_file] = o
end
opts.on("-o", "--output [FILE]", "Print all output to a file (default is STDOUT)") do |o|
EUCALYPTUS_OPTS[:out] = File.open(o, "w") rescue (bail $!)
end
opts.on("-f", "Trace forked child processes") do |o|
EUCALYPTUS_OPTS[:fork] = true
end
opts.on("-k", "Kill the target process when Eucalyptus exits") do |o|
EUCALYPTUS_OPTS[:kill] = true
end
end
opts.parse!(ARGV) rescue (STDERR.puts $!; exit 1)
if EUCALYPTUS_OPTS[:pid] == nil
puts opts.help
exit
end
Eucalyptus.new(EUCALYPTUS_OPTS)
| ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/scripts/glibc_malloc.rb | Eucalyptus/scripts/glibc_malloc.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
## Get and print the register states
## Read the size argument to malloc
## Search the heap buffer for a DWORD
log.str "MALLOC() ======================================================"
@rtrace.print_registers
regs = @rtrace.get_registers
size = @rtrace.read64(@rtrace.get_sp(regs) + @rtrace.get_machine_word) if @rtrace.bits == 32
size = regs.rdi if @rtrace.bits == 64
@log.str "malloc(#{size})"
#locs = @rtrace.search_process(0x41414141)
locs = @rtrace.search_heap(0x41414141).flatten
if !locs.empty?
log.str "0x41414141 found at:"
locs.map do |l|
l.map do |i|
log.str " -> #{i.to_s(16)} #{@rtrace.get_mapping_name(i)}"
end
end
end
stack = @rtrace.get_stack_range
heap = @rtrace.get_heap_range
log.str "Stack => 0x#{stack.first.first.to_s(16)} ... 0x#{stack.first.last.to_s(16)}" if !stack.empty?
log.str "Heap => 0x#{heap.first.first.to_s(16)} ... 0x#{heap.first.last.to_s(16)}" if !heap.empty? | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/scripts/on_breakpoint.rb | Eucalyptus/scripts/on_breakpoint.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
log.str "your breakpoint hit!"
| ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/scripts/on_free.rb | Eucalyptus/scripts/on_free.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
## on_free example
## Get and print the register states
## Read the size argument to malloc
## Search the heap buffer for a DWORD
log.str "\nFREE() ======================================================"
@rtrace.print_registers
regs = @rtrace.get_registers
log.str "free(0x#{regs.rax.to_s(16)})" | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/scripts/on_attach.rb | Eucalyptus/scripts/on_attach.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
log.str "Attached to process #{@pid}" | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/example_configuration_files/dsl_example.rb | Eucalyptus/example_configuration_files/dsl_example.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the accompanying LICENSE file in the project root folder for terms.
## This is an example of using the Eucalyptus
## configuration DSL for debugging a program.
## It is heavily commented to help you
## understand what it does and why.
require './utils/parse_elf.rb'
malloc_addr = nil
## Open libc using the ELFReader class
## This path is hard coded and you might
## need to change it for the system you
## are on. Use ldd on your target binary
## to find the libc path it will use.
d = ELFReader.new("/lib/x86_64-linux-gnu/libc-2.19.so")
## Parse libc's ELF dynamic symbol table
## and locate the address of malloc(). We
## do this so we can set a breakpoint.
d.parse_dynsym do |sym|
if d.get_symbol_type(sym) == "FUNC" and d.get_dyn_symbol_name(sym) =~ /__libc_malloc/
malloc_addr = sym.st_value.to_i
puts "malloc symbol found @ 0x#{malloc_addr.to_s(16)}" if !malloc_addr.nil?
break
end
end
## Instruct Eucalyptus to launch a
## daemonized process
exec_file(
## Path to the binary
@target_binary,
## Arguments to the process
"some_argument",
## Environment variables for the process
{"env_var" => "some value"},
## Ruby code to run upon execution
Proc.new do
puts "I just launched a process!"
end)
## Declare a handler for a ptrace attach event
event_handler "on_attach", (Proc.new do
puts "I am now attached to the target (#{@pid})!"
end)
## Declare a handler for a segmentation fault signal
event_handler "on_segv", (Proc.new do
puts "Oh no I segfaulted!"
end)
## Set a breakpoint for malloc in libc.
## We got this address earlier from the
## ELFReader class we created.
add_breakpoint(
## Address (retrieved from ELFReader)
malloc_addr,
## Name of our breakpoint
"malloc",
## Library where it can be found
"/lib/x86_64-linux-gnu/libc-2.19.so",
## Number of hits before we uninstall it
5,
## Ruby code to run whenever the malloc()
## breakpoint is hit by the program
(Proc.new do
## Let the user know we hit the breakpoint
log.str "\nMALLOC() ======================================================"
## Print the registers
@rtrace.print_registers
## Retrieve registers OpenStruct
regs = @rtrace.get_registers
## Extract the size value passed to malloc
size = @rtrace.read64(@rtrace.get_sp(regs) + @rtrace.get_machine_word) if @rtrace.bits == 32
size = regs.rdi if @rtrace.bits == 64
## Display the call to malloc with size
@log.str "malloc(#{size})"
## Search the process for some values
#locs = @rtrace.search_process(0x41414141)
locs = @rtrace.search_heap(0x41414141).flatten
## Print out where we found this value
if !locs.empty?
log.str "0x41414141 found at:"
locs.map do |l|
l.map do |i|
log.str " -> #{i.to_s(16)} #{@rtrace.get_mapping_name(i)}"
end
end
end
## Print the location of the stack and heap
stack = @rtrace.get_stack_range
heap = @rtrace.get_heap_range
log.str "Stack => 0x#{stack.first.to_s(16)} ... 0x#{stack.last.to_s(16)}" if !stack.empty?
log.str "Heap => 0x#{heap.first.to_s(16)} ... 0x#{heap.last.to_s(16)}" if !heap.empty?
end)) | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/utils/linux-symbol.rb | Eucalyptus/utils/linux-symbol.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
## Simple script that uses nm to search for symbol offsets
## This is mainly for validating the parse_elf code
## ruby linux-symbol.rb /usr/local/my_binary 'authenticate'
if ARGV.size < 2
STDERR.puts "#{$0} <file> <symbol>"
exit
end
elf_obj = ARGV[0].to_s
symbol = ARGV[1].to_s
cmd = ["nm", "-C", "-D", elf_obj]
IO.popen({"LC_ALL" => "C"}, cmd) do |io|
io.each_line do |line|
address, _, func_sig = line.split(' ', 3)
if address.match(/^\h+$/i) and address.size.between?(8,16) == true
func_sig = func_sig.split('(').first if func_sig =~ /\(/
if func_sig =~ /#{symbol}/i
puts "bp=0x#{address}, name=#{func_sig.chomp}, lib=#{elf_obj}"
end
end
end
end | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/utils/elf_reader_example.rb | Eucalyptus/utils/elf_reader_example.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
require 'parse_elf'
require 'pp'
d = ELFReader.new(ARGV[0])
d.phdr.each do |p|
puts sprintf("\n%s", d.get_phdr_name(p))
pp p
end
## The section headers (if any) are automatically
## parsed at object instantiation
d.shdr.each do |s|
puts sprintf("\n%s", d.get_shdr_by_name(s))
pp s
end
## The dynamic segment is automatically
## parsed at object instantiation
d.dyn.each do |dyn|
pp dyn
end
d.parse_reloc do |r|
sym = d.lookup_rel(r)
puts sprintf("RELOC: %s %s 0x%08x %d %s\n", d.get_symbol_type(sym), d.get_symbol_bind(sym), sym.st_value.to_i, sym.st_size.to_i, d.get_dyn_symbol_name(sym));
end
d.parse_dynsym
d.parse_symtab
d.dynsym_symbols.each do |sym|
puts sym.st_value.to_s(16) if d.get_symbol_type(sym) == SymbolTypes::STT_FUNC and d.get_dyn_symbol_name(sym) == "malloc"
end
d.symtab_symbols.each do |sym|
puts sym.st_value.to_s(16) if d.get_symbol_type(sym) == SymbolTypes::STT_FUNC and d.get_sym_symbol_name(sym) == "malloc"
end | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/utils/parse_elf.rb | Eucalyptus/utils/parse_elf.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
## Optional ELF parser for Rtrace/Eucalyptus
## Support (and testing) for x86, x86_64 and ARM
## This is *NOT* a robust ELF parser. It was
## written specifically for extracting symbols
## from gcc/clang generated ELFs whose structures
## have not been tampered with. It does however
## use the ELF program header for parsing so
## it should work on a sstripped ELF. Pull
## requests for improving it are welcome!
## TODO: parse rela.dyn
require 'bindata'
## Basic ELF Header
class ELF32Header < BinData::Record
endian :little
string :e_ident, :read_length => 16
uint16 :e_type
uint16 :e_machine
uint32 :e_version
uint32 :e_entry
uint32 :e_phoff
uint32 :e_shoff
uint32 :e_flags
uint16 :e_ehsize
uint16 :e_phentsize
uint16 :e_phnum
uint16 :e_shentsize
uint16 :e_shnum
uint16 :e_shstrndx
end
## ELF Program Header
class ELF32ProgramHeader < BinData::Record
endian :little
uint32 :p_type
uint32 :p_offset
uint32 :p_vaddr
uint32 :p_paddr
uint32 :p_filesz
uint32 :p_memsz
uint32 :p_flags
uint32 :p_align
end
## ELF Section Header
class ELF32SectionHeader < BinData::Record
endian :little
uint32 :sh_name
uint32 :sh_type
uint32 :sh_flags
uint32 :sh_addr
uint32 :sh_offset
uint32 :sh_size
uint32 :sh_link
uint32 :sh_info
uint32 :sh_addralign
uint32 :sh_entsize
end
class ELF32Dynamic < BinData::Record
endian :little
uint32 :d_tag
uint32 :d_val
#uint32 :d_ptr
end
class ELF32Symbol < BinData::Record
endian :little
uint32 :st_name ## Symbol name (string tbl index)
uint32 :st_value ## Symbol value
uint32 :st_size ## Symbol size
uint8 :st_info ## Symbol type and binding
uint8 :st_other ## Symbol visibility
uint16 :st_shndx ## Section index
end
class ELF32Relocation < BinData::Record
endian :little
uint32 :r_offset ## Address
uint32 :r_info ## Type
end
## Basic ELF Header
class ELF64Header < BinData::Record
endian :little
string :e_ident, :read_length => 16
uint16 :e_type
uint16 :e_machine
uint32 :e_version
uint64 :e_entry
uint64 :e_phoff
uint64 :e_shoff
uint32 :e_flags
uint16 :e_ehsize
uint16 :e_phentsize
uint16 :e_phnum
uint16 :e_shentsize
uint16 :e_shnum
uint16 :e_shstrndx
end
## ELF Program Header
class ELF64ProgramHeader < BinData::Record
endian :little
uint32 :p_type
uint32 :p_flags
uint64 :p_offset
uint64 :p_vaddr
uint64 :p_paddr
uint32 :p_filesz
uint32 :p_memsz
uint32 :p_align
end
## ELF Section Header
class ELF64SectionHeader < BinData::Record
endian :little
uint32 :sh_name
uint32 :sh_type
uint64 :sh_flags
uint64 :sh_addr
uint64 :sh_offset
uint64 :sh_size
uint32 :sh_link
uint32 :sh_info
uint64 :sh_addralign
uint64 :sh_entsize
end
class ELF64Dynamic < BinData::Record
endian :little
uint64 :d_tag
uint64 :d_val
#uint32 :d_ptr
end
class ELF64Symbol < BinData::Record
endian :little
uint32 :st_name ## Symbol name (string tbl index)
uint8 :st_info ## Symbol type and binding
uint8 :st_other ## Symbol visibility
uint16 :st_shndx ## Section index
uint64 :st_value ## Symbol value
uint64 :st_size ## Symbol size
end
class ELF64Relocation < BinData::Record
endian :little
uint64 :r_offset ## Address
uint64 :r_info ## Type
end
class ELFTypes
ET_NONE = 0 ## No file type
ET_REL = 1 ## Relocatable file
ET_EXEC = 2 ## Executable file
ET_DYN = 3 ## Shared object file
ET_CORE = 4 ## Core file
end
class ShdrTypes
SHT_NULL = 0 ## Section header table entry unused
SHT_PROGBITS = 1 ## Program data
SHT_SYMTAB = 2 ## Symbol table
SHT_STRTAB = 3 ## String table
SHT_RELA = 4 ## Relocation entries with addends
SHT_HASH = 5 ## Symbol hash table
SHT_DYNAMIC = 6 ## Dynamic linking information
SHT_NOTE = 7 ## Notes
SHT_NOBITS = 8 ## Program space with no data (bss)
SHT_REL = 9 ## Relocation entries, no addends
SHT_SHLIB = 10 ## Reserved
SHT_DYNSYM = 11 ## Dynamic linker symbol table
SHT_INIT_ARRAY = 14 ## Array of constructors
SHT_FINI_ARRAY = 15 ## Array of destructors
SHT_PREINIT_ARRAY = 16 ## Array of pre-constructors
SHT_GROUP = 17 ## Section group
SHT_SYMTAB_SHNDX = 18 ## Extended section indexes
SHT_NUM = 19 ## Number of defined types.
SHT_LOOS = 0x60000000 ## Start OS-specific.
SHT_GNU_HASH = 0x6ffffff6 ## GNU-style hash table.
SHT_GNU_LIBLIST = 0x6ffffff7 ## Prelink library list
SHT_CHECKSUM = 0x6ffffff8 ## Checksum for DSO content.
SHT_LOSUNW = 0x6ffffffa ## Sun-specific low bound.
SHT_SUNW_move = 0x6ffffffa
SHT_SUNW_COMDAT = 0x6ffffffb
SHT_SUNW_syminfo = 0x6ffffffc
SHT_GNU_verdef = 0x6ffffffd ## Version definition section.
SHT_GNU_verneed = 0x6ffffffe ## Version needs section.
SHT_GNU_versym = 0x6fffffff ## Version symbol table.
SHT_HISUNW = 0x6fffffff ## Sun-specific high bound.
SHT_HIOS = 0x6fffffff ## End OS-specific type
SHT_LOPROC = 0x70000000 ## Start of processor-specific
SHT_HIPROC = 0x7fffffff ## End of processor-specific
SHT_LOUSER = 0x80000000 ## Start of application-specific
SHT_HIUSER = 0x8fffffff ## End of application-specific
end
class PhdrTypes
PT_NULL = 0 ## Program header table entry unused
PT_LOAD = 1 ## Loadable program segment
PT_DYNAMIC = 2 ## Dynamic linking information
PT_INTERP = 3 ## Program interpreter
PT_NOTE = 4 ## Auxiliary information
PT_SHLIB = 5 ## Reserved
PT_PHDR = 6 ## Entry for header table itself
PT_TLS = 7 ## Thread-local storage segment
PT_NUM = 8 ## Number of defined types
PT_LOOS = 0x60000000 ## Start of OS-specific
PT_GNU_EH_FRAME = 0x6474e550 ## GCC .eh_frame_hdr segment
PT_GNU_STACK = 0x6474e551 ## Indicates stack executability
PT_GNU_RELRO = 0x6474e552 ## Read-only after relocation
PT_LOSUNW = 0x6ffffffa
PT_SUNWSTACK = 0x6ffffffb ## Stack segment
PT_HIOS = 0x6fffffff ## End of OS-specific
PT_LOPROC = 0x70000000 ## Start of processor-specific
PT_HIPROC = 0x7fffffff ## End of processor-specific
end
class DynamicTypes
DT_NULL = 0 ## Marks end of dynamic section
DT_NEEDED = 1 ## Name of needed library
DT_PLTRELSZ = 2 ## Size in uint8s of PLT relocs
DT_PLTGOT = 3 ## Processor defined value
DT_HASH = 4 ## Address of symbol hash table
DT_STRTAB = 5 ## Address of string table
DT_SYMTAB = 6 ## Address of symbol table
DT_RELA = 7 ## Address of Rela relocs
DT_RELASZ = 8 ## Total size of Rela relocs
DT_RELAENT = 9 ## Size of one Rela reloc
DT_STRSZ = 10 ## Size of string table
DT_SYMENT = 11 ## Size of one symbol table entry
DT_INIT = 12 ## Address of init function
DT_FINI = 13 ## Address of termination function
DT_SONAME = 14 ## Name of shared object
DT_RPATH = 15 ## Library search path (deprecated)
DT_SYMBOLIC = 16 ## Start symbol search here
DT_REL = 17 ## Address of Rel relocs
DT_RELSZ = 18 ## Total size of Rel relocs
DT_RELENT = 19 ## Size of one Rel reloc
DT_PLTREL = 20 ## Type of reloc in PLT
DT_DEBUG = 21 ## For debugging; unspecified
DT_TEXTREL = 22 ## Reloc might modify .text
DT_JMPREL = 23 ## Address of PLT relocs
DT_BIND_NOW = 24 ## Process relocations of object
DT_INIT_ARRAY = 25 ## Array with addresses of init fct
DT_FINI_ARRAY = 26 ## Array with addresses of fini fct
DT_INIT_ARRAYSZ = 27 ## Size in uint8s of DT_INIT_ARRAY
DT_FINI_ARRAYSZ = 28 ## Size in uint8s of DT_FINI_ARRAY
DT_RUNPATH = 29 ## Library search path
DT_FLAGS = 30 ## Flags for the object being loaded
DT_ENCODING = 32 ## Start of encoded range
DT_PREINIT_ARRAY = 32 ## Array with addresses of preinit fct
DT_PREINIT_ARRAYSZ = 33 ## size in uint8s of DT_PREINIT_ARRAY
DT_NUM = 34 ## Number used
DT_LOOS = 0x6000000d ## Start of OS-specific
DT_HIOS = 0x6ffff000 ## End of OS-specific
DT_LOPROC = 0x70000000 ## Start of processor-specific
DT_HIPROC = 0x7fffffff ## End of processor-specific
DT_ADDRRNGLO = 0x6ffffe00
DT_GNU_HASH = 0x6ffffef5 ## GNU-style hash table.
DT_TLSDESC_PLT = 0x6ffffef6
DT_TLSDESC_GOT = 0x6ffffef7
DT_GNU_CONFLICT = 0x6ffffef8 ## Start of conflict section
DT_GNU_LIBLIST = 0x6ffffef9 ## Library list
DT_CONFIG = 0x6ffffefa ## Configuration information.
DT_DEPAUDIT = 0x6ffffefb ## Dependency auditing.
DT_AUDIT = 0x6ffffefc ## Object auditing.
DT_PLTPAD = 0x6ffffefd ## PLT padding.
DT_MOVETAB = 0x6ffffefe ## Move table.
DT_SYMINFO = 0x6ffffeff ## Syminfo table.
DT_ADDRRNGHI = 0x6ffffeff
end
class SymbolBind
STB_LOCAL = 0 ## Local symbol
STB_GLOBAL = 1 ## Global symbol
STB_WEAK = 2 ## Weak symbol
STB_NUM = 3 ## Number of defined types.
STB_LOOS = 10 ## Start of OS-specific
STB_HIOS = 12 ## End of OS-specific
STB_LOPROC = 13 ## Start of processor-specific
STB_HIPROC = 15 ## End of processor-specific
end
class SymbolTypes
STT_NOTYPE = 0 ## Symbol type is unspecified
STT_OBJECT = 1 ## Symbol is a data object
STT_FUNC = 2 ## Symbol is a code object
STT_SECTION = 3 ## Symbol associated with a section
STT_FILE = 4 ## Symbol's name is file name
STT_COMMON = 5 ## Symbol is a common data object
STT_TLS = 6 ## Symbol is thread-local data object
STT_NUM = 7 ## Number of defined types.
STT_LOOS = 10 ## Start of OS-specific
STT_HIOS = 12 ## End of OS-specific
STT_LOPROC = 13 ## Start of processor-specific
STT_HIPROC = 15 ## End of processor-specific
end
class EIClass
EI_CLASS = 4
ELFCLASS32 = 1
ELFCLASS64 = 2
end
## Members:
##
## ehdr - a structure holding the ELF header
## phdr - an array of BinData structures holding each Program header
## shdr - an array of BinData structures holding each Section header
## dyn - an array of BinData structures holding each dynamic table entry
## symbols - an array of BinData structures holding each symbol table entry
##
## Methods:
##
## parse_ehdr - stores the Elf header in the ELFReader::ehdr BinData structure
## parse_phdr - stores an array of BinData structures containing the Phdr in ELFReader::phdr
## parse_shdr - stores an array of BinData structures containing the Shdr in ELFReader::shdr
## parse_dyn - stores an array of BinData structures containing the Dynamic table in ELFReader::dyn
## parse_dynsym - stores an array of BinData structures containing the Dyn in ELFReader::dyn
## parse_symtab - returns an array of BinData structures containing the symbol table
class ELFReader
attr_accessor :opts, :elf, :ehdr, :phdr, :shdr, :dyn, :strtab, :hash,
:jmprel, :rel, :dynsym, :symtab, :syment, :dynsym_symbols,
:symtab_symbols, :reloc, :gnu_hash, :bits, :baseaddr,
:dynsym_sym_count
def initialize(elf_file)
begin
@elf = File.open(elf_file, 'rb').read
@bits = 32
if @elf[EIClass::EI_CLASS].unpack('c').first == EIClass::ELFCLASS32
@bits = 32
@baseaddr = 0x8048000
end
if @elf[EIClass::EI_CLASS].unpack('c').first == EIClass::ELFCLASS64
@bits = 64
@baseaddr = 0x400000
end
rescue Exception => e
puts "Could not read [#{elf_file}] (#{e})"
exit
end
@phdr = []
@shdr = []
@dyn = []
@reloc = []
@dynsym_symbols = []
@symtab_symbols = []
@dynsym_sym_count = 0
@symtab_sym_count = 0
parse_ehdr
parse_phdr
parse_shdr
parse_dyn
end
def parse_ehdr
@ehdr = ELF32Header.new if @bits == 32
@ehdr = ELF64Header.new if @bits == 64
@ehdr.read(@elf.dup)
end
def parse_phdr
0.upto(ehdr.e_phnum.to_i-1) do |j|
p = ELF32ProgramHeader.new if @bits == 32
p = ELF64ProgramHeader.new if @bits == 64
p.read(@elf.dup[ehdr.e_phoff.to_i + (ehdr.e_phentsize.to_i * j), ehdr.e_phentsize.to_i])
phdr.push(p)
end
end
def get_phdr(type)
phdr.each do |p|
return p if p.p_type.to_i == type
end
return nil
end
def get_phdr_name(phdr)
case phdr.p_type.to_i
when PhdrTypes::PT_NULL
return "PT_NULL"
when PhdrTypes::PT_LOAD
return "PT_LOAD"
when PhdrTypes::PT_DYNAMIC
return "PT_DYNAMIC"
when PhdrTypes::PT_INTERP
return "PT_INTERP"
when PhdrTypes::PT_NOTE
return "PT_NOTE"
when PhdrTypes::PT_SHLIB
return "PT_SHLIB"
when PhdrTypes::PT_PHDR
return "PT_PHDR"
when PhdrTypes::PT_TLS
return "PT_TLS"
when PhdrTypes::PT_NUM
return "PT_NUM"
when PhdrTypes::PT_LOOS
return "PT_LOOS"
when PhdrTypes::PT_GNU_EH_FRAME
return "PT_GNU_EH_FRAME"
when PhdrTypes::PT_GNU_STACK
return "PT_GNU_STACK"
when PhdrTypes::PT_GNU_RELRO
return "PT_GNU_RELRO"
when PhdrTypes::PT_LOSUNW
return "PT_LOSUNW"
when PhdrTypes::PT_SUNWSTACK
return "PT_SUNWSTACK"
when PhdrTypes::PT_HIOS
return "PT_HIOS"
when PhdrTypes::PT_LOPROC
return "PT_LOPROC"
when PhdrTypes::PT_HIPROC
return "PT_HIPROC"
end
end
def parse_shdr
0.upto(@ehdr.e_shnum.to_i-1) do |j|
s = ELF32SectionHeader.new if @bits == 32
s = ELF64SectionHeader.new if @bits == 64
s.read(@elf.dup[@ehdr.e_shoff + (@ehdr.e_shentsize * j), @ehdr.e_shentsize])
@shstrtab = s if s.sh_type.to_i == ShdrTypes::SHT_STRTAB and j == @ehdr.e_shstrndx.to_i
shdr.push(s)
end
end
def get_shdr(type)
shdr.each do |s|
return s if s.sh_type.to_i == type
end
return nil
end
def get_shdr_by_name(shdr)
parse_dyn if dyn.size == 0
return if @shstrtab.nil? or shdr.sh_type == 0
str = @elf.dup[@shstrtab.sh_offset.to_i + shdr.sh_name.to_i, 256]
str = str[0, str.index("\x00")]
end
def parse_dyn
p = get_phdr(PhdrTypes::PT_DYNAMIC)
return if not p
dynamic_section_offset = p.p_vaddr.to_i
if @bits == 32
d = ELF32Dynamic.new
@strtab = ELF32SectionHeader.new
@hash = ELF32SectionHeader.new
@gnu_hash = ELF32SectionHeader.new
@dynsym = ELF32SectionHeader.new
@jmprel = ELF32SectionHeader.new
@rel = ELF32SectionHeader.new
elsif @bits == 64
d = ELF64Dynamic.new
@strtab = ELF64SectionHeader.new
@hash = ELF64SectionHeader.new
@gnu_hash = ELF64SectionHeader.new
@dynsym = ELF64SectionHeader.new
@jmprel = ELF64SectionHeader.new
@rel = ELF64SectionHeader.new
end
@syment = 0
@pltrelsz = 0
@relsz = 0
0.upto(p.p_filesz.to_i / d.num_bytes.to_i) do |j|
d = ELF32Dynamic.new if @bits == 32
d = ELF64Dynamic.new if @bits == 64
d.read(@elf.dup[p.p_offset.to_i + (d.num_bytes.to_i * j), d.num_bytes.to_i])
break if d.d_tag.to_i == DynamicTypes::DT_NULL
exec_type = 1 if ehdr.e_type.to_i == ELFTypes::ET_EXEC
dyna_type = 1 if ehdr.e_type.to_i == ELFTypes::ET_DYN
case d.d_tag.to_i
when DynamicTypes::DT_STRTAB
@strtab.sh_offset = d.d_val.to_i - @baseaddr if exec_type
@strtab.sh_offset = d.d_val.to_i if dyna_type
when DynamicTypes::DT_SYMENT
@syment = d.d_val.to_i
when DynamicTypes::DT_HASH
@hash.sh_offset = d.d_val.to_i - @baseaddr if exec_type
@hash.sh_offset = d.d_val.to_i if dyna_type
@dynsym_sym_count = @elf.dup[hash.sh_offset + 4, 4].unpack('V')[0]
when DynamicTypes::DT_GNU_HASH
@gnu_hash.sh_offset = d.d_val.to_i - @baseaddr if exec_type
@gnu_hash.sh_offset = d.d_val.to_i if dyna_type
## DT_HASH usually trumps DT_GNU_HASH
@dynsym_sym_count = parse_dt_gnu_hash if @dynsym_sym_count == 0 and @hash.sh_offset == 0
when DynamicTypes::DT_SYMTAB
@dynsym.sh_offset = d.d_val.to_i - @baseaddr if exec_type
@dynsym.sh_offset = d.d_val.to_i if dyna_type
when DynamicTypes::DT_PLTRELSZ
@pltrelsz = d.d_val.to_i
when DynamicTypes::DT_RELSZ
@relsz = d.d_val.to_i
when DynamicTypes::DT_JMPREL
@jmprel.sh_offset = d.d_val.to_i - @baseaddr if exec_type
@jmprel.sh_offset = d.d_val.to_i if dyna_type
when DynamicTypes::DT_REL
@rel.sh_offset = d.d_val.to_i - @baseaddr if exec_type
@rel.sh_offset = d.d_val.to_i if dyna_type
end
dyn.push(d)
end
end
## Returns the number of symbols
## DT_GNU_HASH is poorly documented. "Read the source"
## is not an appropriate response. Thanks Metasm
## for providing a reference implementation
def parse_dt_gnu_hash
hbl = @elf.dup[@gnu_hash.sh_offset, 4].unpack('V')[0]
si = @elf.dup[@gnu_hash.sh_offset+4, 4].unpack('V')[0]
mw = @elf.dup[@gnu_hash.sh_offset+8, 4].unpack('V')[0]
shift2 = @elf.dup[@gnu_hash.sh_offset+12, 4].unpack('V')[0]
filter = []
hbu = []
xword = 4
xword = 8 if bits == 64
mw.times do |i|
filter.push(@elf.dup[@gnu_hash.sh_offset+16+i, xword].unpack('V')[0])
end
hbl.times do |i|
hbu.push(@elf.dup[@gnu_hash.sh_offset+(mw*xword)+i, xword].unpack('V')[0])
end
hs = 0
hbu.each do |hb|
i = 0
next if hb == 0
loop do
f = @elf.dup[@gnu_hash.sh_offset+(mw*xword)+(hbl*4)+i, 4].unpack('V')[0]
i+=4
hs += 1
break if f & 1 == 1
end
end
return hs + si
end
## Unused method
def get_dyn(type)
dyn.each do |d|
if d.d_tag.to_i == type
return d
end
end
end
def parse_reloc(&block)
parse_rel(@rel, @relsz, &block)
parse_rel(@jmprel, @pltrelsz, &block)
end
def parse_rel(rel_loc, sz)
p = get_phdr(PhdrTypes::PT_DYNAMIC)
if p.nil? == false
#parse the dynamic relocations
tr = ELF32Relocation.new if @bits == 32
tr = ELF64Relocation.new if @bits == 64
0.upto((sz.to_i-1) / tr.num_bytes) do |j|
r = ELF32Relocation.new if @bits == 32
r = ELF64Relocation.new if @bits == 64
r.read(@elf.dup[rel_loc.sh_offset.to_i + j*tr.num_bytes, tr.num_bytes])
# TODO: merge with existing symbols? symbols.push(lookup_rel(r))
# parse_reloc should be stand alone
#s is a temporary ElfSymbol
#check to see if it already exists by name
s = lookup_rel(r)
sym = get_symbol_by_name(get_dyn_symbol_name(s))
#if the symbol already exists, and it doesnt have an address
# set the relocation info to point to the plt address
if not sym
@dynsym_symbols.push(s)
else
sym.st_value = s.st_value if 0 == sym.st_value.to_i
end
yield(r) if block_given?
reloc.push(r)
end
else
puts "[-] No PT_DYNAMIC phdr entry. (static binary)"
end
end
def lookup_rel(r)
addr = r.r_offset
if @bits == 32
r_type = r.r_info & 0xff
pos = r.r_info >> 8
sym = ELF32Symbol.new
else
r_type = r.r_info & 0xffffffff
pos = r.r_info >> 32
sym = ELF64Symbol.new
end
sym.read(@elf.dup[dynsym.sh_offset + (pos * sym.num_bytes), sym.num_bytes])
sym.st_value = addr if sym.st_value.to_i == 0
return sym
end
def parse_dynsym
d = get_shdr(ShdrTypes::SHT_DYNSYM)
return if !d.kind_of? ELF32SectionHeader and !d.kind_of? ELF64SectionHeader
0.upto(@dynsym_sym_count.to_i-1) do |j|
sym = ELF32Symbol.new if @bits == 32
sym = ELF64Symbol.new if @bits == 64
sym.read(@elf.dup[d.sh_offset.to_i + (j * sym.num_bytes), sym.num_bytes])
str = @elf.dup[strtab.sh_offset.to_i + sym.st_name.to_i, 256]
yield(sym) if block_given?
@dynsym_symbols.push(sym)
end
end
def parse_symtab
@symtab = get_shdr(ShdrTypes::SHT_SYMTAB)
return if !@symtab.kind_of? ELF32SectionHeader and !@symtab.kind_of? ELF64SectionHeader
@sym_str_tbl = shdr[@symtab.sh_link.to_i]
@symtab_sym_count = (@symtab.sh_size.to_i / (ELF32Symbol.new).num_bytes) if @bits == 32
@symtab_sym_count = (@symtab.sh_size.to_i / (ELF64Symbol.new).num_bytes) if @bits == 64
0.upto(@symtab_sym_count.to_i-1) do |j|
sym = ELF32Symbol.new if @bits == 32
sym = ELF64Symbol.new if @bits == 64
sym.read(@elf.dup[@symtab.sh_offset.to_i + (j * sym.num_bytes), sym.num_bytes])
str = @elf.dup[@sym_str_tbl.sh_offset.to_i + sym.st_name.to_i, 256]
yield(sym) if block_given?
@symtab_symbols.push(sym)
end
end
def get_symbol_by_name(name)
@dynsym_symbols.each do |s|
return s if get_dyn_symbol_name(s) == name
end
@symtab_symbols.each do |s|
return s if get_sym_symbol_name(s) == name
end
return nil
end
def get_dyn_symbol_name(sym)
str = @elf.dup[@strtab.sh_offset.to_i + sym.st_name.to_i, 256]
str = str[0, str.index("\x00")]
end
def get_sym_symbol_name(sym)
str = @elf.dup[@sym_str_tbl.sh_offset.to_i + sym.st_name.to_i, 256]
str = str[0, str.index("\x00")]
end
def get_symbol_bind(sym)
case (sym.st_info.to_i >> 4)
when SymbolBind::STB_LOCAL
return "LOCAL"
when SymbolBind::STB_GLOBAL
return "GLOBAL"
when SymbolBind::STB_WEAK
return "WEAK"
when SymbolBind::STB_NUM
return "NUM"
when SymbolBind::STB_LOOS
return "LOOS"
when SymbolBind::STB_HIOS
return "HIOS"
when SymbolBind::STB_LOPROC
return "LOPROC"
when SymbolBind::STB_HIPROC
return "HIPROC"
end
end
def get_symbol_type(sym)
case (sym.st_info.to_i & 0xf)
when SymbolTypes::STT_NOTYPE
return "NOTYPE"
when SymbolTypes::STT_OBJECT
return "OBJECT"
when SymbolTypes::STT_FUNC
return "FUNC"
when SymbolTypes::STT_SECTION
return "SECTION"
when SymbolTypes::STT_FILE
return "FILE"
when SymbolTypes::STT_COMMON
return "COMMON"
when SymbolTypes::STT_TLS
return "TLS"
when SymbolTypes::STT_NUM
return "NUM"
when SymbolTypes::STT_LOOS
return "LOOS"
when SymbolTypes::STT_HIOS
return "HIOS"
when SymbolTypes::STT_LOPROC
return "LOPROC"
when SymbolTypes::STT_HIPROC
return "HIPROC"
end
end
end
if $0 == __FILE__
require 'pp'
d = ELFReader.new(ARGV[0])
## The Elf header is automatically parsed
## at object instantiation
pp d.ehdr
## The program headers are automatically
## parsed at object instantiation
d.phdr.each do |p|
puts sprintf("\n%s", d.get_phdr_name(p))
pp p
end
## The section headers (if any) are automatically
## parsed at object instantiation
d.shdr.each do |s|
puts sprintf("\n%s", d.get_shdr_by_name(s))
pp s
end
## The dynamic segment is automatically
## parsed at object instantiation
d.dyn.each do |dyn|
pp dyn
end
## Parse the relocation entires for dynamic executables
d.parse_reloc do |r|
sym = d.lookup_rel(r)
puts sprintf("RELOC: %s %s 0x%08x %d %s\n", d.get_symbol_type(sym), d.get_symbol_bind(sym), sym.st_value.to_i, sym.st_size.to_i, d.get_dyn_symbol_name(sym));
end
## The parse_symtab and parse_dynsym
## methods can optionally take a block
d.parse_dynsym do |sym|
puts sprintf("DYNSYM: %s %s 0x%08x %d %s\n", d.get_symbol_type(sym), d.get_symbol_bind(sym), sym.st_value.to_i, sym.st_size.to_i, d.get_dyn_symbol_name(sym));
end
d.parse_symtab do |sym|
puts sprintf("SYMTAB: %s %s 0x%08x %d %s\n", d.get_symbol_type(sym), d.get_symbol_bind(sym), sym.st_value.to_i, sym.st_size.to_i, d.get_sym_symbol_name(sym));
end
## Print each symbol collected by parse_dynsym and parse_symtab
#d.dynsym_symbols.each do |sym|
# puts sprintf("DYNSYM: %s %s 0x%08x %d %s\n", d.get_symbol_type(sym), d.get_symbol_bind(sym), sym.st_value.to_i, sym.st_size.to_i, d.get_dyn_symbol_name(sym));
#end
#d.symtab_symbols.each do |sym|
# puts sprintf("SYMTAB: %s %s 0x%08x %d %s\n", d.get_symbol_type(sym), d.get_symbol_bind(sym), sym.st_value.to_i, sym.st_size.to_i, d.get_sym_symbol_name(sym));
#end
end
| ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/common/common.rb | Eucalyptus/common/common.rb | class Eucalyptus
def which_threads
if threads.size == 1
pid = threads[0].to_i
return
end
puts "Thread IDs:"
threads.each { |h| puts h }
puts "Which thread ID do you want to trace?"
pid = STDIN.gets.chomp.to_i
end
end
| ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/common/output.rb | Eucalyptus/common/output.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the accompanying LICENSE file in the project root folder for terms.
class EucalyptusLog
def initialize(out)
@out = out
end
def str(s)
@out.puts s
end
def hit(addr, function_name)
@out.puts "[ #{addr} #{function_name} ]"
end
def finalize
@out.puts "...Eucalyptus is done!"
end
end | ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
YahooArchive/rtrace | https://github.com/YahooArchive/rtrace/blob/248477f80a4e059f2cf96687823cc8d1b843e11e/Eucalyptus/common/config.rb | Eucalyptus/common/config.rb | ## Copyright 2015,2016, Yahoo! Inc.
## Copyrights licensed under the New BSD License. See the
## accompanying LICENSE file in the project root folder for terms.
class Eucalyptus
## Add a breakpoint
## addr - Address to set the breakpoint on,
## either absolute or from parse_elf
## name - Name of the breakpoint
## lib - Name of the library its found in
## count - Number of times to hit the breakpoint
## code - A Ruby block for when the breakpoint is hit
def add_breakpoint(addr, name="", lib=nil, count=0, code)
if code.kind_of?(Proc) == false
puts "add_breakpoint: I need a block! You gave me #{code.class}"
return
end
bp = OpenStruct.new
bp.base = 0
bp.addr = addr
bp.name = name
bp.code = code
bp.count = count
bp.lib = lib.gsub(/[\s\n]+/, "")
bp.hits = 0
breakpoints.push(bp)
end
## Store a signal handler
## event - signal string
## code - Ruby block
def event_handler(event, code)
hdlrs = %w[ on_attach on_detach on_single_step on_syscall_continue on_continue on_exit
on_signal on_sigint on_segv on_illegal_instruction on_sigtrap on_fork_child
on_sigchild on_sigterm on_sigstop on_iot_trap on_stop on_execve on_vfork_done
on_seccomp on_kill on_abort on_sigbus unhandled_signal on_syscall on_clone ]
if hdlrs.include?(event) == false
puts "event_handler: I don't support event #{event}"
return
end
if code.kind_of?(Proc) == false
puts "event_handler: I need a block! You gave me #{code.class}"
return
end
event_handlers.store(event, code)
end
## Eucalyptus supports a DSL for configuration
## This is a wrapper that evals a configuration
## script. That script should call the methods
## above this comment.
def config_dsl(file)
eval(File.read(file))
end
def parse_config_file(file)
return if file.nil?
fd = File.open(file)
## All the handlers a user can script
## There is no specific order to these
hdlrs = %w[ on_attach on_detach on_single_step on_syscall_continue on_continue on_exit
on_signal on_sigint on_segv on_illegal_instruction on_sigtrap on_fork_child
on_sigchild on_sigterm on_sigstop on_iot_trap on_stop on_execve on_vfork_done
on_seccomp on_kill on_abort on_sigbus unhandled_signal on_syscall ]
lines = fd.readlines
lines.map { |x| x.chomp }
lines.each do |tl|
next if tl[0].chr == ';' or tl.nil?
bp = OpenStruct.new
bp.base = 0
bp.flag = true
bp.hits = 0
bp.count = nil
r = tl.split(",")
if r.size < 2 then next end
r.each do |e|
hdlrs.each do |l|
if e.match(/#{l}=/)
i,p = tl.split("=")
i.gsub!(/[\s\n]+/, "")
p.gsub!(/[\s\n]+/, "")
p = File.read(p)
event_handlers.store(i,p)
next
end
end
if e.match(/addr=/)
addr = e.split("bp=").last
bp.addr = addr.gsub(/[\s\n]+/, "")
end
if e.match(/name=/)
name = e.split("name=").last
bp.name = name.gsub(/[\s\n]+/, "")
end
if e.match(/count=/)
count = e.split("count=").last
bp.count = count.to_i
end
if e.match(/code=/)
code = e.split("code=").last
c = code.gsub(/[\s\n]+/, "")
r = File.read(c)
bp.code = r
end
if e.match(/lib=/)
lib = e.split("lib=").last
bp.lib = lib.gsub(/[\s\n]+/, "")
end
end
bp.hits = 0
breakpoints.push(bp)
end
end
## Execute a program
## path - Path on disk to the file
## args - Array of arguments to pass
## env - Hash of environment variables
## code - Optional Ruby block to run
def exec_file(path, args, env, code=nil)
if args.kind_of?(String) == false and env.kind_of?(Hash) == false
puts "exec_file: args must be an Array and env must be a Hash. (args=#{args.class}) (env=#{env.class})"
return
end
exec_proc.args = ""
exec_proc.env = {}
exec_proc.target = path
exec_proc.args = args
exec_proc.env = env
exec_proc.code = code if code.kind_of?(Proc)
end
def parse_exec_proc(file)
return if file.nil?
fd = File.open(file)
proc_control = %w[ target args env ]
lines = fd.readlines
lines.map { |x| x.chomp }
exec_proc.args = Array.new
exec_proc.env = Hash.new
lines.each do |tl|
if tl[0].chr == ';' or tl.nil? then next end
k,v,l = tl.split(':')
if k.match(/target/)
## Dirty little hack if a : is used
## in the target path
v = "#{v}:#{l}" if !l.nil?
v.gsub!(/[\n]+/, "")
v.gsub!(/[\s]+/, "")
exec_proc.target = v
end
if k.match(/args/)
v.gsub!(/[\n]+/, "")
exec_proc.args = v
end
if k.match(/env/)
v.gsub!(/[\n]+/, "")
k,v = v.split('=')
k.gsub!(/[\s]+/, "")
exec_proc.env.store(k,v)
end
end
end
end
| ruby | BSD-3-Clause | 248477f80a4e059f2cf96687823cc8d1b843e11e | 2026-01-04T17:44:47.121226Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/group_spec.rb | spec/group_spec.rb | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
TOP_LEVEL = self
def foo; end
def bar; end
module Fruity
describe Group do
lambdas = [->{1},->{2}]
it "can be built from lambdas" do
group = Group.new(*lambdas)
group.elements.values.should == lambdas
end
it "can be built from a block with no parameter" do
group = Group.new do
first(&lambdas.first)
last(&lambdas.last)
end
group.elements.should == {
:first => lambdas.first,
:last => lambdas.last,
}
group.options[:self].object_id.should equal(self.object_id)
end
it "can be built from a block taking a parameter" do
group = Group.new do |cmp|
cmp.first(&lambdas.first)
cmp.last(&lambdas.last)
->{ second{} }.should raise_error(NameError)
end
group.elements.should == {
:first => lambdas.first,
:last => lambdas.last,
}
group.options[:self].should == nil
end
it "can be built from list of method names and an object" do
str = "Hello"
group = Group.new(:upcase, :downcase, :on => str)
group.elements.should == {
:upcase => str.method(:upcase),
:downcase => str.method(:downcase),
}
end
it "can be built from list of method names and an object" do
group = Group.new(:foo, :bar)
group.elements.should == {
:foo => TOP_LEVEL.method(:foo),
:bar => TOP_LEVEL.method(:bar),
}
end
end
end | ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/find_thresold.rb | spec/find_thresold.rb | require_relative "../lib/fruity"
power = 15
x = 2
n = 30
min = 1
max = 2
s = 10
n.times.map do
group = Fruity::Group.new(*[->{}] * s, *[->{ 2 + 2 }] * s, :baseline => :none, :samples => 20, :magnify => 1 << power)
means = group.run.stats.map{|s| s[:mean]}
noops = means.first(s).sort
plus = means.last(s).sort
min = [min, noops.last / noops.first].max
max = [max, plus.first / noops.last].min
p min, max
raise "Damn, #{min} >= #{max}" if min >= max
end.sort
puts "Threshold between #{min} and #{max} are ok, suggesting #{Math.sqrt(min * max)}"
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/comparison_run_spec.rb | spec/comparison_run_spec.rb | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
module Fruity
describe ComparisonRun do
let(:group) { Group.new ->{1}, ->{2} }
let(:timings){ ([[1.0, 2.0]] * 10).transpose }
subject { @run = ComparisonRun.new(group, timings, nil) }
its(:comparison) { should == {
:mean=>2.0,
:factor=>2.0,
:max=>2.0,
:min=>2.0,
:rounding=>666,
:precision=>0.0,
}
}
end
end | ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/fruity_spec.rb | spec/fruity_spec.rb | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Fruity do
it "is able to report that two identical blocks are identical" do
report = Fruity.report(->{ 2 ** 2 }, ->{ 2 ** 2 })
report.factor.should == 1.0
end
it "is able to report very small performance differences" do
report = Fruity.report(->{ sleep(1.0) }, ->{ sleep(1.001) })
report.factor.should == 1.001
end
it "is able to report a 2x difference even for small blocks" do
report = Fruity.report(->{ 2 ** 2 }, ->{ 2 ** 2 ; 2 ** 2 })
report.factor.should == 2.0
end
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/util_spec.rb | spec/util_spec.rb | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
module Fruity
describe Util do
its(:clock_precision) { should == 1.0e-6 }
its(:proper_time_precision) { should == 4.0e-06 }
describe :sufficient_magnification do
it "returns a big value for a quick (but not trivial)" do
Util.sufficient_magnification(->{ 2 + 2 }).should > 10000
end
it "return 1 for a sufficiently slow block" do
Util.sufficient_magnification(->{sleep(0.01)}).should == 1
end
it "should raise an error for a trivial block" do
->{
Util.sufficient_magnification(->{})
}.should raise_error
end
end
describe :stats do
it "returns cools stats on the given values" do
Util.stats([0, 4]).should == {
:min => 0,
:max => 4,
:mean => 2,
:sample_std_dev => 2.8284271247461903,
}
end
end
describe :difference do
it "returns stats for the difference of two series" do
s = Util.stats([0, 4])
Util.difference(s, s).should == {
:min => -4,
:max => 4,
:mean => 0,
:sample_std_dev => 4,
}
end
it "gives similar results when comparing an exec and its baseline from stats on proper_time" do
exec = ->{ 2 ** 3 ** 4 }
options = {:magnify => Util.sufficient_magnification(exec) }
n = 100
timings = [exec, ->{}].map do |e|
n.times.map { Util.real_time(e, options) }
end
proper = Util.stats(timings.transpose.map{|e, b| e - b})
diff = Util.difference(*timings)
diff[:mean].should be_within(Float::EPSILON).of(proper[:mean])
diff[:max].should be_between(proper[:max], proper[:max]*2)
diff[:min].should <= proper[:min]
diff[:sample_std_dev].should be_between(proper[:sample_std_dev], 2 * proper[:sample_std_dev])
end
end
describe :filter do
it "returns the filtered series" do
Util.filter([4, 5, 2, 3, 1], 0.21, 0.39).should == [2, 3, 4]
end
end
end
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/manual_test.rb | spec/manual_test.rb | require_relative "../lib/fruity"
compare do
one { 42.nil? }
two { 42.nil?; 42.nil? }
end
compare do
two { 42.nil?; 42.nil? }
two_again { 42.nil?; 42.nil? }
three { 42.nil?; 42.nil?; 42.nil? }
four { 42.nil?; 42.nil?; 42.nil?; 42.nil? }
five { 42.nil?; 42.nil?; 42.nil?; 42.nil?; 42.nil? }
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/runner_spec.rb | spec/runner_spec.rb | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
module Fruity
describe Runner do
let(:group) { Group.new(:upcase, :downcase, :on => "Hello") }
let(:runner){ Runner.new(group) }
it "runs from a Group" do
run = runner.run(:samples => 42, :magnify => 100, :baseline => :split)
run.timings.should be_array_of_size(2, 42)
run.baselines.should be_array_of_size(2, 42)
end
it "can use a single baseline" do
run = runner.run(:samples => 42, :magnify => 100, :baseline => :single)
run.timings.should be_array_of_size(2, 42)
run.baselines.should be_array_of_size(42)
end
it "can use no baseline" do
run = runner.run(:samples => 42, :magnify => 100, :baseline => :none)
run.timings.should be_array_of_size(2, 42)
run.baselines.should == nil
end
end
end | ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/baseline_spec.rb | spec/baseline_spec.rb | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
module Fruity
describe Baseline do
describe "#[]" do
it "returns an object of the right type" do
b = Baseline[Proc.new{ 42 }]
b.class.should == Proc
b.lambda?.should == false
b.call.should == nil
b = Baseline[lambda{ 42 }]
b.class.should == Proc
b.lambda?.should == true
b.call.should == nil
b = Baseline[Fruity.method(:compare)]
b.class.should == Method
b.call.should == nil
end
it "copies the arity" do
b = Baseline[lambda{|a, b| 42}]
b.call(1, 2).should == nil
lambda{
b.call(1)
}.should raise_error
lambda{
b.call(1, 2, 3)
}.should raise_error
Baseline[lambda{|a, *b| 42}].call(1, 2, 3, 4, 5, 6).should == nil
end
end
end
end | ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'fruity'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
RSpec.configure do |config|
end
RSpec::Matchers.define :be_between do |low,high|
match do |actual|
@low, @high = low, high
actual.between? low, high
end
failure_message_for_should do |actual|
"expected to be between #{@low} and #{@high}, but was #{actual}"
end
failure_message_for_should_not do |actual|
"expected not to be between #{@low} and #{@high}, but was #{actual}"
end
end
RSpec::Matchers.define :be_array_of_size do |*dimensions|
match do |actual|
@dimensions = dimensions
@actual = []
while actual.is_a?(Array)
@actual << actual.size
actual = actual.first
end
@dimensions == @actual
end
failure_message_for_should do |actual|
"expected to be an array of dimension #{@dimensions.join('x')} but was #{@actual.join('x')}"
end
failure_message_for_should_not do |actual|
"expected not to be an array of dimension #{@dimensions.join('x')}"
end
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/lib/fruity.rb | lib/fruity.rb | require_relative "fruity/base"
extend Fruity | ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/lib/fruity/named_block_collector.rb | lib/fruity/named_block_collector.rb | module Fruity
class NamedBlockCollector
def initialize(to_hash)
@to_hash = to_hash
end
def method_missing(method, *args, &block)
super unless args.empty?
@to_hash[method] = block
end
end
end | ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/lib/fruity/group.rb | lib/fruity/group.rb | module Fruity
# A group of callable objects
#
class Group
attr_reader :elements
attr_reader :options
# Pass either a list of callable objects, a Hash of names and callable objects
# or an Array of methods names with the option :on specifying which object to call
# them on (or else the methods are assumed to be global, see the README)
# Another possibility is to use a block; if it accepts an argument,
#
def initialize(*args, &block)
@options = DEFAULT_OPTIONS.dup
@elements = {}
@counter = 0
compare(*args, &block)
end
# Adds things to compare. See +new+ for details on interface
#
def compare(*args, &block)
if args.last.is_a?(Hash) && (args.last.keys - OPTIONS).empty?
@options.merge!(args.pop)
end
case args.first
when Hash
raise ArgumentError, "Expected only one hash of {value => executable}, got #{args.size-1} extra arguments" unless args.size == 1
raise ArgumentError, "Expected values to be executable" unless args.first.values.all?{|v| v.respond_to?(:call)}
compare_hash(args.first)
when Symbol, String
compare_methods(*args)
else
compare_lambdas(*args)
end
compare_block(block) if block
end
# Returns the maximal sufficient_magnification for all elements
# See Util.sufficient_magnification
#
def sufficient_magnification
elements.map{|name, exec| Util.sufficient_magnification(exec, options) }.max
end
# Returns the maximal sufficient_magnification for all elements
# and the approximate delay taken for the whole group
# See Util.sufficient_magnification
#
def sufficient_magnification_and_delay
mags_and_delays = elements.map{|name, exec| Util.sufficient_magnification_and_delay(exec, options) }
mag = mags_and_delays.map(&:first).max
delay = mags_and_delays.map{|m, d| d * mag / m}.inject(:+)
[mag, delay]
end
def size
elements.size
end
def run(options = {})
Runner.new(self).run(options)
end
private
def compare_hash(h)
elements.merge!(h)
end
def compare_methods(*args)
on = @options[:on]
args.each do |m|
elements[m] = on.method(m)
end
end
def compare_lambdas(*lambdas)
lambdas.flat_map{|o| Array(o)}
lambdas.each do |name, callable|
name, callable = generate_name(name), name unless callable
raise "Excepted a callable object, got #{callable}" unless callable.respond_to?(:call)
elements[name] = callable
end
end
def compare_block(block)
collect = NamedBlockCollector.new(@elements)
if block.arity == 0
@options[:self] = block.binding.eval("self")
collect.instance_eval(&block)
else
block.call(collect)
end
end
def generate_name(callable)
"Code #{@counter += 1}"
end
end
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/lib/fruity/base.rb | lib/fruity/base.rb | require_relative "baseline"
require_relative "util"
require_relative "runner"
require_relative "comparison_run"
require_relative "group"
require_relative "named_block_collector"
Fruity::GLOBAL_SCOPE = self
module Fruity
DEFAULT_OPTIONS = {
:on => GLOBAL_SCOPE,
:samples => 20,
:disable_gc => false,
:filter => [0, 0.2], # Proportion of samples to discard [lower_end, upper_end]
:baseline => :single, # Either :none, :single or :split
}
OTHER_OPTIONS = [
:magnify,
:args,
:self,
:verbose,
]
OPTIONS = DEFAULT_OPTIONS.keys + OTHER_OPTIONS
def report(*stuff, &block)
Fruity::Runner.new(Fruity::Group.new(*stuff, &block)).run(&:feedback)
end
def compare(*stuff, &block)
puts report(*stuff, &block)
end
def study(*stuff, &block)
run = Fruity::Runner.new(Fruity::Group.new(*stuff, &block)).run(:baseline => :single, &:feedback)
path = run.export
`open "#{path}"`
run
end
extend self
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/lib/fruity/runner.rb | lib/fruity/runner.rb | module Fruity
class Runner < Struct.new(:group)
attr_reader :options, :delay, :timings, :baselines
def run(options = {})
prepare(options)
yield self if block_given?
sample
end
def feedback
mess = "Running each test " << (options[:magnify] == 1 ? "once." : "#{options[:magnify]} times.")
if d = delay
if d > 60
d = (d / 60).round
unit = "minute"
end
mess << " Test will take about #{d.ceil} #{unit || 'second'}#{d > 1 ? 's' : ''}."
end
puts mess
end
private
def prepare(opt)
@options = group.options.merge(opt)
unless options[:magnify]
options[:magnify], @delay = group.sufficient_magnification_and_delay
@delay *= options.fetch(:samples)
end
end
def sample
send(:"sample_baseline_#{options.fetch(:baseline)}")
ComparisonRun.new(group, timings, baselines)
end
def sample_baseline_split
baselines = group.elements.map{|name, exec| Baseline[exec]}
exec_and_baselines = group.elements.values.zip(baselines)
@baselines, @timings = options.fetch(:samples).times.map do
exec_and_baselines.flat_map do |exec, baseline|
[
Util.real_time(baseline, options),
Util.real_time(exec, options),
]
end
end.transpose.each_slice(2).to_a.transpose
end
def sample_baseline_single
baseline = Baseline[group.elements.first.last]
@baselines = []
@timings = options.fetch(:samples).times.map do
baselines << Util.real_time(baseline, options)
group.elements.map do |name, exec|
Util.real_time(exec, options)
end
end.transpose
end
def sample_baseline_none
@baselines = nil
@timings = options.fetch(:samples).times.map do
group.elements.map do |name, exec|
Util.real_time(exec, options)
end
end.transpose
end
end
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/lib/fruity/baseline.rb | lib/fruity/baseline.rb | module Fruity
# Utility module for building
# baseline equivalents for callables.
#
module Baseline
extend self
# Returns the baseline for the given callable object
# The signature (number of arguments) and type (proc, ...)
# will be copied as much as possible.
#
def [](exec)
kind = callable_kind(exec)
signature = callable_signature(exec)
NOOPs[kind][signature] ||= build_baseline(kind, signature)
end
NOOPs = Hash.new{|h, k| h[k] = {}}
def callable_kind(exec)
if exec.is_a?(Method)
exec.source_location ? :method : :builtin_method
elsif exec.lambda?
:lambda
else
:proc
end
end
def callable_signature(exec)
if exec.respond_to?(:parameters)
exec.parameters.map(&:first)
else
# Ruby 1.8 didn't have parameters, so rely on arity
opt = exec.arity < 0
req = opt ? -1-exec.arity : exec.arity
signature = [:req] * req
signature << :rest if opt
signature
end
end
PARAM_MAP = {
:req => "%{name}",
:opt => "%{name} = nil",
:rest => "*%{name}",
:block => "&%{name}",
}
def arg_list(signature)
signature.map.with_index{|kind, i| PARAM_MAP[kind] % {:name => "p#{i}"}}.join(",")
end
def build_baseline(kind, signature)
args = "|#{arg_list(signature)}|"
case kind
when :lambda, :proc
eval("#{kind}{#{args}}")
when :builtin_method
case signature
when []
nil.method(:nil?)
when [:req]
nil.method(:==)
else
Array.method(:[])
end
when :method
@method_counter ||= 0
@method_counter += 1
name = "baseline_#{@method_counter}"
eval("define_method(:#{name}){#{args}}")
method(name)
end
end
end
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/lib/fruity/comparison_run.rb | lib/fruity/comparison_run.rb | # encoding: utf-8
module Fruity
class ComparisonRun < Struct.new(:group, :timings, :baselines)
attr_reader :stats
# +timings+ must be an array of size `group.size` of arrays of delays
# or of arrays of [delay, baseline]
#
def initialize(group, timings, baselines)
raise ArgumentError, "Expected timings to be an array with #{group.size} elements (was #{timings.size})" unless timings.size == group.size
super
filter = group.options.fetch(:filter)
baseline = Util.filter(baselines, *filter) if baseline_type == :single
@stats = timings.map.with_index do |series, i|
case baseline_type
when :split
Util.difference(Util.filter(series, *filter), Util.filter(baselines.fetch(i), *filter))
when :single
Util.difference(Util.filter(series, *filter), baseline)
when :none
Util.stats(series)
end
end.freeze
end
def to_s
order = (0...group.size).sort_by{|i| @stats[i][:mean] }
results = group.elements.map{|n, exec| Util.result_of(exec, group.options) }
order.each_cons(2).map do |i, j|
cmp = comparison(i, j)
s = if cmp[:factor] == 1
"%{cur} is similar to %{vs}%{different}"
else
"%{cur} is faster than %{vs} by %{ratio}%{different}"
end
s % {
:cur => group.elements.keys[i],
:vs => group.elements.keys[j],
:ratio => format_comparison(cmp),
:different => results[i] == results[j] ? "" : " (results differ: #{results[i]} vs #{results[j]})"
}
end.join("\n")
end
def export(fn = (require "tmpdir"; "#{Dir.tmpdir}/export.csv"))
require "csv"
CSV.open(fn, "wb") do |csv|
head = group.elements.keys
case baseline_type
when :split
head = head.flat_map{|h| [h, "#{head} bl"]}
data = timings.zip(baselines).flatten(1).transpose
when :single
data = (timings + [baselines]).transpose
head << "baseline"
else
data = timings.transpose
end
csv << head
data.each{|vals| csv << vals}
end
fn
end
def size
timings.first.size
end
def factor(cur = 0, vs = 1)
comparison(cur, vs)[:factor]
end
def factor_range(cur = 0, vs =1)
comparison(cur, vs)[:min]..comparison(cur, vs)[:max]
end
def comparison(cur = 0, vs = 1)
Util.compare_stats(@stats[cur], @stats[vs])
end
def format_comparison(cmp)
ratio = cmp[:factor]
prec = cmp[:precision]
if ratio.abs > 1.8
"#{ratio}x ± #{prec}"
else
"#{(ratio - 1)*100}% ± #{prec*100}%"
end
end
def baseline_type
if baselines.nil?
:none
elsif baselines.first.is_a?(Array)
:split
else
:single
end
end
end
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
marcandre/fruity | https://github.com/marcandre/fruity/blob/d270f6a477861444391ffce86dd20e406fe5f443/lib/fruity/util.rb | lib/fruity/util.rb | require 'benchmark'
module Fruity
# Utility module doing most of the maths
#
module Util
extend self
PROPER_TIME_RELATIVE_ERROR = 0.001
MEASUREMENTS_BY_REALTIME = 2
MEASUREMENTS_BY_PROPER_TIME = 2 * MEASUREMENTS_BY_REALTIME
# Measures the smallest obtainable delta of two time measurements
#
def clock_precision
@clock_precision ||= 10.times.map do
t = Time.now
delta = Time.now - t
while delta == 0
delta = Time.now - t
end
delta
end.min
end
APPROX_POWER = 5
# Calculates the number +n+ that needs to be passed
# to +real_time+ to get a result that is precise
# to within +PROPER_TIME_RELATIVE_ERROR+ when compared
# to the baseline.
#
# For example, ->{ sleep(1) } needs only to be run once to get
# a measurement that will not be affected by the inherent imprecision
# of the time measurement (or of the inner loop), but ->{ 2 + 2 } needs to be called
# a huge number of times so that the returned time measurement is not
# due in big part to the imprecision of the measurement itself
# or the inner loop itself.
#
def sufficient_magnification(exec, options = {})
mag, delay = sufficient_magnification_and_delay(exec, options)
mag
end
BASELINE_THRESHOLD = 1.02 # Ratio between two identical baselines is typically < 1.02, while {2+2} compared to baseline is typically > 1.02
def sufficient_magnification_and_delay(exec, options = {})
power = 0
min_desired_delta = clock_precision * MEASUREMENTS_BY_PROPER_TIME / PROPER_TIME_RELATIVE_ERROR
# First, make a gross approximation with a single sample and no baseline
min_approx_delay = min_desired_delta / (1 << APPROX_POWER)
while (delay = real_time(exec, options.merge(:magnify => 1 << power))) < min_approx_delay
power += [Math.log(min_approx_delay.div(delay + clock_precision), 2), 1].max.floor
end
# Then take a couple of samples, along with a baseline
power += 1 unless delay > 2 * min_approx_delay
group = Group.new(exec, Baseline[exec],
options.merge(
:baseline => :none,
:samples => 5,
:filter => [0, 0.25],
:magnify => 1 << power
))
stats = group.run.stats
if stats[0][:mean] / stats[1][:mean] < 2
# Quite close to baseline, which means we need to be more discriminant
power += APPROX_POWER
stats = group.run(:samples => 40, :magnify => 1 << power).stats
if stats[0][:mean] / stats[1][:mean] < BASELINE_THRESHOLD
raise "Given callable can not be reasonably distinguished from an empty block"
end
end
delta = stats[0][:mean] - stats[1][:mean]
addl_power = [Math.log(min_desired_delta.div(delta), 2), 0].max.floor
[
1 << (power + addl_power),
stats[0][:mean] * (1 << addl_power),
]
end
# The proper time is the real time taken by calling +exec+
# number of times given by +options[:magnify]+ minus
# the real time for calling an empty executable instead.
#
# If +options[:magnify]+ is not given, it will be calculated to be meaningful.
#
def proper_time(exec, options = {})
unless options.has_key?(:magnify)
options = {:magnify => sufficient_magnification(exec, options)}.merge(options)
end
real_time(exec, options) - real_time(Baseline[exec], options)
end
# Returns the real time taken by calling +exec+
# number of times given by +options[:magnify]+
#
def real_time(exec, options = {})
GC.start
GC.disable if options[:disable_gc]
n = options.fetch(:magnify)
if options.has_key?(:self)
new_self = options[:self]
if args = options[:args] and args.size > 0
Benchmark.realtime{ n.times{ new_self.instance_exec(*args, &exec) } }
else
Benchmark.realtime{ n.times{ new_self.instance_eval(&exec) } }
end
else
if args = options[:args] and args.size > 0
Benchmark.realtime{ n.times{ exec.call(*args) } }
else
Benchmark.realtime{ n.times{ exec.call } }
end
end
ensure
GC.enable
end
# Returns the result of calling +exec+
#
def result_of(exec, options = {})
args = (options[:args] || [])
if options.has_key?(:self)
options[:self].instance_exec(*args, &exec)
else
exec.call(*args)
end
end
# Returns the inherent precision of +proper_time+
#
def proper_time_precision
MEASUREMENTS_BY_PROPER_TIME * clock_precision
end
# Calculates stats on some values: {:min, :max, :mean, :sample_std_dev }
#
def stats(values)
sum = values.inject(0, :+)
# See http://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods
q = mean = 0
values.each_with_index do |x, k|
prev_mean = mean
mean += (x - prev_mean) / (k + 1)
q += (x - mean) * (x - prev_mean)
end
sample_std_dev = Math.sqrt( q / (values.size-1) )
min, max = values.minmax
{
:min => min,
:max => max,
:mean => mean,
:sample_std_dev => sample_std_dev
}
end
# Calculates the stats of the difference of +values+ and +baseline+
# (which can be stats or timings)
#
def difference(values, baseline)
values, baseline = [values, baseline].map{|x| x.is_a?(Hash) ? x : stats(x)}
{
:min => values[:min] - baseline[:max],
:max => values[:max] - baseline[:min],
:mean => values[:mean] - baseline[:mean],
:sample_std_dev => Math.sqrt(values[:sample_std_dev] ** 2 + values[:sample_std_dev] ** 2),
# See http://stats.stackexchange.com/questions/6096/correct-way-to-calibrate-means
}
end
# Given two stats +cur+ and +vs+, returns a hash with
# the ratio between the two, the precision, etc.
#
def compare_stats(cur, vs)
err = (vs[:sample_std_dev] +
cur[:sample_std_dev] * vs[:mean] / cur[:mean]
) / cur[:mean]
rounding = err > 0 ? -Math.log(err, 10) : 666
mean = vs[:mean] / cur[:mean]
{
:mean => mean,
:factor => (mean).round(rounding),
:max => (vs[:mean] + vs[:sample_std_dev]) / (cur[:mean] - cur[:sample_std_dev]),
:min => (vs[:mean] - vs[:sample_std_dev]) / (cur[:mean] + cur[:sample_std_dev]),
:rounding => rounding,
:precision => 10.0 **(-rounding.round),
}
end
def filter(series, remove_min_ratio, remove_max_ratio = remove_min_ratio)
series.sort![
(remove_min_ratio * series.size).floor ...
((1-remove_max_ratio) * series.size).ceil
]
end
end
end
| ruby | MIT | d270f6a477861444391ffce86dd20e406fe5f443 | 2026-01-04T17:44:46.522329Z | false |
soveran/syro | https://github.com/soveran/syro/blob/8dc597c19c8aa1446e21a70cfed7fd2890a7176a/test/helper.rb | test/helper.rb | require_relative "../lib/syro"
require "rack/test"
class Driver
include Rack::Test::Methods
def initialize(app)
@app = app
end
def app
@app
end
end
| ruby | MIT | 8dc597c19c8aa1446e21a70cfed7fd2890a7176a | 2026-01-04T17:44:51.789656Z | false |
soveran/syro | https://github.com/soveran/syro/blob/8dc597c19c8aa1446e21a70cfed7fd2890a7176a/test/all.rb | test/all.rb | require "json"
class RackApp
def call(env)
[200, {"Content-Type" => "text/html"}, ["GET /rack"]]
end
end
class MarkdownDeck < Syro::Deck
def markdown(str)
res[Rack::CONTENT_TYPE] = "text/markdown"
res.write(str)
end
end
class DefaultHeaders < Syro::Deck
def default_headers
{ Rack::CONTENT_TYPE => "text/html" }
end
end
class CustomRequestAndResponse < Syro::Deck
class JSONRequest < Rack::Request
def params
JSON.parse(body.read)
end
end
class JSONResponse < Syro::Response
def write(s)
super(JSON.generate(s))
end
end
def request_class
JSONRequest
end
def response_class
JSONResponse
end
end
markdown = Syro.new(MarkdownDeck) do
get do
markdown("GET /markdown")
end
end
default_headers = Syro.new(DefaultHeaders) do end
json = Syro.new(CustomRequestAndResponse) do
root do
params = req.params
res.write(params)
end
end
admin = Syro.new do
get do
res.write("GET /admin")
end
end
platforms = Syro.new do
@id = inbox.fetch(:id)
get do
res.write "GET /platforms/#{@id}"
end
end
comments = Syro.new do
get do
res.write sprintf("GET %s/%s/comments",
inbox[:path],
inbox[:post_id])
end
end
handlers = Syro.new do
on "without_handler" do
# Not found
end
handle(404) do
res.text "Not found!"
end
on "with_handler" do
# Not found
end
on "with_local_handler" do
handle(404) do
res.text "Also not found!"
end
end
end
path_info = Syro.new do
on "foo" do
get do
res.text req.path
end
end
get do
res.text req.path
end
end
script_name = Syro.new do
on "path" do
run(path_info)
end
end
exception = Syro.new do
get { res.text(this_method_does_not_exist) }
end
app = Syro.new do
get do
res.write "GET /"
end
post do
on req.POST["user"] != nil do
res.write "POST / (user)"
end
on true do
res.write "POST / (none)"
end
end
on "foo" do
on "bar" do
on "baz" do
res.write("error")
end
get do
res.write("GET /foo/bar")
end
put do
res.write("PUT /foo/bar")
end
head do
res.write("HEAD /foo/bar")
end
post do
res.write("POST /foo/bar")
end
patch do
res.write("PATCH /foo/bar")
end
delete do
res.write("DELETE /foo/bar")
end
options do
res.write("OPTIONS /foo/bar")
end
end
end
on "bar/baz" do
get do
res.write("GET /bar/baz")
end
end
on "admin" do
run(admin)
end
on "platforms" do
run(platforms, id: 42)
end
on "rack" do
run(RackApp.new)
end
on "users" do
on :id do
res.write(sprintf("GET /users/%s", inbox[:id]))
end
end
on "posts" do
@path = path.prev
on :post_id do
on "comments" do
run(comments, inbox.merge(path: @path))
end
end
end
on "one" do
@one = "1"
get do
res.write(@one)
end
end
on "two" do
get do
res.write(@one)
end
post do
res.redirect("/one")
end
end
on "markdown" do
run(markdown)
end
on "headers" do
run(default_headers)
end
on "custom" do
run(json)
end
on "handlers" do
run(handlers)
end
on "private" do
res.status = 401
res.write("Unauthorized")
end
on "write" do
res.write "nil!"
end
on "text" do
res.text "plain!"
end
on "html" do
res.html "html!"
end
on "json" do
res.json "json!"
end
on "script" do
run(script_name)
end
on "exception" do
run(exception)
end
end
setup do
Driver.new(app)
end
test "path + verb" do |f|
f.get("/foo/bar")
assert_equal 200, f.last_response.status
assert_equal "GET /foo/bar", f.last_response.body
f.get("/bar/baz")
assert_equal 404, f.last_response.status
assert_equal "", f.last_response.body
f.put("/foo/bar")
assert_equal 200, f.last_response.status
assert_equal "PUT /foo/bar", f.last_response.body
f.head("/foo/bar")
assert_equal 200, f.last_response.status
assert_equal "HEAD /foo/bar", f.last_response.body
f.post("/foo/bar")
assert_equal 200, f.last_response.status
assert_equal "POST /foo/bar", f.last_response.body
f.patch("/foo/bar")
assert_equal 200, f.last_response.status
assert_equal "PATCH /foo/bar", f.last_response.body
f.delete("/foo/bar")
assert_equal 200, f.last_response.status
assert_equal "DELETE /foo/bar", f.last_response.body
f.options("/foo/bar")
assert_equal 200, f.last_response.status
assert_equal "OPTIONS /foo/bar", f.last_response.body
end
test "verbs match only on root" do |f|
f.get("/bar/baz/foo")
assert_equal "", f.last_response.body
assert_equal 404, f.last_response.status
end
test "mounted app" do |f|
f.get("/admin")
assert_equal "GET /admin", f.last_response.body
assert_equal 200, f.last_response.status
end
test "mounted app + inbox" do |f|
f.get("/platforms")
assert_equal "GET /platforms/42", f.last_response.body
assert_equal 200, f.last_response.status
end
test "run rack app" do |f|
f.get("/rack")
assert_equal "GET /rack", f.last_response.body
assert_equal 200, f.last_response.status
end
test "root" do |f|
f.get("/")
assert_equal "GET /", f.last_response.body
assert_equal 200, f.last_response.status
end
test "captures" do |f|
f.get("/users/42")
assert_equal "GET /users/42", f.last_response.body
# As the verb was not mached, the status is 404.
assert_equal 404, f.last_response.status
end
test "post values" do |f|
f.post("/", "user" => { "username" => "foo" })
assert_equal "POST / (user)", f.last_response.body
assert_equal 200, f.last_response.status
f.post("/")
assert_equal "POST / (none)", f.last_response.body
assert_equal 200, f.last_response.status
end
test "inherited inbox" do |f|
f.get("/posts/42/comments")
assert_equal "GET /posts/42/comments", f.last_response.body
assert_equal 200, f.last_response.status
end
test "leaks" do |f|
f.get("/one")
assert_equal "1", f.last_response.body
assert_equal 200, f.last_response.status
f.get("/two")
assert_equal "", f.last_response.body
assert_equal 200, f.last_response.status
end
test "redirect" do |f|
f.post("/two")
assert_equal 302, f.last_response.status
f.follow_redirect!
assert_equal "1", f.last_response.body
assert_equal 200, f.last_response.status
end
test "custom deck" do |f|
f.get("/markdown")
assert_equal "GET /markdown", f.last_response.body
assert_equal "text/markdown", f.last_response.headers["Content-Type"]
assert_equal 200, f.last_response.status
end
test "default headers" do |f|
f.get("/headers")
assert_equal "text/html", f.last_response.headers["Content-Type"]
end
test "custom request and response class" do |f|
params = JSON.generate(foo: "foo")
f.post("/custom", params)
assert_equal params, f.last_response.body
end
test "don't set content type by default" do |f|
f.get("/private")
assert_equal 401, f.last_response.status
assert_equal "Unauthorized", f.last_response.body
assert_equal nil, f.last_response.headers["Content-Type"]
end
test "content type" do |f|
f.get("/write")
assert_equal nil, f.last_response.headers["Content-Type"]
f.get("/text")
assert_equal "text/plain", f.last_response.headers["Content-Type"]
f.get("/html")
assert_equal "text/html", f.last_response.headers["Content-Type"]
f.get("/json")
assert_equal "application/json", f.last_response.headers["Content-Type"]
end
test "status code handling" do |f|
f.get("/handlers")
assert_equal 404, f.last_response.status
assert_equal "text/plain", f.last_response.headers["Content-Type"]
assert_equal "Not found!", f.last_response.body
f.get("/handlers/without_handler")
assert_equal 404, f.last_response.status
assert_equal nil, f.last_response.headers["Content-Type"]
assert_equal "", f.last_response.body
f.get("/handlers/with_handler")
assert_equal 404, f.last_response.status
assert_equal "text/plain", f.last_response.headers["Content-Type"]
assert_equal "Not found!", f.last_response.body
f.get("/handlers/with_local_handler")
assert_equal 404, f.last_response.status
assert_equal "text/plain", f.last_response.headers["Content-Type"]
assert_equal "Also not found!", f.last_response.body
end
test "script name and path info" do |f|
f.get("/script/path")
assert_equal 200, f.last_response.status
assert_equal "/script/path", f.last_response.body
end
test "deck exceptions reference a named class" do |f|
f.get("/exception")
rescue NameError => exception
ensure
assert exception.to_s.include?("Syro::Deck")
end
| ruby | MIT | 8dc597c19c8aa1446e21a70cfed7fd2890a7176a | 2026-01-04T17:44:51.789656Z | false |
soveran/syro | https://github.com/soveran/syro/blob/8dc597c19c8aa1446e21a70cfed7fd2890a7176a/lib/syro.rb | lib/syro.rb | # encoding: UTF-8
#
# Copyright (c) 2015 Michel Martens
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require "rack"
require "seg"
class Syro
INBOX = "syro.inbox".freeze # :nodoc:
class Response
LOCATION = "Location".freeze # :nodoc:
module ContentType
HTML = "text/html".freeze # :nodoc:
TEXT = "text/plain".freeze # :nodoc:
JSON = "application/json".freeze # :nodoc:
end
# The status of the response.
#
# res.status = 200
# res.status # => 200
#
attr_accessor :status
# Returns the body of the response.
#
# res.body
# # => []
#
# res.write("there is")
# res.write("no try")
#
# res.body
# # => ["there is", "no try"]
#
attr_reader :body
# Returns a hash with the response headers.
#
# res.headers
# # => { "Content-Type" => "text/html", "Content-Length" => "42" }
#
attr_reader :headers
def initialize(headers = {})
@status = 404
@headers = headers
@body = []
@length = 0
end
# Returns the response header corresponding to `key`.
#
# res["Content-Type"] # => "text/html"
# res["Content-Length"] # => "42"
#
def [](key)
@headers[key]
end
# Sets the given `value` with the header corresponding to `key`.
#
# res["Content-Type"] = "application/json"
# res["Content-Type"] # => "application/json"
#
def []=(key, value)
@headers[key] = value
end
# Appends `str` to `body` and updates the `Content-Length` header.
#
# res.body # => []
#
# res.write("foo")
# res.write("bar")
#
# res.body
# # => ["foo", "bar"]
#
# res["Content-Length"]
# # => 6
#
def write(str)
s = str.to_s
@length += s.bytesize
@headers[Rack::CONTENT_LENGTH] = @length.to_s
@body << s
end
# Write response body as text/plain
def text(str)
@headers[Rack::CONTENT_TYPE] = ContentType::TEXT
write(str)
end
# Write response body as text/html
def html(str)
@headers[Rack::CONTENT_TYPE] = ContentType::HTML
write(str)
end
# Write response body as application/json
def json(str)
@headers[Rack::CONTENT_TYPE] = ContentType::JSON
write(str)
end
# Sets the `Location` header to `path` and updates the status to
# `status`. By default, `status` is `302`.
#
# res.redirect("/path")
#
# res["Location"] # => "/path"
# res.status # => 302
#
# res.redirect("http://syro.ru", 303)
#
# res["Location"] # => "http://syro.ru"
# res.status # => 303
#
def redirect(path, status = 302)
@headers[LOCATION] = path
@status = status
end
# Returns an array with three elements: the status, headers and
# body. If the status is not set, the status is set to 404. If
# a match is found for both path and request method, the status
# is changed to 200.
#
# res.status = 200
# res.finish
# # => [200, {}, []]
#
# res.status = nil
# res.finish
# # => [404, {}, []]
#
# res.status = nil
# res.write("syro")
# res.finish
# # => [200, { "Content-Type" => "text/html" }, ["syro"]]
#
def finish
[@status, @headers, @body]
end
# Sets a cookie into the response.
#
# res.set_cookie("foo", "bar")
# res["Set-Cookie"] # => "foo=bar"
#
# res.set_cookie("foo2", "bar2")
# res["Set-Cookie"] # => "foo=bar\nfoo2=bar2"
#
# res.set_cookie("bar", {
# domain: ".example.com",
# path: "/",
# # max_age: 0,
# # expires: Time.now + 10_000,
# secure: true,
# httponly: true,
# value: "bar"
# })
#
# res["Set-Cookie"].split("\n").last
# # => "bar=bar; domain=.example.com; path=/; secure; HttpOnly
#
# **NOTE:** This method doesn't sign and/or encrypt the value of the cookie.
#
def set_cookie(key, value)
Rack::Utils.set_cookie_header!(@headers, key, value)
end
# Deletes given cookie.
#
# res.set_cookie("foo", "bar")
# res["Set-Cookie"]
# # => "foo=bar"
#
# res.delete_cookie("foo")
# res["Set-Cookie"]
# # => "foo=; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
#
def delete_cookie(key, value = {})
Rack::Utils.delete_cookie_header!(@headers, key, value)
end
end
class Deck
# Attaches the supplied block to a subclass of Deck as #dispatch!
# Returns the subclassed Deck.
def self.implement(&code)
Class.new(self) do
define_method(:dispatch!, code)
private :dispatch!
# Instead of calling inspect on this anonymous class,
# defer to the superclass which is likely Syro::Deck.
define_method(:inspect) do
self.class.superclass.inspect
end
end
end
module API
def env
@syro_env
end
# Returns the incoming request object. This object is an
# instance of Rack::Request.
#
# req.post? # => true
# req.params # => { "username" => "bob", "password" => "secret" }
# req[:username] # => "bob"
#
def req
@syro_req
end
# Returns the current response object. This object is an
# instance of Syro::Response.
#
# res.status = 200
# res["Content-Type"] = "text/html"
# res.write("<h1>Welcome back!</h1>")
#
def res
@syro_res
end
def path
@syro_path
end
def inbox
@syro_inbox
end
def default_headers
{}
end
def request_class
Rack::Request
end
def response_class
Syro::Response
end
def call(env, inbox)
@syro_env = env
@syro_req = request_class.new(env)
@syro_res = response_class.new(default_headers)
@syro_path = Seg.new(env.fetch(Rack::PATH_INFO))
@syro_inbox = inbox
catch(:halt) do
dispatch!
finish!
end
end
def run(app, inbox = {})
path, script = env[Rack::PATH_INFO], env[Rack::SCRIPT_NAME]
env[Rack::PATH_INFO] = @syro_path.curr
env[Rack::SCRIPT_NAME] = script.to_s + @syro_path.prev
env[Syro::INBOX] = inbox
halt(app.call(env))
ensure
env[Rack::PATH_INFO], env[Rack::SCRIPT_NAME] = path, script
end
# Immediately stops the request and returns `response`
# as per Rack's specification.
#
# halt([200, { "Content-Type" => "text/html" }, ["hello"]])
# halt([res.status, res.headers, res.body])
# halt(res.finish)
#
def halt(response)
throw(:halt, response)
end
# Install a handler for a given status code. Once a handler is
# installed, it will be called by Syro before halting the
# request.
#
# handle 404 do
# res.text "Not found!"
# end
#
# If a new handler is installed for the same status code, the
# previous handler is overwritten. A handler is valid in the
# current scope and in all its nested branches. Blocks that end
# before the handler is installed are not affected.
#
# For example:
#
# on "foo" do
# # Not found
# end
#
# handle 404 do
# res.text "Not found!"
# end
#
# on "bar" do
# # Not found
# end
#
# on "baz" do
# # Not found
#
# handle 404 do
# res.text "Couldn't find baz"
# end
# end
#
# A request to "/foo" will return a 404, because the request
# method was not matched. But as the `on "foo"` block ends
# before the handler is installed, the result will be a blank
# screen. On the other hand, a request to "/bar" will return a
# 404 with the plain text "Not found!".
#
# Finally, a request to "/baz" will return a 404 with the plain text
# "Couldn't find baz", because by the time the `on "baz"` block ends
# a new handler is installed, and thus the previous one is overwritten.
#
# Any status code can be handled this way, even status `200`.
# In that case the handler will behave as a filter to be run
# after each successful request.
#
def handle(status, &block)
inbox[status] = block
end
def finish!
inbox[res.status]&.call
halt(res.finish)
end
def consume(arg)
@syro_path.consume(arg)
end
def capture(arg)
@syro_path.capture(arg, inbox)
end
def root?
@syro_path.root?
end
def match(arg)
case arg
when String then consume(arg)
when Symbol then capture(arg)
when true then true
else false
end
end
def default
yield; finish!
end
def on(arg)
default { yield } if match(arg)
end
def root
default { yield } if root?
end
def get
root { res.status = 200; yield } if req.get?
end
def put
root { res.status = 200; yield } if req.put?
end
def head
root { res.status = 200; yield } if req.head?
end
def post
root { res.status = 200; yield } if req.post?
end
def patch
root { res.status = 200; yield } if req.patch?
end
def delete
root { res.status = 200; yield } if req.delete?
end
def options
root { res.status = 200; yield } if req.options?
end
end
include API
end
def initialize(deck = Deck, &code)
@deck = deck.implement(&code)
end
def call(env, inbox = env.fetch(Syro::INBOX, {}))
@deck.new.call(env, inbox)
end
end
| ruby | MIT | 8dc597c19c8aa1446e21a70cfed7fd2890a7176a | 2026-01-04T17:44:51.789656Z | false |
xrd/ng-rails-csrf | https://github.com/xrd/ng-rails-csrf/blob/3193e99c7db5822f3cb94a8b11cc68bc4792e966/lib/ng-rails-csrf.rb | lib/ng-rails-csrf.rb | require "ng-rails-csrf/version"
module Ng
module Rails
module Csrf
class Engine < ::Rails::Engine
end
end
end
end
| ruby | MIT | 3193e99c7db5822f3cb94a8b11cc68bc4792e966 | 2026-01-04T17:44:51.698774Z | false |
xrd/ng-rails-csrf | https://github.com/xrd/ng-rails-csrf/blob/3193e99c7db5822f3cb94a8b11cc68bc4792e966/lib/ng-rails-csrf/version.rb | lib/ng-rails-csrf/version.rb | module Ng
module Rails
module Csrf
VERSION = "0.1.0"
end
end
end
| ruby | MIT | 3193e99c7db5822f3cb94a8b11cc68bc4792e966 | 2026-01-04T17:44:51.698774Z | false |
ankane/trend-ruby | https://github.com/ankane/trend-ruby/blob/a8c01d4327231db4044f672b18a0f73dbb7c6980/test/trend_test.rb | test/trend_test.rb | require_relative "test_helper"
class TrendTest < Minitest::Test
def test_anomalies
series = {}
date = Date.parse("2018-04-01")
28.times do
series[date] = rand(100)
date += 1
end
series[date - 13] = nil # test nil
series[date - 8] = 999
assert_equal [Date.parse("2018-04-21")], Trend.anomalies(series)
end
def test_forecast
series = {}
date = Date.parse("2018-04-01")
28.times do
series[date] = date.wday
date += 1
end
series.delete(date - 13) # test missing
forecast = Trend.forecast(series, count: 7)
assert_equal [0, 1, 2, 3, 4, 5, 6], forecast.values
end
def test_correlation
series = {}
date = Date.parse("2018-04-01")
28.times do
series[date] = date.wday
date += 1
end
series2 = series.dup
series2[date - 8] = 10
correlation = Trend.correlation(series, series2)
assert_equal 0.9522, correlation
end
def test_correlation_exact
series = {}
date = Date.parse("2018-04-01")
28.times do
series[date] = date.wday
date += 1
end
# test positive
correlation = Trend.correlation(series, series)
assert_equal 1, correlation
# test negative
correlation = Trend.correlation(series, Hash[series.map { |k, v| [k, -v] }])
assert_equal(-1, correlation)
end
end
| ruby | MIT | a8c01d4327231db4044f672b18a0f73dbb7c6980 | 2026-01-04T17:44:55.176641Z | false |
ankane/trend-ruby | https://github.com/ankane/trend-ruby/blob/a8c01d4327231db4044f672b18a0f73dbb7c6980/test/test_helper.rb | test/test_helper.rb | require "bundler/setup"
Bundler.require(:default)
require "minitest/autorun"
Trend.url ||= "http://localhost:8000"
| ruby | MIT | a8c01d4327231db4044f672b18a0f73dbb7c6980 | 2026-01-04T17:44:55.176641Z | false |
ankane/trend-ruby | https://github.com/ankane/trend-ruby/blob/a8c01d4327231db4044f672b18a0f73dbb7c6980/lib/trend.rb | lib/trend.rb | # stdlib
require "date"
require "json"
require "net/http"
require "time"
# modules
require_relative "trend/client"
require_relative "trend/version"
module Trend
class Error < StandardError; end
def self.anomalies(*args)
client.anomalies(*args)
end
def self.forecast(*args)
client.forecast(*args)
end
def self.correlation(*args)
client.correlation(*args)
end
def self.url
@url ||= ENV["TREND_URL"]
end
def self.url=(url)
@url = url
@client = nil
end
def self.api_key
@api_key ||= ENV["TREND_API_KEY"]
end
def self.api_key=(api_key)
@api_key = api_key
@client = nil
end
# private
def self.client
@client ||= Client.new
end
end
| ruby | MIT | a8c01d4327231db4044f672b18a0f73dbb7c6980 | 2026-01-04T17:44:55.176641Z | false |
ankane/trend-ruby | https://github.com/ankane/trend-ruby/blob/a8c01d4327231db4044f672b18a0f73dbb7c6980/lib/trend/version.rb | lib/trend/version.rb | module Trend
VERSION = "0.3.0"
end
| ruby | MIT | a8c01d4327231db4044f672b18a0f73dbb7c6980 | 2026-01-04T17:44:55.176641Z | false |
ankane/trend-ruby | https://github.com/ankane/trend-ruby/blob/a8c01d4327231db4044f672b18a0f73dbb7c6980/lib/trend/client.rb | lib/trend/client.rb | require "trend/version"
module Trend
class Client
HEADERS = {
"Content-Type" => "application/json",
"Accept" => "application/json",
"User-Agent" => "trend-ruby/#{Trend::VERSION}"
}
def initialize(url: nil, api_key: nil, timeout: 30)
@api_key = api_key || Trend.api_key
url ||= Trend.url
if !url
raise ArgumentError, "Trend url not set"
end
@uri = URI.parse(url)
@http = Net::HTTP.new(@uri.host, @uri.port)
@http.use_ssl = true if @uri.scheme == "https"
@http.open_timeout = timeout
@http.read_timeout = timeout
end
def anomalies(series, params = {})
resp = make_request("anomalies", series, params)
resp["anomalies"].map { |v| parse_time(v) }
end
def forecast(series, params = {})
resp = make_request("forecast", series, params)
Hash[resp["forecast"].map { |k, v| [parse_time(k), v] }]
end
def correlation(series, series2, params = {})
resp = make_request("correlation", series, params.merge(series2: series2))
resp["correlation"]
end
private
def make_request(path, series, params)
post_data = {
series: series
}.merge(params)
path = "#{path}?#{URI.encode_www_form(api_key: @api_key)}" if @api_key
begin
response = @http.post("/#{path}", post_data.to_json, HEADERS)
rescue Errno::ECONNREFUSED, Timeout::Error => e
raise Trend::Error, e.message
end
parsed_body = JSON.parse(response.body) rescue {}
if !response.is_a?(Net::HTTPSuccess)
raise Trend::Error, parsed_body["error"] || "Server returned #{response.code} response"
end
parsed_body
end
def parse_time(v)
v.size == 10 ? Date.parse(v) : Time.parse(v)
end
end
end
| ruby | MIT | a8c01d4327231db4044f672b18a0f73dbb7c6980 | 2026-01-04T17:44:55.176641Z | false |
cyrusstoller/RevTilt | https://github.com/cyrusstoller/RevTilt/blob/c3fd80e411c3de72e9c9479474774d6cdcab888d/app/helpers/reviews_helper.rb | app/helpers/reviews_helper.rb | module ReviewsHelper
end
| ruby | MIT | c3fd80e411c3de72e9c9479474774d6cdcab888d | 2026-01-04T17:44:55.378213Z | false |
cyrusstoller/RevTilt | https://github.com/cyrusstoller/RevTilt/blob/c3fd80e411c3de72e9c9479474774d6cdcab888d/app/helpers/application_helper.rb | app/helpers/application_helper.rb | module ApplicationHelper
def bootstrap_alert_type(type)
case type
when :alert, "alert"
"danger"
when :error, "error"
"danger"
when :notice, "notice"
"warning"
when :success, "success"
"success"
else
type.to_s
end
end
def title
base_title = "RevTilt"
if @title.blank?
base_title
else
"#{base_title} | #{@title}"
end
end
end
| ruby | MIT | c3fd80e411c3de72e9c9479474774d6cdcab888d | 2026-01-04T17:44:55.378213Z | false |
cyrusstoller/RevTilt | https://github.com/cyrusstoller/RevTilt/blob/c3fd80e411c3de72e9c9479474774d6cdcab888d/app/helpers/pages_helper.rb | app/helpers/pages_helper.rb | module PagesHelper
def bookmarklet_javascript(service = nil, new_window = nil)
"javascript:(function(){__script=document.createElement('SCRIPT');__script.type='text/javascript';__script.src='#{bookmarklet_url(:service => service, :format => :js, :new_window => new_window)}';document.getElementsByTagName('head')[0].appendChild(__script);})();"
end
end
| ruby | MIT | c3fd80e411c3de72e9c9479474774d6cdcab888d | 2026-01-04T17:44:55.378213Z | false |
cyrusstoller/RevTilt | https://github.com/cyrusstoller/RevTilt/blob/c3fd80e411c3de72e9c9479474774d6cdcab888d/app/helpers/organizations_helper.rb | app/helpers/organizations_helper.rb | module OrganizationsHelper
end
| ruby | MIT | c3fd80e411c3de72e9c9479474774d6cdcab888d | 2026-01-04T17:44:55.378213Z | false |
cyrusstoller/RevTilt | https://github.com/cyrusstoller/RevTilt/blob/c3fd80e411c3de72e9c9479474774d6cdcab888d/app/helpers/relationships/organization_users_helper.rb | app/helpers/relationships/organization_users_helper.rb | module Relationships::OrganizationUsersHelper
end
| ruby | MIT | c3fd80e411c3de72e9c9479474774d6cdcab888d | 2026-01-04T17:44:55.378213Z | false |
cyrusstoller/RevTilt | https://github.com/cyrusstoller/RevTilt/blob/c3fd80e411c3de72e9c9479474774d6cdcab888d/app/helpers/api/v1/pages_helper.rb | app/helpers/api/v1/pages_helper.rb | module Api::V1::PagesHelper
end
| ruby | MIT | c3fd80e411c3de72e9c9479474774d6cdcab888d | 2026-01-04T17:44:55.378213Z | false |
cyrusstoller/RevTilt | https://github.com/cyrusstoller/RevTilt/blob/c3fd80e411c3de72e9c9479474774d6cdcab888d/app/helpers/api/v1/organizations_helper.rb | app/helpers/api/v1/organizations_helper.rb | module Api::V1::OrganizationsHelper
end
| ruby | MIT | c3fd80e411c3de72e9c9479474774d6cdcab888d | 2026-01-04T17:44:55.378213Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.