repository_name
stringlengths 7
56
| func_path_in_repository
stringlengths 10
101
| func_name
stringlengths 12
78
| language
stringclasses 1
value | func_code_string
stringlengths 74
11.9k
| func_documentation_string
stringlengths 3
8.03k
| split_name
stringclasses 1
value | func_code_url
stringlengths 98
213
| enclosing_scope
stringlengths 42
98.2k
|
---|---|---|---|---|---|---|---|---|
dropofwill/rtasklib | lib/rtasklib/taskrc.rb | Rtasklib.Taskrc.mappable_to_model | ruby | def mappable_to_model rc_file
rc_file.map! { |l| line_to_tuple(l) }.compact!
taskrc = Hash[rc_file]
hash_to_model(taskrc)
end | Converts a .taskrc file path into a Hash that can be converted into a
TaskrcModel object
@param rc_file [String,Pathname] a valid pathname to a .taskrc file
@return [Models::TaskrcModel] the instance variable config
@api private | train | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/taskrc.rb#L69-L73 | class Taskrc
attr_accessor :config
# Generate a dynamic Virtus model, with the attributes defined by the input
#
# @param rc [Hash, Pathname] either a hash of attribute value pairs
# or a Pathname to the raw taskrc file.
# @raise [TypeError] if rc is not of type Hash, String, or Pathname
# @raise [RuntimeError] if rc is a path and does not exist on the fs
def initialize rc, type=:array
@config = Models::TaskrcModel.new().extend(Virtus.model)
case type
when :array
mappable_to_model(rc)
when :hash
hash_to_model(rc)
when :path
if path_exist?(rc)
mappable_to_model(File.open(rc).readlines)
else
raise RuntimeError.new("rc path does not exist on the file system")
end
else
raise TypeError.new("no implicit conversion to Hash, String, or Pathname")
end
end
# Turn a hash of attribute => value pairs into a TaskrcModel object.
# There can be only one TaskrcModel object per Taskrc, it's saved to the
# instance variable `config`
#
# @param taskrc_hash [Hash{Symbol=>String}]
# @return [Models::TaskrcModel] the instance variable config
# @api private
def hash_to_model taskrc_hash
taskrc_hash.each do |attr, value|
add_model_attr(attr, value)
set_model_attr_value(attr, value)
end
config
end
private :hash_to_model
# Converts a .taskrc file path into a Hash that can be converted into a
# TaskrcModel object
#
# @param rc_file [String,Pathname] a valid pathname to a .taskrc file
# @return [Models::TaskrcModel] the instance variable config
# @api private
private :mappable_to_model
# Converts a line of the form "json.array=on" to [ :json_array, true ]
#
# @param line [String] a line from a .taskrc file
# @return [Array<Symbol, Object>, nil] a valid line returns an array of
# length 2, invalid input returns nil
# @api private
def line_to_tuple line
line = line.chomp.split('=', 2)
if line.size == 2 and not line.include? "#"
attr = get_hash_attr_from_rc line[0]
return [ attr.to_sym, line[1] ]
else
return nil
end
end
private :line_to_tuple
# Serialize the given attrs model back to the taskrc format
#
# @param attrs [Array] a splat of attributes
# @return [Array<String>] an array of CLI formatted strings
# @api public
def part_of_model_to_rc *attrs
attrs.map do |attr|
value = get_model_attr_value attr
hash_attr = get_rc_attr_from_hash attr.to_s
attr = "rc.#{hash_attr}=#{value}"
end
end
# Serialize all attrs of the model to the taskrc format
#
# @return [Array<String>] an array of CLI formatted strings
# @api public
def model_to_rc
part_of_model_to_rc(*config.attributes.keys)
end
# Serialize the given attrs model back to the taskrc format and reduce them
# to a string that can be passed directly to Execute
#
# @param attrs [Array] a splat of attributes
# @return [String] a CLI formatted string
# @api public
def part_of_model_to_s *attrs
part_of_model_to_rc(*attrs).join(" ")
end
# Serialize all attrs model back to the taskrc format and reduce them
# to a string that can be passed directly to Execute
#
# @return [String] a CLI formatted string
# @api public
def model_to_s
model_to_rc().join(" ")
end
# Dynamically add a Virtus attr, detect Boolean, Integer, and Float types
# based on the value, otherwise just treat it like a string.
# Modifies the config instance variable
# TODO: May also be able to detect arrays
#
# @param attr [#to_sym] the name for the attr, e.g. "json_array"
# @param value [String] the value of the attr, e.g. "yes"
# @return [undefined]
# @api private
def add_model_attr attr, value
config.attribute(attr.to_sym, Helpers.determine_type(value))
end
private :add_model_attr
# Modifies the value of a given attr in the config object
#
# @param attr [#to_s] the name for the attr, e.g. "json_array"
# @param value [String] the value of the attr, e.g. "yes"
# @return [undefined]
# @api public
def set_model_attr_value attr, value
config.send("#{attr}=".to_sym, value)
end
# Gets the current value of a given attr in the config object
#
# @param attr [#to_s] the name for the attr, e.g. "json_array"
# @return [Object] the type varies depending on the type attr
# @api public
def get_model_attr_value attr
config.send("#{attr.to_s}".to_sym)
end
# Convert dot notation to Symbol safe underscores
#
# @param attr [String] the name for the attr, e.g. "json_array"
# @return [String]
# @api private
def get_hash_attr_from_rc attr
return attr.gsub(".", "_")
end
private :get_hash_attr_from_rc
# Convert Symbol safe underscores to dot notation
#
# @param attr [String] the name for the attr, e.g. "json_array"
# @return [String]
# @api private
def get_rc_attr_from_hash attr
return attr.gsub("_", ".")
end
private :get_rc_attr_from_hash
# Check whether a given object is a path and it exists on the file system
#
# @param path [Object]
# @return [Boolean]
# @api private
def path_exist? path
if path.is_a? Pathname
return path.exist?
elsif path.is_a? String
return Pathname.new(path).exist?
else
return false
end
end
private :path_exist?
end
|
bradleymarques/carbon_date | lib/carbon_date/standard_formatter.rb | CarbonDate.StandardFormatter.millennium | ruby | def millennium(date)
m = ((date.year.abs.to_i / 1000) + 1).ordinalize + ' millennium'
return [m, BCE_SUFFIX].join(' ') if (date.year <= -1)
m
end | Formats a CarbonDate::Date with millennium precision
Returns:
A human-readable string representing the Date | train | https://github.com/bradleymarques/carbon_date/blob/778b2a58e0d0ae554d36fb92c356a6d9fc6415b4/lib/carbon_date/standard_formatter.rb#L84-L88 | class StandardFormatter < Formatter
# Suffix to use for Before Common Era dates (quite often BCE or BC)
BCE_SUFFIX = 'BCE'
# Collection of strings denoting month names for this Formatter
MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
# Formats a CarbonDate::Date with year precision as a string
# Returns:
# A human-readable string representing the Date
def year(date)
y = date.year.abs.to_s
return [y, BCE_SUFFIX].join(' ') if (date.year <= -1)
y
end
# Formats a CarbonDate::Date with month precision as a string
# Returns:
# A human-readable string representing the Date
def month(date)
[MONTHS[date.month - 1], year(date)].join(', ')
end
# Formats a CarbonDate::Date with day precision as a string
# Returns:
# A human-readable string representing the Date
def day(date)
[date.day.ordinalize.to_s, month(date)].join(' ')
end
# Formats a CarbonDate::Date with hour precision as a string
# Returns:
# A human-readable string representing the Date
def hour(date)
h = date.minute >= 30 ? date.hour + 1 : date.hour
time = [pad(h.to_s), '00'].join(':')
[time, day(date)].join(' ')
end
# Formats a CarbonDate::Date with minute precision as a string
# Returns:
# A human-readable string representing the Date
def minute(date)
time = [pad(date.hour.to_s), pad(date.minute.to_s)].join(':')
[time, day(date)].join(' ')
end
# Formats a CarbonDate::Date with second precision as a string
# Returns:
# A human-readable string representing the Date
def second(date)
time = [pad(date.hour.to_s), pad(date.minute.to_s), pad(date.second.to_s)].join(':')
[time, day(date)].join(' ')
end
# Formats a CarbonDate::Date with decade precision
# Returns:
# A human-readable string representing the Date
def decade(date)
d = ((date.year.abs.to_i / 10) * 10).to_s + 's'
return [d, BCE_SUFFIX].join(' ') if (date.year <= -1)
d
end
# Formats a CarbonDate::Date with century precision
# Returns:
# A human-readable string representing the Date
def century(date)
c = ((date.year.abs.to_i / 100) + 1).ordinalize + ' century'
return [c, BCE_SUFFIX].join(' ') if (date.year <= -1)
c
end
# Formats a CarbonDate::Date with millennium precision
# Returns:
# A human-readable string representing the Date
# Formats a CarbonDate::Date with ten_thousand_years precision
# Returns:
# A human-readable string representing the Date
def ten_thousand_years(date)
coarse_precision(date.year, 10e3.to_i)
end
# Formats a CarbonDate::Date with hundred_thousand_years precision
# Returns:
# A human-readable string representing the Date
def hundred_thousand_years(date)
coarse_precision(date.year, 100e3.to_i)
end
# Formats a CarbonDate::Date with million_years precision
# Returns:
# A human-readable string representing the Date
def million_years(date)
coarse_precision(date.year, 1e6.to_i)
end
# Formats a CarbonDate::Date with ten_million_years precision
# Returns:
# A human-readable string representing the Date
def ten_million_years(date)
coarse_precision(date.year, 10e6.to_i)
end
# Formats a CarbonDate::Date with hundred_million_years precision
# Returns:
# A human-readable string representing the Date
def hundred_million_years(date)
coarse_precision(date.year, 100e6.to_i)
end
# Formats a CarbonDate::Date with billion_years precision
# Returns:
# A human-readable string representing the Date
def billion_years(date)
coarse_precision(date.year, 1e9.to_i)
end
# A helper function used to format dates that have less than millenium precision
# Params:
# +date_year+ The year component of the CarbonDate::Date being formatted
# +interval+ The precision in years
# Returns:
# A human-readable string representing the Date
def coarse_precision(date_year, interval)
date_year = date_year.to_i
interval = interval.to_i
year_diff = date_year - ::Date.today.year
return "Within the last #{number_with_delimiter(interval)} years" if (-(interval - 1)..0).include? year_diff
return "Within the next #{number_with_delimiter(interval)} years" if (1..(interval - 1)).include? year_diff
rounded = (year_diff.to_f / interval.to_f).round * interval
return "in #{number_with_delimiter(rounded.abs)} years" if rounded > 0
return "#{number_with_delimiter(rounded.abs)} years ago" if rounded < 0
nil
end
# Converts an integer number into a human-readable string with thousands delimiters.
# Example:
# number_with_delimiter(1234567890, ',')
# => 1,234,567,890
# Params:
# +n+ the number to be delimited. Will be converted to an integer
# +delim+ the string to be used as the thousands delimiter. Defaults to ','
def number_with_delimiter(n, delim = ',')
n.to_i.to_s.reverse.chars.each_slice(3).map(&:join).join(delim).reverse
end
# Pad a string with '0' to ensure it has two characters.
# If a string of 2 or more characters is used as parameter, will not alter the string.
# Example:
# pad('1')
# => "01"
# Params:
# +s+ The string to pad.
# Returns:
# A string of at least 2 characters
def pad(s)
s.rjust(2, '0')
end
end
|
oleganza/btcruby | lib/btcruby/wire_format.rb | BTC.WireFormat.write_uleb128 | ruby | def write_uleb128(value, data: nil, stream: nil)
raise ArgumentError, "Integer must be present" if !value
buf = encode_uleb128(value)
data << buf if data
stream.write(buf) if stream
buf
end | Writes an unsigned integer encoded in LEB128 to a data buffer or a stream.
Returns LEB128-encoded binary string. | train | https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L280-L286 | module WireFormat
extend self
# Reads varint from data or stream.
# Either data or stream must be present (and only one of them).
# Optional offset is useful when reading from data.
# Returns [value, length] where value is a decoded integer value and length is number of bytes read (including offset bytes).
# Value may be nil when decoding failed (length might be zero or greater, depending on how much data was consumed before failing).
# Usage:
# i, _ = read_varint(data: buffer, offset: 42)
# i, _ = read_varint(stream: File.open('someblock','r'))
def read_varint(data: nil, stream: nil, offset: 0)
if data && !stream
return [nil, 0] if data.bytesize < 1 + offset
bytes = BTC::Data.bytes_from_data(data, offset: offset, limit: 9) # we don't need more than 9 bytes.
byte = bytes[0]
if byte < 0xfd
return [byte, offset + 1]
elsif byte == 0xfd
return [nil, 1] if data.bytesize < 3 + offset # 1 byte prefix, 2 bytes uint16
return [bytes[1] +
bytes[2]*256, offset + 3]
elsif byte == 0xfe
return [nil, 1] if data.bytesize < 5 + offset # 1 byte prefix, 4 bytes uint32
return [bytes[1] +
bytes[2]*256 +
bytes[3]*256*256 +
bytes[4]*256*256*256, offset + 5]
elsif byte == 0xff
return [nil, 1] if data.bytesize < 9 + offset # 1 byte prefix, 8 bytes uint64
return [bytes[1] +
bytes[2]*256 +
bytes[3]*256*256 +
bytes[4]*256*256*256 +
bytes[5]*256*256*256*256 +
bytes[6]*256*256*256*256*256 +
bytes[7]*256*256*256*256*256*256 +
bytes[8]*256*256*256*256*256*256*256, offset + 9]
end
elsif stream && !data
if stream.eof?
raise ArgumentError, "Can't parse varint from stream because it is already closed."
end
if offset > 0
buf = stream.read(offset)
return [nil, 0] if !buf
return [nil, buf.bytesize] if buf.bytesize < offset
end
prefix = stream.read(1)
return [nil, offset] if !prefix || prefix.bytesize == 0
byte = prefix.bytes[0]
if byte < 0xfd
return [byte, offset + 1]
elsif byte == 0xfd
buf = stream.read(2)
return [nil, offset + 1] if !buf
return [nil, offset + 1 + buf.bytesize] if buf.bytesize < 2
return [buf.unpack("v").first, offset + 3]
elsif byte == 0xfe
buf = stream.read(4)
return [nil, offset + 1] if !buf
return [nil, offset + 1 + buf.bytesize] if buf.bytesize < 4
return [buf.unpack("V").first, offset + 5]
elsif byte == 0xff
buf = stream.read(8)
return [nil, offset + 1] if !buf
return [nil, offset + 1 + buf.bytesize] if buf.bytesize < 8
return [buf.unpack("Q<").first, offset + 9]
end
else
raise ArgumentError, "Either data or stream must be specified."
end
end # read_varint
# Encodes integer and returns its binary varint representation.
def encode_varint(i)
raise ArgumentError, "int must be present" if !i
raise ArgumentError, "int must be non-negative" if i < 0
buf = if i < 0xfd
[i].pack("C")
elsif i <= 0xffff
[0xfd, i].pack("Cv")
elsif i <= 0xffffffff
[0xfe, i].pack("CV")
elsif i <= 0xffffffffffffffff
[0xff, i].pack("CQ<")
else
raise ArgumentError, "Does not support integers larger 0xffffffffffffffff (i = 0x#{i.to_s(16)})"
end
buf
end
# Encodes integer and returns its binary varint representation.
# If data is given, appends to a data.
# If stream is given, writes to a stream.
def write_varint(i, data: nil, stream: nil)
buf = encode_varint(i)
data << buf if data
stream.write(buf) if stream
buf
end
# Reads variable-length string from data buffer or IO stream.
# Either data or stream must be present (and only one of them).
# Returns [string, length] where length is a number of bytes read (includes length prefix and offset bytes).
# In case of failure, returns [nil, length] where length is a number of bytes read before the error was encountered.
def read_string(data: nil, stream: nil, offset: 0)
if data && !stream
string_length, read_length = read_varint(data: data, offset: offset)
# If failed to read the length prefix, return nil.
return [nil, read_length] if !string_length
# Check if we have enough bytes to read the string itself
return [nil, read_length] if data.bytesize < read_length + string_length
string = BTC::Data.ensure_binary_encoding(data)[read_length, string_length]
return [string, read_length + string_length]
elsif stream && !data
string_length, read_length = read_varint(stream: stream, offset: offset)
return [nil, read_length] if !string_length
buf = stream.read(string_length)
return [nil, read_length] if !buf
return [nil, read_length + buf.bytesize] if buf.bytesize < string_length
return [buf, read_length + buf.bytesize]
else
raise ArgumentError, "Either data or stream must be specified."
end
end
# Returns the binary representation of the var-length string.
def encode_string(string)
raise ArgumentError, "String must be present" if !string
encode_varint(string.bytesize) + BTC::Data.ensure_binary_encoding(string)
end
# Writes variable-length string to a data buffer or IO stream.
# If data is given, appends to a data.
# If stream is given, writes to a stream.
# Returns the binary representation of the var-length string.
def write_string(string, data: nil, stream: nil)
raise ArgumentError, "String must be present" if !string
intbuf = write_varint(string.bytesize, data: data, stream: stream)
stringbuf = BTC::Data.ensure_binary_encoding(string)
data << stringbuf if data
stream.write(stringbuf) if stream
intbuf + stringbuf
end
# Reads varint length prefix, then calls the block appropriate number of times to read the items.
# Returns an array of items.
def read_array(data: nil, stream: nil, offset: 0)
count, len = read_varint(data: data, stream: stream, offset: offset)
return [nil, len] if !count
(0...count).map do |i|
yield
end
end
def encode_array(array, &block)
write_array(array, &block)
end
def write_array(array, data: nil, stream: nil, &block)
raise ArgumentError, "Array must be present" if !array
raise ArgumentError, "Parsing block must be present" if !block
intbuf = write_varint(array.size, data: data, stream: stream)
array.inject(intbuf) do |buf, e|
string = block.call(e)
stringbuf = BTC::Data.ensure_binary_encoding(string)
data << stringbuf if data
stream.write(stringbuf) if stream
buf << stringbuf
buf
end
end
# LEB128 encoding used in Open Assets protocol
# Decodes an unsigned integer encoded in LEB128.
# Returns `[value, length]` where `value` is an integer decoded from LEB128 and `length`
# is a number of bytes read (includes length prefix and offset bytes).
def read_uleb128(data: nil, stream: nil, offset: 0)
if (data && stream) || (!data && !stream)
raise ArgumentError, "Either data or stream must be specified."
end
if data
data = BTC::Data.ensure_binary_encoding(data)
end
if stream
if stream.eof?
raise ArgumentError, "Can't read LEB128 from stream because it is already closed."
end
if offset > 0
buf = stream.read(offset)
return [nil, 0] if !buf
return [nil, buf.bytesize] if buf.bytesize < offset
end
end
result = 0
shift = 0
while true
byte = if data
return [nil, offset] if data.bytesize < 1 + offset
BTC::Data.bytes_from_data(data, offset: offset, limit: 1)[0]
elsif stream
buf = stream.read(1)
return [nil, offset] if !buf || buf.bytesize == 0
buf.bytes[0]
end
result |= (byte & 0x7f) << shift
break if byte & 0x80 == 0
shift += 7
offset += 1
end
[result, offset + 1]
end
# Encodes an unsigned integer using LEB128.
def encode_uleb128(value)
raise ArgumentError, "Signed integers are not supported" if value < 0
return "\x00" if value == 0
bytes = []
while value != 0
byte = value & 0b01111111 # 0x7f
value >>= 7
if value != 0
byte |= 0b10000000 # 0x80
end
bytes << byte
end
return BTC::Data.data_from_bytes(bytes)
end
# Writes an unsigned integer encoded in LEB128 to a data buffer or a stream.
# Returns LEB128-encoded binary string.
PACK_FORMAT_UINT8 = "C".freeze
PACK_FORMAT_INT8 = "c".freeze
PACK_FORMAT_UINT16LE = "S<".freeze
PACK_FORMAT_INT16LE = "s<".freeze
PACK_FORMAT_UINT32LE = "L<".freeze
PACK_FORMAT_INT32LE = "l<".freeze
PACK_FORMAT_UINT32BE = "L>".freeze # used in BIP32
PACK_FORMAT_INT32BE = "l>".freeze
PACK_FORMAT_UINT64LE = "Q<".freeze
PACK_FORMAT_INT64LE = "q<".freeze
# These read fixed-length integer in appropriate format ("le" stands for "little-endian")
# Return [value, length] or [nil, length] just like #read_varint method (see above).
def read_uint8(data: nil, stream: nil, offset: 0)
_read_fixint(name: :uint8, length: 1, pack_format: PACK_FORMAT_UINT8, data: data, stream: stream, offset: offset)
end
def read_int8(data: nil, stream: nil, offset: 0)
_read_fixint(name: :int8, length: 1, pack_format: PACK_FORMAT_INT8, data: data, stream: stream, offset: offset)
end
def read_uint16le(data: nil, stream: nil, offset: 0)
_read_fixint(name: :uint16le, length: 2, pack_format: PACK_FORMAT_UINT16LE, data: data, stream: stream, offset: offset)
end
def read_int16le(data: nil, stream: nil, offset: 0)
_read_fixint(name: :int16le, length: 2, pack_format: PACK_FORMAT_INT16LE, data: data, stream: stream, offset: offset)
end
def read_uint32le(data: nil, stream: nil, offset: 0)
_read_fixint(name: :uint32le, length: 4, pack_format: PACK_FORMAT_UINT32LE, data: data, stream: stream, offset: offset)
end
def read_int32le(data: nil, stream: nil, offset: 0)
_read_fixint(name: :int32le, length: 4, pack_format: PACK_FORMAT_INT32LE, data: data, stream: stream, offset: offset)
end
def read_uint32be(data: nil, stream: nil, offset: 0) # used in BIP32
_read_fixint(name: :uint32be, length: 4, pack_format: PACK_FORMAT_UINT32BE, data: data, stream: stream, offset: offset)
end
def read_int32be(data: nil, stream: nil, offset: 0)
_read_fixint(name: :int32be, length: 4, pack_format: PACK_FORMAT_INT32BE, data: data, stream: stream, offset: offset)
end
def read_uint64le(data: nil, stream: nil, offset: 0)
_read_fixint(name: :uint64le, length: 8, pack_format: PACK_FORMAT_UINT64LE, data: data, stream: stream, offset: offset)
end
def read_int64le(data: nil, stream: nil, offset: 0)
_read_fixint(name: :int64le, length: 8, pack_format: PACK_FORMAT_INT64LE, data: data, stream: stream, offset: offset)
end
# Encode int into one of the formats
def encode_uint8(int); [int].pack(PACK_FORMAT_UINT8); end
def encode_int8(int); [int].pack(PACK_FORMAT_INT8); end
def encode_uint16le(int); [int].pack(PACK_FORMAT_UINT16LE); end
def encode_int16le(int); [int].pack(PACK_FORMAT_INT16LE); end
def encode_int32be(int); [int].pack(PACK_FORMAT_INT32BE); end
def encode_uint32le(int); [int].pack(PACK_FORMAT_UINT32LE); end
def encode_int32le(int); [int].pack(PACK_FORMAT_INT32LE); end
def encode_uint32be(int); [int].pack(PACK_FORMAT_UINT32BE); end # used in BIP32
def encode_uint64le(int); [int].pack(PACK_FORMAT_UINT64LE); end
def encode_int64le(int); [int].pack(PACK_FORMAT_INT64LE); end
protected
def _read_fixint(name: nil, length: nil, pack_format: nil, data: nil, stream: nil, offset: 0)
if data && !stream
if data.bytesize < offset + length
Diagnostics.current.add_message("BTC::WireFormat#read_#{name}: Not enough bytes to read #{name} in binary string.")
return [nil, 0]
end
if offset > 0
pack_format = "@#{offset}" + pack_format
end
return [data.unpack(pack_format).first, offset + length]
elsif stream && !data
if offset > 0
buf = stream.read(offset)
return [nil, 0] if !buf
return [nil, buf.bytesize] if buf.bytesize < offset
end
buf = stream.read(length)
if !buf
Diagnostics.current.add_message("BTC::WireFormat#read_#{name}: Failed to read #{name} from stream.")
return [nil, offset]
end
if buf.bytesize < length
Diagnostics.current.add_message("BTC::WireFormat#read_#{name}: Not enough bytes to read #{name} from stream.")
return [nil, offset + buf.bytesize]
end
return [buf.unpack(pack_format).first, offset + length]
else
raise ArgumentError, "BTC::WireFormat#read_#{name}: Either data or stream must be specified."
end
end
end
|
dicom/rtp-connect | lib/rtp-connect/control_point.rb | RTP.ControlPoint.dcm_collimator | ruby | def dcm_collimator(axis, coeff, nr)
mode = self.send("field_#{axis}_mode")
if mode && !mode.empty?
target = self
else
target = @parent
end
target.send("collimator_#{axis}#{nr}").to_f * 10 * coeff
end | Converts the collimator attribute to proper DICOM format.
@param [Symbol] axis a representation for the axis of interest (x or y)
@param [Integer] coeff a coeffecient (of -1 or 1) which the attribute is multiplied with
@param [Integer] nr collimator side/index (1 or 2)
@return [Float] the DICOM-formatted collimator attribute | train | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/control_point.rb#L585-L593 | class ControlPoint < Record
# The number of attributes not having their own variable for this record (200 - 2).
NR_SURPLUS_ATTRIBUTES = 198
# The Record which this instance belongs to.
attr_accessor :parent
# The MLC shape record (if any) that belongs to this ControlPoint.
attr_reader :mlc_shape
attr_reader :field_id
attr_reader :mlc_type
attr_reader :mlc_leaves
attr_reader :total_control_points
attr_reader :control_pt_number
attr_reader :mu_convention
attr_reader :monitor_units
attr_reader :wedge_position
attr_reader :energy
attr_reader :doserate
attr_reader :ssd
attr_reader :scale_convention
attr_reader :gantry_angle
attr_reader :gantry_dir
attr_reader :collimator_angle
attr_reader :collimator_dir
attr_reader :field_x_mode
attr_reader :field_x
attr_reader :collimator_x1
attr_reader :collimator_x2
attr_reader :field_y_mode
attr_reader :field_y
attr_reader :collimator_y1
attr_reader :collimator_y2
attr_reader :couch_vertical
attr_reader :couch_lateral
attr_reader :couch_longitudinal
attr_reader :couch_angle
attr_reader :couch_dir
attr_reader :couch_pedestal
attr_reader :couch_ped_dir
attr_reader :iso_pos_x
attr_reader :iso_pos_y
attr_reader :iso_pos_z
# Note: This attribute contains an array of all MLC LP A values (leaves 1..100).
attr_reader :mlc_lp_a
# Note: This attribute contains an array of all MLC LP B values (leaves 1..100).
attr_reader :mlc_lp_b
# Creates a new ControlPoint by parsing a RTPConnect string line.
#
# @param [#to_s] string the control point definition record string line
# @param [Record] parent a record which is used to determine the proper parent of this instance
# @return [ControlPoint] the created ControlPoint instance
# @raise [ArgumentError] if given a string containing an invalid number of elements
#
def self.load(string, parent)
cp = self.new(parent)
cp.load(string)
end
# Creates a new ControlPoint.
#
# @param [Record] parent a record which is used to determine the proper parent of this instance
#
def initialize(parent)
super('CONTROL_PT_DEF', 233, 236)
# Child:
@mlc_shape = nil
# Parent relation (may get more than one type of record here):
@parent = get_parent(parent.to_record, Field)
@parent.add_control_point(self)
@mlc_lp_a = Array.new(100)
@mlc_lp_b = Array.new(100)
@attributes = [
# Required:
:keyword,
:field_id,
:mlc_type,
:mlc_leaves,
:total_control_points,
:control_pt_number,
:mu_convention,
:monitor_units,
:wedge_position,
:energy,
:doserate,
:ssd,
:scale_convention,
:gantry_angle,
:gantry_dir,
:collimator_angle,
:collimator_dir,
:field_x_mode,
:field_x,
:collimator_x1,
:collimator_x2,
:field_y_mode,
:field_y,
:collimator_y1,
:collimator_y2,
:couch_vertical,
:couch_lateral,
:couch_longitudinal,
:couch_angle,
:couch_dir,
:couch_pedestal,
:couch_ped_dir,
:iso_pos_x,
:iso_pos_y,
:iso_pos_z,
:mlc_lp_a,
:mlc_lp_b
]
end
# Checks for equality.
#
# Other and self are considered equivalent if they are
# of compatible types and their attributes are equivalent.
#
# @param other an object to be compared with self.
# @return [Boolean] true if self and other are considered equivalent
#
def ==(other)
if other.respond_to?(:to_control_point)
other.send(:state) == state
end
end
alias_method :eql?, :==
# As of now, gives an empty array. However, by definition, this record may
# have an mlc shape record as child, but this is not implemented yet.
#
# @return [Array] an emtpy array
#
def children
#return [@mlc_shape]
return Array.new
end
# Converts the collimator_x1 attribute to proper DICOM format.
#
# @param [Symbol] scale if set, relevant device parameters are converted from a native readout format to IEC1217 (supported values are :elekta & :varian)
# @return [Float] the DICOM-formatted collimator_x1 attribute
#
def dcm_collimator_x1(scale=nil)
dcm_collimator_1(scale, default_axis=:x)
end
# Converts the collimator_x2 attribute to proper DICOM format.
#
# @param [Symbol] scale if set, relevant device parameters are converted from native readout format to IEC1217 (supported values are :elekta & :varian)
# @return [Float] the DICOM-formatted collimator_x2 attribute
#
def dcm_collimator_x2(scale=nil)
axis = (scale == :elekta ? :y : :x)
dcm_collimator(axis, coeff=1, side=2)
end
# Converts the collimator_y1 attribute to proper DICOM format.
#
# @param [Symbol] scale if set, relevant device parameters are converted from native readout format to IEC1217 (supported values are :elekta & :varian)
# @return [Float] the DICOM-formatted collimator_y1 attribute
#
def dcm_collimator_y1(scale=nil)
dcm_collimator_1(scale, default_axis=:y)
end
# Converts the collimator_y2 attribute to proper DICOM format.
#
# @param [Symbol] scale if set, relevant device parameters are converted from native readout format to IEC1217 (supported values are :elekta & :varian)
# @return [Float] the DICOM-formatted collimator_y2 attribute
#
def dcm_collimator_y2(scale=nil)
axis = (scale == :elekta ? :x : :y)
dcm_collimator(axis, coeff=1, side=2)
end
# Converts the mlc_lp_a & mlc_lp_b attributes to a proper DICOM formatted string.
#
# @param [Symbol] scale if set, relevant device parameters are converted from native readout format to IEC1217 (supported values are :elekta & :varian)
# @return [String] the DICOM-formatted leaf pair positions
#
def dcm_mlc_positions(scale=nil)
coeff = (scale == :elekta ? -1 : 1)
# As with the collimators, the first side (1/a) may need scale invertion:
pos_a = @mlc_lp_a.collect{|p| (p.to_f * 10 * coeff).round(1) unless p.empty?}.compact
pos_b = @mlc_lp_b.collect{|p| (p.to_f * 10).round(1) unless p.empty?}.compact
(pos_a + pos_b).join("\\")
end
# Computes a hash code for this object.
#
# @note Two objects with the same attributes will have the same hash code.
#
# @return [Fixnum] the object's hash code
#
def hash
state.hash
end
# Gives the index of this ControlPoint
# (i.e. its index among the control points belonging to the parent Field).
#
# @return [Fixnum] the control point's index
#
def index
@parent.control_points.index(self)
end
# Collects the values (attributes) of this instance.
#
# @note The CRC is not considered part of the actual values and is excluded.
# @return [Array<String>] an array of attributes (in the same order as they appear in the RTP string)
#
def values
[
@keyword,
@field_id,
@mlc_type,
@mlc_leaves,
@total_control_points,
@control_pt_number,
@mu_convention,
@monitor_units,
@wedge_position,
@energy,
@doserate,
@ssd,
@scale_convention,
@gantry_angle,
@gantry_dir,
@collimator_angle,
@collimator_dir,
@field_x_mode,
@field_x,
@collimator_x1,
@collimator_x2,
@field_y_mode,
@field_y,
@collimator_y1,
@collimator_y2,
@couch_vertical,
@couch_lateral,
@couch_longitudinal,
@couch_angle,
@couch_dir,
@couch_pedestal,
@couch_ped_dir,
@iso_pos_x,
@iso_pos_y,
@iso_pos_z,
*@mlc_lp_a,
*@mlc_lp_b
]
end
# Returns self.
#
# @return [ControlPoint] self
#
def to_control_point
self
end
# Sets the mlc_lp_a attribute.
#
# @note As opposed to the ordinary (string) attributes, this attribute
# contains an array holding all 100 MLC leaf 'A' string values.
# @param [Array<nil, #to_s>] array the new attribute values
#
def mlc_lp_a=(array)
@mlc_lp_a = array.to_a.validate_and_process(100)
end
# Sets the mlc_lp_b attribute.
#
# @note As opposed to the ordinary (string) attributes, this attribute
# contains an array holding all 100 MLC leaf 'B' string values.
# @param [Array<nil, #to_s>] array the new attribute values
#
def mlc_lp_b=(array)
@mlc_lp_b = array.to_a.validate_and_process(100)
end
# Sets the field_id attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def field_id=(value)
@field_id = value && value.to_s
end
# Sets the mlc_type attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def mlc_type=(value)
@mlc_type = value && value.to_s
end
# Sets the mlc_leaves attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def mlc_leaves=(value)
@mlc_leaves = value && value.to_s.strip
end
# Sets the total_control_points attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def total_control_points=(value)
@total_control_points = value && value.to_s.strip
end
# Sets the control_pt_number attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def control_pt_number=(value)
@control_pt_number = value && value.to_s.strip
end
# Sets the mu_convention attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def mu_convention=(value)
@mu_convention = value && value.to_s
end
# Sets the monitor_units attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def monitor_units=(value)
@monitor_units = value && value.to_s
end
# Sets the wedge_position attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def wedge_position=(value)
@wedge_position = value && value.to_s
end
# Sets the energy attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def energy=(value)
@energy = value && value.to_s
end
# Sets the doserate attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def doserate=(value)
@doserate = value && value.to_s.strip
end
# Sets the ssd attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def ssd=(value)
@ssd = value && value.to_s
end
# Sets the scale_convention attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def scale_convention=(value)
@scale_convention = value && value.to_s
end
# Sets the gantry_angle attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def gantry_angle=(value)
@gantry_angle = value && value.to_s.strip
end
# Sets the gantry_dir attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def gantry_dir=(value)
@gantry_dir = value && value.to_s
end
# Sets the collimator_angle attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def collimator_angle=(value)
@collimator_angle = value && value.to_s.strip
end
# Sets the collimator_dir attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def collimator_dir=(value)
@collimator_dir = value && value.to_s
end
# Sets the field_x_mode attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def field_x_mode=(value)
@field_x_mode = value && value.to_s
end
# Sets the field_x attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def field_x=(value)
@field_x = value && value.to_s.strip
end
# Sets the collimator_x1 attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def collimator_x1=(value)
@collimator_x1 = value && value.to_s.strip
end
# Sets the collimator_x2 attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def collimator_x2=(value)
@collimator_x2 = value && value.to_s.strip
end
# Sets the field_y_mode attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def field_y_mode=(value)
@field_y_mode = value && value.to_s
end
# Sets the field_y attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def field_y=(value)
@field_y = value && value.to_s.strip
end
# Sets the collimator_y1 attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def collimator_y1=(value)
@collimator_y1 = value && value.to_s.strip
end
# Sets the collimator_y2 attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def collimator_y2=(value)
@collimator_y2 = value && value.to_s.strip
end
# Sets the couch_vertical attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def couch_vertical=(value)
@couch_vertical = value && value.to_s.strip
end
# Sets the couch_lateral attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def couch_lateral=(value)
@couch_lateral = value && value.to_s.strip
end
# Sets the couch_longitudinal attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def couch_longitudinal=(value)
@couch_longitudinal = value && value.to_s.strip
end
# Sets the couch_angle attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def couch_angle=(value)
@couch_angle = value && value.to_s.strip
end
# Sets the couch_dir attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def couch_dir=(value)
@couch_dir = value && value.to_s
end
# Sets the couch_pedestal attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def couch_pedestal=(value)
@couch_pedestal = value && value.to_s.strip
end
# Sets the couch_ped_dir attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def couch_ped_dir=(value)
@couch_ped_dir = value && value.to_s
end
# Sets the iso_pos_x attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def iso_pos_x=(value)
@iso_pos_x = value && value.to_s.strip
end
# Sets the iso_pos_y attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def iso_pos_y=(value)
@iso_pos_y = value && value.to_s.strip
end
# Sets the iso_pos_z attribute.
#
# @param [nil, #to_s] value the new attribute value
#
def iso_pos_z=(value)
@iso_pos_z = value && value.to_s.strip
end
private
# Collects the attributes of this instance.
#
# @note The CRC is not considered part of the attributes of interest and is excluded
# @return [Array<String>] an array of attributes
#
alias_method :state, :values
# Converts the collimator attribute to proper DICOM format.
#
# @param [Symbol] axis a representation for the axis of interest (x or y)
# @param [Integer] coeff a coeffecient (of -1 or 1) which the attribute is multiplied with
# @param [Integer] nr collimator side/index (1 or 2)
# @return [Float] the DICOM-formatted collimator attribute
#
# Converts the collimator1 attribute to proper DICOM format.
#
# @param [Symbol] scale if set, relevant device parameters are converted from a native readout format to IEC1217 (supported values are :elekta & :varian)
# @return [Float] the DICOM-formatted collimator_x1 attribute
#
def dcm_collimator_1(scale=nil, axis)
coeff = 1
if scale == :elekta
axis = (axis == :x ? :y : :x)
coeff = -1
elsif scale == :varian
coeff = -1
end
dcm_collimator(axis, coeff, side=1)
end
# Gives an array of indices indicating where the attributes of this record gets its
# values from in the comma separated string which the instance is created from.
#
# @param [Integer] length the number of elements to create in the indices array
#
def import_indices(length)
# Note that this method is defined in the parent Record class, where it is
# used for most record types. However, because this record has two attributes
# which contain an array of values, we use a custom import_indices method.
#
# Furthermore, as of Mosaiq version 2.64, the RTP ControlPoint record includes
# 3 new attributes: iso_pos_x/y/z. Since these (unfortunately) are not placed
# at the end of the record (which is the norm), but rather inserted before the
# MLC leaf positions, we have to take special care here to make sure that this
# gets right for records where these are included or excluded.
#
# Override length:
applied_length = 235
ind = Array.new(applied_length - NR_SURPLUS_ATTRIBUTES) { |i| [i] }
# Override indices for mlc_pl_a and mlc_lp_b:
# Allocation here is dependent on the RTP file version:
# For 2.62 and earlier, where length is 232, we dont have the 3 iso_pos_x/y/z values preceeding the mlc arrays leaf position arrays.
# For 2.64 (and later), where length is 235, we have the 3 iso_pos_x/y/z values preceeding the mlc leaf position arrays.
if length == 232
ind[32] = nil
ind[33] = nil
ind[34] = nil
ind[35] = (32..131).to_a
ind[36] = (132..231).to_a
else # (length = 235)
ind[35] = (35..134).to_a
ind[36] = (135..234).to_a
end
ind
end
end
|
kontena/kontena | cli/lib/kontena/client.rb | Kontena.Client.delete | ruby | def delete(path, body = nil, params = {}, headers = {}, auth = true)
request(http_method: :delete, path: path, body: body, query: params, headers: headers, auth: auth)
end | Delete request
@param [String] path
@param [Hash,String] body
@param [Hash] params
@param [Hash] headers
@return [Hash] | train | https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L243-L245 | class Client
CLIENT_ID = ENV['KONTENA_CLIENT_ID'] || '15faec8a7a9b4f1e8b7daebb1307f1d8'.freeze
CLIENT_SECRET = ENV['KONTENA_CLIENT_SECRET'] || 'fb8942ae00da4c7b8d5a1898effc742f'.freeze
CONTENT_URLENCODED = 'application/x-www-form-urlencoded'.freeze
CONTENT_JSON = 'application/json'.freeze
JSON_REGEX = /application\/(.+?\+)?json/.freeze
CONTENT_TYPE = 'Content-Type'.freeze
X_KONTENA_VERSION = 'X-Kontena-Version'.freeze
ACCEPT = 'Accept'.freeze
AUTHORIZATION = 'Authorization'.freeze
ACCEPT_ENCODING = 'Accept-Encoding'.freeze
GZIP = 'gzip'.freeze
attr_accessor :default_headers
attr_accessor :path_prefix
attr_reader :http_client
attr_reader :last_response
attr_reader :options
attr_reader :token
attr_reader :logger
attr_reader :api_url
attr_reader :host
# Initialize api client
#
# @param [String] api_url
# @param [Kontena::Cli::Config::Token,Hash] access_token
# @param [Hash] options
def initialize(api_url, token = nil, options = {})
require 'json'
require 'excon'
require 'uri'
require 'base64'
require 'socket'
require 'openssl'
require 'uri'
require 'time'
require 'kontena/errors'
require 'kontena/cli/version'
require 'kontena/cli/config'
@api_url, @token, @options = api_url, token, options
uri = URI.parse(@api_url)
@host = uri.host
@logger = Kontena.logger
@options[:default_headers] ||= {}
excon_opts = {
omit_default_port: true,
connect_timeout: ENV["EXCON_CONNECT_TIMEOUT"] ? ENV["EXCON_CONNECT_TIMEOUT"].to_i : 10,
read_timeout: ENV["EXCON_READ_TIMEOUT"] ? ENV["EXCON_READ_TIMEOUT"].to_i : 30,
write_timeout: ENV["EXCON_WRITE_TIMEOUT"] ? ENV["EXCON_WRITE_TIMEOUT"].to_i : 10,
ssl_verify_peer: ignore_ssl_errors? ? false : true,
middlewares: Excon.defaults[:middlewares] + [Excon::Middleware::Decompress]
}
if Kontena.debug?
require 'kontena/debug_instrumentor'
excon_opts[:instrumentor] = Kontena::DebugInstrumentor
end
excon_opts[:ssl_ca_file] = @options[:ssl_cert_path]
excon_opts[:ssl_verify_peer_host] = @options[:ssl_subject_cn]
debug { "Excon opts: #{excon_opts.inspect}" }
@http_client = Excon.new(api_url, excon_opts)
@default_headers = {
ACCEPT => CONTENT_JSON,
CONTENT_TYPE => CONTENT_JSON,
'User-Agent' => "kontena-cli/#{Kontena::Cli::VERSION}"
}.merge(options[:default_headers])
if token
if token.kind_of?(String)
@token = { 'access_token' => token }
else
@token = token
end
end
@api_url = api_url
@path_prefix = options[:prefix] || '/v1/'
end
def debug(&block)
logger.debug("CLIENT", &block)
end
def error(&block)
logger.error("CLIENT", &block)
end
# Generates a header hash for HTTP basic authentication.
# Defaults to using client_id and client_secret as user/pass
#
# @param [String] username
# @param [String] password
# @return [Hash] auth_header_hash
def basic_auth_header(user = nil, pass = nil)
user ||= client_id
pass ||= client_secret
{
AUTHORIZATION =>
"Basic #{Base64.encode64([user, pass].join(':')).gsub(/[\r\n]/, '')}"
}
end
# Generates a bearer token authentication header hash if a token object is
# available. Otherwise returns an empty hash.
#
# @return [Hash] authentication_header
def bearer_authorization_header
if token && token['access_token']
{AUTHORIZATION => "Bearer #{token['access_token']}"}
else
{}
end
end
# Requests path supplied as argument and returns true if the request was a success.
# For checking if the current authentication is valid.
#
# @param [String] token_verify_path a path that requires authentication
# @return [Boolean]
def authentication_ok?(token_verify_path)
return false unless token
return false unless token['access_token']
return false unless token_verify_path
final_path = token_verify_path.gsub(/\:access\_token/, token['access_token'])
debug { "Requesting user info from #{final_path}" }
request(path: final_path)
true
rescue => ex
error { "Authentication verification exception" }
error { ex }
false
end
# Calls the code exchange endpoint in token's config to exchange an authorization_code
# to a access_token
def exchange_code(code)
return nil unless token_account
return nil unless token_account['token_endpoint']
response = request(
http_method: token_account['token_method'].downcase.to_sym,
path: token_account['token_endpoint'],
headers: { CONTENT_TYPE => token_account['token_post_content_type'] },
body: {
'grant_type' => 'authorization_code',
'code' => code,
'client_id' => Kontena::Client::CLIENT_ID,
'client_secret' => Kontena::Client::CLIENT_SECRET
},
expects: [200,201],
auth: false
)
response['expires_at'] ||= in_to_at(response['expires_in'])
response
end
# Return server version from a Kontena master by requesting '/'
#
# @return [String] version_string
def server_version
request(auth: false, expects: 200)['version']
rescue => ex
error { "Server version exception" }
error { ex }
nil
end
# OAuth2 client_id from ENV KONTENA_CLIENT_ID or client CLIENT_ID constant
#
# @return [String]
def client_id
ENV['KONTENA_CLIENT_ID'] || CLIENT_ID
end
# OAuth2 client_secret from ENV KONTENA_CLIENT_SECRET or client CLIENT_SECRET constant
#
# @return [String]
def client_secret
ENV['KONTENA_CLIENT_SECRET'] || CLIENT_SECRET
end
# Get request
#
# @param [String] path
# @param [Hash,NilClass] params
# @param [Hash] headers
# @return [Hash]
def get(path, params = nil, headers = {}, auth = true)
request(path: path, query: params, headers: headers, auth: auth)
end
# Post request
#
# @param [String] path
# @param [Object] obj
# @param [Hash] params
# @param [Hash] headers
# @return [Hash]
def post(path, obj, params = {}, headers = {}, auth = true)
request(http_method: :post, path: path, body: obj, query: params, headers: headers, auth: auth)
end
# Put request
#
# @param [String] path
# @param [Object] obj
# @param [Hash] params
# @param [Hash] headers
# @return [Hash]
def put(path, obj, params = {}, headers = {}, auth = true)
request(http_method: :put, path: path, body: obj, query: params, headers: headers, auth: auth)
end
# Patch request
#
# @param [String] path
# @param [Object] obj
# @param [Hash] params
# @param [Hash] headers
# @return [Hash]
def patch(path, obj, params = {}, headers = {}, auth = true)
request(http_method: :patch, path: path, body: obj, query: params, headers: headers, auth: auth)
end
# Delete request
#
# @param [String] path
# @param [Hash,String] body
# @param [Hash] params
# @param [Hash] headers
# @return [Hash]
# Get stream request
#
# @param [String] path
# @param [Lambda] response_block
# @param [Hash,NilClass] params
# @param [Hash] headers
def get_stream(path, response_block, params = nil, headers = {}, auth = true)
request(path: path, query: params, headers: headers, response_block: response_block, auth: auth, gzip: false)
end
def token_expired?
return false unless token
if token.respond_to?(:expired?)
token.expired?
elsif token['expires_at'].to_i > 0
token['expires_at'].to_i < Time.now.utc.to_i
else
false
end
end
# Perform a HTTP request. Will try to refresh the access token and retry if it's
# expired or if the server responds with HTTP 401.
#
# Automatically parses a JSON response into a hash.
#
# After the request has been performed, the response can be inspected using
# client.last_response.
#
# @param http_method [Symbol] :get, :post, etc
# @param path [String] if it starts with / then prefix won't be used.
# @param body [Hash, String] will be encoded using #encode_body
# @param query [Hash] url query parameters
# @param headers [Hash] extra headers for request.
# @param response_block [Proc] for streaming requests, must respond to #call
# @param expects [Array] raises unless response status code matches this list.
# @param auth [Boolean] use token authentication default = true
# @return [Hash, String] response parsed response object
def request(http_method: :get, path:'/', body: nil, query: {}, headers: {}, response_block: nil, expects: [200, 201, 204], host: nil, port: nil, auth: true, gzip: true)
retried ||= false
if auth && token_expired?
raise Excon::Error::Unauthorized, "Token expired or not valid, you need to login again, use: kontena #{token_is_for_master? ? "master" : "cloud"} login"
end
request_headers = request_headers(headers, auth: auth, gzip: gzip)
if body.nil?
body_content = ''
request_headers.delete(CONTENT_TYPE)
else
body_content = encode_body(body, request_headers[CONTENT_TYPE])
request_headers.merge!('Content-Length' => body_content.bytesize)
end
uri = URI.parse(path)
host_options = {}
if uri.host
host_options[:host] = uri.host
host_options[:port] = uri.port
host_options[:scheme] = uri.scheme
path = uri.request_uri
else
host_options[:host] = host if host
host_options[:port] = port if port
end
request_options = {
method: http_method,
expects: Array(expects),
path: path_with_prefix(path),
headers: request_headers,
body: body_content,
query: query
}.merge(host_options)
request_options.merge!(response_block: response_block) if response_block
# Store the response into client.last_response
@last_response = http_client.request(request_options)
parse_response(@last_response)
rescue Excon::Error::Unauthorized
if token
debug { 'Server reports access token expired' }
if retried || !token || !token['refresh_token']
raise Kontena::Errors::StandardError.new(401, 'The access token has expired and needs to be refreshed')
end
retried = true
retry if refresh_token
end
raise Kontena::Errors::StandardError.new(401, 'Unauthorized')
rescue Excon::Error::HTTPStatus => error
if error.response.headers['Content-Encoding'] == 'gzip'
error.response.body = Zlib::GzipReader.new(StringIO.new(error.response.body)).read
end
debug { "Request #{error.request[:method].upcase} #{error.request[:path]}: #{error.response.status} #{error.response.reason_phrase}: #{error.response.body}" }
handle_error_response(error.response)
end
# Build a token refresh request param hash
#
# @return [Hash]
def refresh_request_params
{
refresh_token: token['refresh_token'],
grant_type: 'refresh_token',
client_id: client_id,
client_secret: client_secret
}
end
# Accessor to token's account settings
def token_account
return {} unless token
if token.respond_to?(:account)
token.account
elsif token.kind_of?(Hash) && token['account'].kind_of?(String)
config.find_account(token['account'])
else
{}
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end
# Perform refresh token request to auth provider.
# Updates the client's Token object and writes changes to
# configuration.
#
# @param [Boolean] use_basic_auth? When true, use basic auth authentication header
# @return [Boolean] success?
def refresh_token
debug { "Performing token refresh" }
return false if token.nil?
return false if token['refresh_token'].nil?
uri = URI.parse(token_account['token_endpoint'])
endpoint_data = { path: uri.path }
endpoint_data[:host] = uri.host if uri.host
endpoint_data[:port] = uri.port if uri.port
debug { "Token refresh endpoint: #{endpoint_data.inspect}" }
return false unless endpoint_data[:path]
response = request(
{
http_method: token_account['token_method'].downcase.to_sym,
body: refresh_request_params,
headers: {
CONTENT_TYPE => token_account['token_post_content_type']
}.merge(
token_account['code_requires_basic_auth'] ? basic_auth_header : {}
),
expects: [200, 201, 400, 401, 403],
auth: false
}.merge(endpoint_data)
)
if response && response['access_token']
debug { "Got response to refresh request" }
token['access_token'] = response['access_token']
token['refresh_token'] = response['refresh_token']
token['expires_at'] = in_to_at(response['expires_in'])
token.config.write if token.respond_to?(:config)
true
else
debug { "Got null or bad response to refresh request: #{last_response.inspect}" }
false
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end
private
# Returns true if the token object belongs to a master
#
# @return [Boolean]
def token_is_for_master?
token_account['name'] == 'master'
end
# Get prefixed request path unless path starts with /
#
# @param [String] path
# @return [String]
def path_with_prefix(path)
path.to_s.start_with?('/') ? path : "#{path_prefix}#{path}"
end
##
# Build request headers. Removes empty headers.
# @example
# request_headers('Authorization' => nil)
#
# @param [Hash] headers
# @return [Hash]
def request_headers(headers = {}, auth: true, gzip: true)
headers = default_headers.merge(headers)
headers.merge!(bearer_authorization_header) if auth
headers[ACCEPT_ENCODING] = GZIP if gzip
headers.reject{|_,v| v.nil? || (v.respond_to?(:empty?) && v.empty?)}
end
##
# Encode body based on content type.
#
# @param [Object] body
# @param [String] content_type
# @return [String] encoded_content
def encode_body(body, content_type)
if content_type =~ JSON_REGEX # vnd.api+json should pass as json
dump_json(body)
elsif content_type == CONTENT_URLENCODED && body.kind_of?(Hash)
URI.encode_www_form(body)
else
body
end
end
##
# Parse response. If the respons is JSON, returns a Hash representation.
# Otherwise returns the raw body.
#
# @param [Excon::Response]
# @return [Hash,String]
def parse_response(response)
check_version_and_warn(response.headers[X_KONTENA_VERSION])
if response.headers[CONTENT_TYPE] =~ JSON_REGEX
parse_json(response)
else
response.body
end
end
def check_version_and_warn(server_version)
return nil if $VERSION_WARNING_ADDED
return nil unless server_version.to_s =~ /^\d+\.\d+\.\d+/
unless server_version[/^(\d+\.\d+)/, 1] == Kontena::Cli::VERSION[/^(\d+\.\d+)/, 1] # Just compare x.y
add_version_warning(server_version)
$VERSION_WARNING_ADDED = true
end
end
def add_version_warning(server_version)
at_exit do
warn Kontena.pastel.yellow("Warning: Server version is #{server_version}. You are using CLI version #{Kontena::Cli::VERSION}.")
end
end
# Parse json
#
# @param response [Excon::Response]
# @return [Hash,Object,NilClass]
def parse_json(response)
return nil if response.body.empty?
JSON.parse(response.body)
rescue => ex
raise Kontena::Errors::StandardError.new(520, "Invalid response JSON from server for #{response.path}: #{ex.class.name}: #{ex.message}")
end
# Dump json
#
# @param [Object] obj
# @return [String]
def dump_json(obj)
JSON.dump(obj)
end
# @return [Boolean]
def ignore_ssl_errors?
ENV['SSL_IGNORE_ERRORS'] == 'true' || options[:ignore_ssl_errors]
end
# @param [Excon::Response] response
def handle_error_response(response)
data = parse_response(response)
request_path = " (#{response.path})"
if data.is_a?(Hash) && data.has_key?('error') && data['error'].is_a?(Hash)
raise Kontena::Errors::StandardErrorHash.new(response.status, response.reason_phrase, data['error'])
elsif data.is_a?(Hash) && data.has_key?('errors') && data['errors'].is_a?(Array) && data['errors'].all? { |e| e.is_a?(Hash) }
error_with_status = data['errors'].find { |error| error.key?('status') }
if error_with_status
status = error_with_status['status']
else
status = response.status
end
raise Kontena::Errors::StandardErrorHash.new(status, response.reason_phrase, data)
elsif data.is_a?(Hash) && data.has_key?('error')
raise Kontena::Errors::StandardError.new(response.status, data['error'] + request_path)
elsif data.is_a?(String) && !data.empty?
raise Kontena::Errors::StandardError.new(response.status, data + request_path)
else
raise Kontena::Errors::StandardError.new(response.status, response.reason_phrase + request_path)
end
end
# Convert expires_in into expires_at
#
# @param [Fixnum] seconds_till_expiration
# @return [Fixnum] expires_at_unix_timestamp
def in_to_at(expires_in)
if expires_in.to_i < 1
0
else
Time.now.utc.to_i + expires_in.to_i
end
end
end
|
igrigorik/http-2 | lib/http/2/connection.rb | HTTP2.Connection.encode_headers | ruby | def encode_headers(frame)
payload = frame[:payload]
payload = @compressor.encode(payload) unless payload.is_a? Buffer
frames = []
while payload.bytesize > 0
cont = frame.dup
cont[:type] = :continuation
cont[:flags] = []
cont[:payload] = payload.slice!(0, @remote_settings[:settings_max_frame_size])
frames << cont
end
if frames.empty?
frames = [frame]
else
frames.first[:type] = frame[:type]
frames.first[:flags] = frame[:flags] - [:end_headers]
frames.last[:flags] << :end_headers
end
frames
rescue StandardError => e
connection_error(:compression_error, e: e)
nil
end | Encode headers payload and update connection compressor state.
@param frame [Hash]
@return [Array of Frame] | train | https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/connection.rb#L636-L662 | class Connection
include FlowBuffer
include Emitter
include Error
# Connection state (:new, :closed).
attr_reader :state
# Size of current connection flow control window (by default, set to
# infinity, but is automatically updated on receipt of peer settings).
attr_reader :local_window
attr_reader :remote_window
alias window local_window
# Current settings value for local and peer
attr_reader :local_settings
attr_reader :remote_settings
# Pending settings value
# Sent but not ack'ed settings
attr_reader :pending_settings
# Number of active streams between client and server (reserved streams
# are not counted towards the stream limit).
attr_reader :active_stream_count
# Initializes new connection object.
#
def initialize(**settings)
@local_settings = DEFAULT_CONNECTION_SETTINGS.merge(settings)
@remote_settings = SPEC_DEFAULT_CONNECTION_SETTINGS.dup
@compressor = Header::Compressor.new(settings)
@decompressor = Header::Decompressor.new(settings)
@active_stream_count = 0
@streams = {}
@streams_recently_closed = {}
@pending_settings = []
@framer = Framer.new
@local_window_limit = @local_settings[:settings_initial_window_size]
@local_window = @local_window_limit
@remote_window_limit = @remote_settings[:settings_initial_window_size]
@remote_window = @remote_window_limit
@recv_buffer = Buffer.new
@send_buffer = []
@continuation = []
@error = nil
@h2c_upgrade = nil
@closed_since = nil
end
def closed?
@state == :closed
end
# Allocates new stream for current connection.
#
# @param priority [Integer]
# @param window [Integer]
# @param parent [Stream]
def new_stream(**args)
fail ConnectionClosed if @state == :closed
fail StreamLimitExceeded if @active_stream_count >= @remote_settings[:settings_max_concurrent_streams]
stream = activate_stream(id: @stream_id, **args)
@stream_id += 2
stream
end
# Sends PING frame to the peer.
#
# @param payload [String] optional payload must be 8 bytes long
# @param blk [Proc] callback to execute when PONG is received
def ping(payload, &blk)
send(type: :ping, stream: 0, payload: payload)
once(:ack, &blk) if blk
end
# Sends a GOAWAY frame indicating that the peer should stop creating
# new streams for current connection.
#
# Endpoints MAY append opaque data to the payload of any GOAWAY frame.
# Additional debug data is intended for diagnostic purposes only and
# carries no semantic value. Debug data MUST NOT be persistently stored,
# since it could contain sensitive information.
#
# @param error [Symbol]
# @param payload [String]
def goaway(error = :no_error, payload = nil)
last_stream = if (max = @streams.max)
max.first
else
0
end
send(type: :goaway, last_stream: last_stream,
error: error, payload: payload)
@state = :closed
@closed_since = Time.now
end
# Sends a WINDOW_UPDATE frame to the peer.
#
# @param increment [Integer]
def window_update(increment)
@local_window += increment
send(type: :window_update, stream: 0, increment: increment)
end
# Sends a connection SETTINGS frame to the peer.
# The values are reflected when the corresponding ACK is received.
#
# @param settings [Array or Hash]
def settings(payload)
payload = payload.to_a
connection_error if validate_settings(@local_role, payload)
@pending_settings << payload
send(type: :settings, stream: 0, payload: payload)
@pending_settings << payload
end
# Decodes incoming bytes into HTTP 2.0 frames and routes them to
# appropriate receivers: connection frames are handled directly, and
# stream frames are passed to appropriate stream objects.
#
# @param data [String] Binary encoded string
def receive(data)
@recv_buffer << data
# Upon establishment of a TCP connection and determination that
# HTTP/2.0 will be used by both peers, each endpoint MUST send a
# connection header as a final confirmation and to establish the
# initial settings for the HTTP/2.0 connection.
#
# Client connection header is 24 byte connection header followed by
# SETTINGS frame. Server connection header is SETTINGS frame only.
if @state == :waiting_magic
if @recv_buffer.size < 24
if !CONNECTION_PREFACE_MAGIC.start_with? @recv_buffer
fail HandshakeError
else
return # maybe next time
end
elsif @recv_buffer.read(24) == CONNECTION_PREFACE_MAGIC
# MAGIC is OK. Send our settings
@state = :waiting_connection_preface
payload = @local_settings.reject { |k, v| v == SPEC_DEFAULT_CONNECTION_SETTINGS[k] }
settings(payload)
else
fail HandshakeError
end
end
while (frame = @framer.parse(@recv_buffer))
emit(:frame_received, frame)
# Header blocks MUST be transmitted as a contiguous sequence of frames
# with no interleaved frames of any other type, or from any other stream.
unless @continuation.empty?
unless frame[:type] == :continuation && frame[:stream] == @continuation.first[:stream]
connection_error
end
@continuation << frame
return unless frame[:flags].include? :end_headers
payload = @continuation.map { |f| f[:payload] }.join
frame = @continuation.shift
@continuation.clear
frame.delete(:length)
frame[:payload] = Buffer.new(payload)
frame[:flags] << :end_headers
end
# SETTINGS frames always apply to a connection, never a single stream.
# The stream identifier for a settings frame MUST be zero. If an
# endpoint receives a SETTINGS frame whose stream identifier field is
# anything other than 0x0, the endpoint MUST respond with a connection
# error (Section 5.4.1) of type PROTOCOL_ERROR.
if connection_frame?(frame)
connection_management(frame)
else
case frame[:type]
when :headers
# When server receives even-numbered stream identifier,
# the endpoint MUST respond with a connection error of type PROTOCOL_ERROR.
connection_error if frame[:stream].even? && self.is_a?(Server)
# The last frame in a sequence of HEADERS/CONTINUATION
# frames MUST have the END_HEADERS flag set.
unless frame[:flags].include? :end_headers
@continuation << frame
return
end
# After sending a GOAWAY frame, the sender can discard frames
# for new streams. However, any frames that alter connection
# state cannot be completely ignored. For instance, HEADERS,
# PUSH_PROMISE and CONTINUATION frames MUST be minimally
# processed to ensure a consistent compression state
decode_headers(frame)
return if @state == :closed
stream = @streams[frame[:stream]]
if stream.nil?
stream = activate_stream(
id: frame[:stream],
weight: frame[:weight] || DEFAULT_WEIGHT,
dependency: frame[:dependency] || 0,
exclusive: frame[:exclusive] || false,
)
emit(:stream, stream)
end
stream << frame
when :push_promise
# The last frame in a sequence of PUSH_PROMISE/CONTINUATION
# frames MUST have the END_HEADERS flag set
unless frame[:flags].include? :end_headers
@continuation << frame
return
end
decode_headers(frame)
return if @state == :closed
# PUSH_PROMISE frames MUST be associated with an existing, peer-
# initiated stream... A receiver MUST treat the receipt of a
# PUSH_PROMISE on a stream that is neither "open" nor
# "half-closed (local)" as a connection error (Section 5.4.1) of
# type PROTOCOL_ERROR. Similarly, a receiver MUST treat the
# receipt of a PUSH_PROMISE that promises an illegal stream
# identifier (Section 5.1.1) (that is, an identifier for a stream
# that is not currently in the "idle" state) as a connection error
# (Section 5.4.1) of type PROTOCOL_ERROR, unless the receiver
# recently sent a RST_STREAM frame to cancel the associated stream.
parent = @streams[frame[:stream]]
pid = frame[:promise_stream]
# if PUSH parent is recently closed, RST_STREAM the push
if @streams_recently_closed[frame[:stream]]
send(type: :rst_stream, stream: pid, error: :refused_stream)
return
end
connection_error(msg: 'missing parent ID') if parent.nil?
unless parent.state == :open || parent.state == :half_closed_local
# An endpoint might receive a PUSH_PROMISE frame after it sends
# RST_STREAM. PUSH_PROMISE causes a stream to become "reserved".
# The RST_STREAM does not cancel any promised stream. Therefore, if
# promised streams are not desired, a RST_STREAM can be used to
# close any of those streams.
if parent.closed == :local_rst
# We can either (a) 'resurrect' the parent, or (b) RST_STREAM
# ... sticking with (b), might need to revisit later.
send(type: :rst_stream, stream: pid, error: :refused_stream)
else
connection_error
end
end
stream = activate_stream(id: pid, parent: parent)
emit(:promise, stream)
stream << frame
else
if (stream = @streams[frame[:stream]])
stream << frame
if frame[:type] == :data
update_local_window(frame)
calculate_window_update(@local_window_limit)
end
else
case frame[:type]
# The PRIORITY frame can be sent for a stream in the "idle" or
# "closed" state. This allows for the reprioritization of a
# group of dependent streams by altering the priority of an
# unused or closed parent stream.
when :priority
stream = activate_stream(
id: frame[:stream],
weight: frame[:weight] || DEFAULT_WEIGHT,
dependency: frame[:dependency] || 0,
exclusive: frame[:exclusive] || false,
)
emit(:stream, stream)
stream << frame
# WINDOW_UPDATE can be sent by a peer that has sent a frame
# bearing the END_STREAM flag. This means that a receiver could
# receive a WINDOW_UPDATE frame on a "half-closed (remote)" or
# "closed" stream. A receiver MUST NOT treat this as an error
# (see Section 5.1).
when :window_update
process_window_update(frame)
else
# An endpoint that receives an unexpected stream identifier
# MUST respond with a connection error of type PROTOCOL_ERROR.
connection_error
end
end
end
end
end
rescue StandardError => e
raise if e.is_a?(Error::Error)
connection_error(e: e)
end
def <<(*args)
receive(*args)
end
private
# Send an outgoing frame. DATA frames are subject to connection flow
# control and may be split and / or buffered based on current window size.
# All other frames are sent immediately.
#
# @note all frames are currently delivered in FIFO order.
# @param frame [Hash]
def send(frame)
emit(:frame_sent, frame)
if frame[:type] == :data
send_data(frame, true)
else
# An endpoint can end a connection at any time. In particular, an
# endpoint MAY choose to treat a stream error as a connection error.
if frame[:type] == :rst_stream && frame[:error] == :protocol_error
goaway(frame[:error])
else
# HEADERS and PUSH_PROMISE may generate CONTINUATION. Also send
# RST_STREAM that are not protocol errors
frames = encode(frame)
frames.each { |f| emit(:frame, f) }
end
end
end
# Applies HTTP 2.0 binary encoding to the frame.
#
# @param frame [Hash]
# @return [Array of Buffer] encoded frame
def encode(frame)
frames = if frame[:type] == :headers || frame[:type] == :push_promise
encode_headers(frame) # HEADERS and PUSH_PROMISE may create more than one frame
else
[frame] # otherwise one frame
end
frames.map { |f| @framer.generate(f) }
end
# Check if frame is a connection frame: SETTINGS, PING, GOAWAY, and any
# frame addressed to stream ID = 0.
#
# @param frame [Hash]
# @return [Boolean]
def connection_frame?(frame)
(frame[:stream]).zero? ||
frame[:type] == :settings ||
frame[:type] == :ping ||
frame[:type] == :goaway
end
# Process received connection frame (stream ID = 0).
# - Handle SETTINGS updates
# - Connection flow control (WINDOW_UPDATE)
# - Emit PONG auto-reply to PING frames
# - Mark connection as closed on GOAWAY
#
# @param frame [Hash]
def connection_management(frame)
case @state
when :waiting_connection_preface
# The first frame MUST be a SETTINGS frame at the start of a connection.
@state = :connected
connection_settings(frame)
when :connected
case frame[:type]
when :settings
connection_settings(frame)
when :window_update
@remote_window += frame[:increment]
send_data(nil, true)
when :ping
if frame[:flags].include? :ack
emit(:ack, frame[:payload])
else
send(type: :ping, stream: 0,
flags: [:ack], payload: frame[:payload])
end
when :goaway
# Receivers of a GOAWAY frame MUST NOT open additional streams on
# the connection, although a new connection can be established
# for new streams.
@state = :closed
@closed_since = Time.now
emit(:goaway, frame[:last_stream], frame[:error], frame[:payload])
when :altsvc
# 4. The ALTSVC HTTP/2 Frame
# An ALTSVC frame on stream 0 with empty (length 0) "Origin"
# information is invalid and MUST be ignored.
if frame[:origin] && !frame[:origin].empty?
emit(frame[:type], frame)
end
when :blocked
emit(frame[:type], frame)
else
connection_error
end
when :closed
connection_error if (Time.now - @closed_since) > 15
else
connection_error
end
end
# Validate settings parameters. See sepc Section 6.5.2.
#
# @param role [Symbol] The sender's role: :client or :server
# @return nil if no error. Exception object in case of any error.
def validate_settings(role, settings)
settings.each do |key, v|
case key
when :settings_header_table_size
# Any value is valid
when :settings_enable_push
case role
when :server
# Section 8.2
# Clients MUST reject any attempt to change the
# SETTINGS_ENABLE_PUSH setting to a value other than 0 by treating the
# message as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
return ProtocolError.new("invalid #{key} value") unless v.zero?
when :client
# Any value other than 0 or 1 MUST be treated as a
# connection error (Section 5.4.1) of type PROTOCOL_ERROR.
unless v.zero? || v == 1
return ProtocolError.new("invalid #{key} value")
end
end
when :settings_max_concurrent_streams
# Any value is valid
when :settings_initial_window_size
# Values above the maximum flow control window size of 2^31-1 MUST
# be treated as a connection error (Section 5.4.1) of type
# FLOW_CONTROL_ERROR.
unless v <= 0x7fffffff
return FlowControlError.new("invalid #{key} value")
end
when :settings_max_frame_size
# The initial value is 2^14 (16,384) octets. The value advertised
# by an endpoint MUST be between this initial value and the maximum
# allowed frame size (2^24-1 or 16,777,215 octets), inclusive.
# Values outside this range MUST be treated as a connection error
# (Section 5.4.1) of type PROTOCOL_ERROR.
unless v >= 16_384 && v <= 16_777_215
return ProtocolError.new("invalid #{key} value")
end
when :settings_max_header_list_size
# Any value is valid
# else # ignore unknown settings
end
end
nil
end
# Update connection settings based on parameters set by the peer.
#
# @param frame [Hash]
def connection_settings(frame)
connection_error unless frame[:type] == :settings && (frame[:stream]).zero?
# Apply settings.
# side =
# local: previously sent and pended our settings should be effective
# remote: just received peer settings should immediately be effective
settings, side = if frame[:flags].include?(:ack)
# Process pending settings we have sent.
[@pending_settings.shift, :local]
else
connection_error(check) if validate_settings(@remote_role, frame[:payload])
[frame[:payload], :remote]
end
settings.each do |key, v|
case side
when :local
@local_settings[key] = v
when :remote
@remote_settings[key] = v
end
case key
when :settings_max_concurrent_streams
# Do nothing.
# The value controls at the next attempt of stream creation.
when :settings_initial_window_size
# A change to SETTINGS_INITIAL_WINDOW_SIZE could cause the available
# space in a flow control window to become negative. A sender MUST
# track the negative flow control window, and MUST NOT send new flow
# controlled frames until it receives WINDOW_UPDATE frames that cause
# the flow control window to become positive.
case side
when :local
@local_window = @local_window - @local_window_limit + v
@streams.each do |_id, stream|
stream.emit(:local_window, stream.local_window - @local_window_limit + v)
end
@local_window_limit = v
when :remote
@remote_window = @remote_window - @remote_window_limit + v
@streams.each do |_id, stream|
# Event name is :window, not :remote_window
stream.emit(:window, stream.remote_window - @remote_window_limit + v)
end
@remote_window_limit = v
end
when :settings_header_table_size
# Setting header table size might cause some headers evicted
case side
when :local
@compressor.table_size = v
when :remote
@decompressor.table_size = v
end
when :settings_enable_push
# nothing to do
when :settings_max_frame_size
# nothing to do
# else # ignore unknown settings
end
end
case side
when :local
# Received a settings_ack. Notify application layer.
emit(:settings_ack, frame, @pending_settings.size)
when :remote
unless @state == :closed || @h2c_upgrade == :start
# Send ack to peer
send(type: :settings, stream: 0, payload: [], flags: [:ack])
end
end
end
# Decode headers payload and update connection decompressor state.
#
# The receiver endpoint reassembles the header block by concatenating
# the individual fragments, then decompresses the block to reconstruct
# the header set - aka, header payloads are buffered until END_HEADERS,
# or an END_PROMISE flag is seen.
#
# @param frame [Hash]
def decode_headers(frame)
if frame[:payload].is_a? Buffer
frame[:payload] = @decompressor.decode(frame[:payload])
end
rescue CompressionError => e
connection_error(:compression_error, e: e)
rescue ProtocolError => e
connection_error(:protocol_error, e: e)
rescue StandardError => e
connection_error(:internal_error, e: e)
end
# Encode headers payload and update connection compressor state.
#
# @param frame [Hash]
# @return [Array of Frame]
# Activates new incoming or outgoing stream and registers appropriate
# connection managemet callbacks.
#
# @param id [Integer]
# @param priority [Integer]
# @param window [Integer]
# @param parent [Stream]
def activate_stream(id: nil, **args)
connection_error(msg: 'Stream ID already exists') if @streams.key?(id)
stream = Stream.new({ connection: self, id: id }.merge(args))
# Streams that are in the "open" state, or either of the "half closed"
# states count toward the maximum number of streams that an endpoint is
# permitted to open.
stream.once(:active) { @active_stream_count += 1 }
stream.once(:close) do
@active_stream_count -= 1
# Store a reference to the closed stream, such that we can respond
# to any in-flight frames while close is registered on both sides.
# References to such streams will be purged whenever another stream
# is closed, with a minimum of 15s RTT time window.
@streams_recently_closed[id] = Time.now
to_delete = @streams_recently_closed.select { |_, v| (Time.now - v) > 15 }
to_delete.each do |stream_id|
@streams.delete stream_id
@streams_recently_closed.delete stream_id
end
end
stream.on(:promise, &method(:promise)) if self.is_a? Server
stream.on(:frame, &method(:send))
@streams[id] = stream
end
# Emit GOAWAY error indicating to peer that the connection is being
# aborted, and once sent, raise a local exception.
#
# @param error [Symbol]
# @option error [Symbol] :no_error
# @option error [Symbol] :internal_error
# @option error [Symbol] :flow_control_error
# @option error [Symbol] :stream_closed
# @option error [Symbol] :frame_too_large
# @option error [Symbol] :compression_error
# @param msg [String]
def connection_error(error = :protocol_error, msg: nil, e: nil)
goaway(error) unless @state == :closed || @state == :new
@state, @error = :closed, error
klass = error.to_s.split('_').map(&:capitalize).join
msg ||= e && e.message
backtrace = (e && e.backtrace) || []
fail Error.const_get(klass), msg, backtrace
end
alias error connection_error
def manage_state(_)
yield
end
end
|
cdarne/triton | lib/triton/messenger.rb | Triton.Messenger.remove_listener | ruby | def remove_listener(listener)
type = listener.type
if listeners.has_key? type
listeners[type].delete(listener)
listeners.delete(type) if listeners[type].empty?
end
end | Unregister the given block. It won't be call then went an event is emitted. | train | https://github.com/cdarne/triton/blob/196ce7784fc414d9751a3492427b506054203185/lib/triton/messenger.rb#L36-L42 | module Messenger
extend self # This make Messenger behave like a singleton
def listeners # this makes @listeners to be auto-initialized and accessed read-only
@listeners ||= Hash.new
end
# Register the given block to be called when the events of type +type+ will be emitted.
# if +once+, the block will be called once
def add_listener(type, once=false, &callback)
listener = Listener.new(type, callback, once)
listeners[type] ||= []
listeners[type] << listener
emit(:new_listener, self, type, once, callback)
listener
end
alias :on :add_listener
# Register the given block to be called only once when the events of type +type+ will be emitted.
def once(type, &callback)
add_listener(type, true, &callback)
end
# Unregister the given block. It won't be call then went an event is emitted.
# Unregister all the listener for the +type+ events.
# If +type+ is omitted, unregister *all* the listeners.
def remove_all_listeners(type=nil)
if type
listeners.delete(type)
else
listeners.clear
end
end
# Emit an event of type +type+ and call all the registered listeners to this event.
# The +sender+ param will help the listener to identify who is emitting the event.
# You can pass then every additional arguments you'll need
def emit(type, sender=nil, *args)
listeners[type].each { |l| l.fire(sender, *args) } if listeners.has_key? type
end
# Mixin that add shortcuts to emit events
module Emittable
def emit(type, *args)
Triton::Messenger.emit(type, self, *args)
end
end
# Mixin that add shortcuts to emit events
module Listenable
def add_listener(type, once=false, &listener)
Triton::Messenger.add_listener(type, once, &listener)
end
alias :on :add_listener
def once(type, &listener)
Triton::Messenger.once(type, &listener)
end
end
# The Listener class helps managing event triggering.
# It may not be used as its own.
class Listener
attr_accessor :type, :callback, :once
def initialize(type, callback, once=false)
@type = type
@callback = callback
@once = once
end
# Call the event listener passing through the +sender+ and the additional args
def fire(sender=nil, *args)
@callback.call(sender, *args)
if @once
Messenger::remove_listener(self)
end
end
end
end
|
zed-0xff/zpng | lib/zpng/image.rb | ZPNG.Image.crop! | ruby | def crop! params
decode_all_scanlines
x,y,h,w = (params[:x]||0), (params[:y]||0), params[:height], params[:width]
raise ArgumentError, "negative params not allowed" if [x,y,h,w].any?{ |x| x < 0 }
# adjust crop sizes if they greater than image sizes
h = self.height-y if (y+h) > self.height
w = self.width-x if (x+w) > self.width
raise ArgumentError, "negative params not allowed (p2)" if [x,y,h,w].any?{ |x| x < 0 }
# delete excess scanlines at tail
scanlines[(y+h)..-1] = [] if (y+h) < scanlines.size
# delete excess scanlines at head
scanlines[0,y] = [] if y > 0
# crop remaining scanlines
scanlines.each{ |l| l.crop!(x,w) }
# modify header
hdr.height, hdr.width = h, w
# return self
self
end | modifies this image | train | https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L430-L455 | class Image
attr_accessor :chunks, :scanlines, :imagedata, :extradata, :format, :verbose
# now only for (limited) BMP support
attr_accessor :color_class
include DeepCopyable
alias :clone :deep_copy
alias :dup :deep_copy
include BMP::Reader
PNG_HDR = "\x89PNG\x0d\x0a\x1a\x0a".force_encoding('binary')
BMP_HDR = "BM".force_encoding('binary')
# possible input params:
# IO of opened image file
# String with image file already readed
# Hash of image parameters to create new blank image
def initialize x, h={}
@chunks = []
@extradata = []
@color_class = Color
@format = :png
@verbose =
case h[:verbose]
when true; 1
when false; 0
else h[:verbose].to_i
end
case x
when IO
_from_io x
when String
_from_io StringIO.new(x)
when Hash
_from_hash x
else
raise NotSupported, "unsupported input data type #{x.class}"
end
if palette && hdr && hdr.depth
palette.max_colors = 2**hdr.depth
end
end
def inspect
"#<ZPNG::Image " +
%w'width height bpp chunks scanlines'.map do |k|
v = case (v = send(k))
when Array
"[#{v.size} entries]"
when String
v.size > 40 ? "[#{v.bytesize} bytes]" : v.inspect
else v.inspect
end
"#{k}=#{v}"
end.compact.join(", ") + ">"
end
def adam7
@adam7 ||= Adam7Decoder.new(self)
end
class << self
# load image from file
def load fname, h={}
open(fname,"rb") do |f|
self.new(f,h)
end
end
alias :load_file :load
alias :from_file :load # as in ChunkyPNG
end
# save image to file
def save fname, options={}
File.open(fname,"wb"){ |f| f << export(options) }
end
# flag that image is just created, and NOT loaded from file
# as in Rails' ActiveRecord::Base#new_record?
def new_image?
@new_image
end
alias :new? :new_image?
private
def _from_hash h
@new_image = true
@chunks << Chunk::IHDR.new(h)
if header.palette_used?
if h.key?(:palette)
if h[:palette]
@chunks << h[:palette]
else
# :palette => nil
# assume palette will be added later
end
else
@chunks << Chunk::PLTE.new
palette[0] = h[:background] || h[:bg] || Color::BLACK # add default bg color
end
end
end
def _read_png io
while !io.eof?
chunk = Chunk.from_stream(io)
chunk.idx = @chunks.size
@chunks << chunk
break if chunk.is_a?(Chunk::IEND)
end
end
def _from_io io
# Puts ios into binary mode.
# Once a stream is in binary mode, it cannot be reset to nonbinary mode.
io.binmode
hdr = io.read(BMP_HDR.size)
if hdr == BMP_HDR
_read_bmp io
else
hdr << io.read(PNG_HDR.size - BMP_HDR.size)
if hdr == PNG_HDR
_read_png io
else
raise NotSupported, "Unsupported header #{hdr.inspect} in #{io.inspect}"
end
end
unless io.eof?
offset = io.tell
@extradata << io.read
puts "[?] #{@extradata.last.size} bytes of extra data after image end (IEND), offset = 0x#{offset.to_s(16)}".red if @verbose >= 1
end
end
public
# internal helper method for color types 0 (grayscale) and 2 (truecolor)
def _alpha_color color
return nil unless trns
# For color type 0 (grayscale), the tRNS chunk contains a single gray level value, stored in the format:
#
# Gray: 2 bytes, range 0 .. (2^bitdepth)-1
#
# For color type 2 (truecolor), the tRNS chunk contains a single RGB color value, stored in the format:
#
# Red: 2 bytes, range 0 .. (2^bitdepth)-1
# Green: 2 bytes, range 0 .. (2^bitdepth)-1
# Blue: 2 bytes, range 0 .. (2^bitdepth)-1
#
# (If the image bit depth is less than 16, the least significant bits are used and the others are 0)
# Pixels of the specified gray level are to be treated as transparent (equivalent to alpha value 0);
# all other pixels are to be treated as fully opaque ( alpha = (2^bitdepth)-1 )
@alpha_color ||=
case hdr.color
when COLOR_GRAYSCALE
v = trns.data.unpack('n')[0] & (2**hdr.depth-1)
Color.from_grayscale(v, :depth => hdr.depth)
when COLOR_RGB
a = trns.data.unpack('n3').map{ |v| v & (2**hdr.depth-1) }
Color.new(*a, :depth => hdr.depth)
else
raise Exception, "color2alpha only intended for GRAYSCALE & RGB color modes"
end
color == @alpha_color ? 0 : (2**hdr.depth-1)
end
public
###########################################################################
# chunks access
def ihdr
@ihdr ||= @chunks.find{ |c| c.is_a?(Chunk::IHDR) }
end
alias :header :ihdr
alias :hdr :ihdr
def trns
# not used "@trns ||= ..." here b/c it will call find() each time of there's no TRNS chunk
defined?(@trns) ? @trns : (@trns=@chunks.find{ |c| c.is_a?(Chunk::TRNS) })
end
def plte
@plte ||= @chunks.find{ |c| c.is_a?(Chunk::PLTE) }
end
alias :palette :plte
###########################################################################
# image attributes
def bpp
ihdr && @ihdr.bpp
end
def width
ihdr && @ihdr.width
end
def height
ihdr && @ihdr.height
end
def grayscale?
ihdr && @ihdr.grayscale?
end
def interlaced?
ihdr && @ihdr.interlace != 0
end
def alpha_used?
ihdr && @ihdr.alpha_used?
end
private
def _imagedata
data_chunks = @chunks.find_all{ |c| c.is_a?(Chunk::IDAT) }
case data_chunks.size
when 0
# no imagedata chunks ?!
nil
when 1
# a single chunk - save memory and return a reference to its data
data_chunks[0].data
else
# multiple data chunks - join their contents
data_chunks.map(&:data).join
end
end
# unpack zlib,
# on errors keep going and try to return maximum possible data
def _safe_inflate data
zi = Zlib::Inflate.new
pos = 0; r = ''
begin
# save some memory by not using String#[] when not necessary
r << zi.inflate(pos==0 ? data : data[pos..-1])
if zi.total_in < data.size
@extradata << data[zi.total_in..-1]
puts "[?] #{@extradata.last.size} bytes of extra data after zlib stream".red if @verbose >= 1
end
# decompress OK
rescue Zlib::BufError
# tried to decompress, but got EOF - need more data
puts "[!] #{$!.inspect}".red if @verbose >= -1
# collect any remaining data in decompress buffer
r << zi.flush_next_out
rescue Zlib::DataError
puts "[!] #{$!.inspect}".red if @verbose >= -1
#p [pos, zi.total_in, zi.total_out, data.size, r.size]
r << zi.flush_next_out
# XXX TODO try to skip error and continue
# printf "[d] pos=%d/%d t_in=%d t_out=%d bytes_ok=%d\n".gray, pos, data.size,
# zi.total_in, zi.total_out, r.size
# if pos < zi.total_in
# pos = zi.total_in
# else
# pos += 1
# end
# pos = 0
# retry if pos < data.size
rescue Zlib::NeedDict
puts "[!] #{$!.inspect}".red if @verbose >= -1
# collect any remaining data in decompress buffer
r << zi.flush_next_out
end
r == "" ? nil : r
ensure
zi.close if zi && !zi.closed?
end
public
def imagedata
@imagedata ||=
begin
puts "[?] no image header, assuming non-interlaced RGB".yellow unless header
data = _imagedata
(data && data.size > 0) ? _safe_inflate(data) : ''
end
end
def imagedata_size
if new_image?
@scanlines.map(&:size).inject(&:+)
else
imagedata.size
end
end
# # try to get imagedata size in bytes, w/o storing entire decompressed
# # stream in memory. used in bin/zpng
# # result: less memory used on big images, but speed gain near 1-2% in best case,
# # and 2x slower in worst case because imagedata decoded 2 times
# def imagedata_size
# if @imagedata
# # already decompressed
# @imagedata.size
# else
# zi = nil
# @imagedata_size ||=
# begin
# zi = Zlib::Inflate.new(Zlib::MAX_WBITS)
# io = StringIO.new(_imagedata)
# while !io.eof? && !zi.finished?
# n = zi.inflate(io.read(16384))
# end
# zi.finish unless zi.finished?
# zi.total_out
# ensure
# zi.close if zi && !zi.closed?
# end
# end
# end
def metadata
@metadata ||= Metadata.new(self)
end
def [] x, y
# extracting this check into a module => +1-2% speed
x,y = adam7.convert_coords(x,y) if interlaced?
scanlines[y][x]
end
def []= x, y, newcolor
# extracting these checks into a module => +1-2% speed
decode_all_scanlines
x,y = adam7.convert_coords(x,y) if interlaced?
scanlines[y][x] = newcolor
end
# we must decode all scanlines before doing any modifications
# or scanlines decoded AFTER modification of UPPER ones will be decoded wrong
def decode_all_scanlines
return if @all_scanlines_decoded || new_image?
@all_scanlines_decoded = true
scanlines.each(&:decode!)
end
def scanlines
@scanlines ||=
begin
r = []
n = interlaced? ? adam7.scanlines_count : height.to_i
n.times do |i|
r << ScanLine.new(self,i)
end
r.delete_if(&:bad?)
r
end
end
def to_ascii *args
if scanlines.any?
if interlaced?
height.times.map{ |y| width.times.map{ |x| self[x,y].to_ascii(*args) }.join }.join("\n")
else
scanlines.map{ |l| l.to_ascii(*args) }.join("\n")
end
else
super()
end
end
def extract_block x,y=nil,w=nil,h=nil
if x.is_a?(Hash)
Block.new(self,x[:x], x[:y], x[:width], x[:height])
else
Block.new(self,x,y,w,h)
end
end
def each_block bw,bh, &block
0.upto(height/bh-1) do |by|
0.upto(width/bw-1) do |bx|
b = extract_block(bx*bw, by*bh, bw, bh)
yield b
end
end
end
def export options = {}
# allow :zlib_level => nil
options[:zlib_level] = 9 unless options.key?(:zlib_level)
if options.fetch(:repack, true)
data = Zlib::Deflate.deflate(scanlines.map(&:export).join, options[:zlib_level])
idats = @chunks.find_all{ |c| c.is_a?(Chunk::IDAT) }
case idats.size
when 0
# add new IDAT
@chunks << Chunk::IDAT.new( :data => data )
when 1
idats[0].data = data
else
idats[0].data = data
# delete other IDAT chunks
@chunks -= idats[1..-1]
end
end
unless @chunks.last.is_a?(Chunk::IEND)
# delete old IEND chunk(s) b/c IEND must be the last one
@chunks.delete_if{ |c| c.is_a?(Chunk::IEND) }
# add fresh new IEND
@chunks << Chunk::IEND.new
end
PNG_HDR + @chunks.map(&:export).join
end
# modifies this image
# returns new image
def crop params
decode_all_scanlines
# deep copy first, then crop!
deep_copy.crop!(params)
end
def pixels
Pixels.new(self)
end
def == other_image
return false unless other_image.is_a?(Image)
return false if width != other_image.width
return false if height != other_image.height
each_pixel do |c,x,y|
return false if c != other_image[x,y]
end
true
end
def each_pixel &block
height.times do |y|
width.times do |x|
yield(self[x,y], x, y)
end
end
end
# returns new deinterlaced image if deinterlaced
# OR returns self if no need to deinterlace
def deinterlace
return self unless interlaced?
# copy all but 'interlace' header params
h = Hash[*%w'width height depth color compression filter'.map{ |k| [k.to_sym, hdr.send(k)] }.flatten]
# don't auto-add palette chunk
h[:palette] = nil
# create new img
new_img = self.class.new h
# copy all but hdr/imagedata/end chunks
chunks.each do |chunk|
next if chunk.is_a?(Chunk::IHDR)
next if chunk.is_a?(Chunk::IDAT)
next if chunk.is_a?(Chunk::IEND)
new_img.chunks << chunk.deep_copy
end
# pixel-by-pixel copy
each_pixel do |c,x,y|
new_img[x,y] = c
end
new_img
end
end
|
hashicorp/vagrant | lib/vagrant/box.rb | Vagrant.Box.in_use? | ruby | def in_use?(index)
results = []
index.each do |entry|
box_data = entry.extra_data["box"]
next if !box_data
# If all the data matches, record it
if box_data["name"] == self.name &&
box_data["provider"] == self.provider.to_s &&
box_data["version"] == self.version.to_s
results << entry
end
end
return nil if results.empty?
results
end | Checks if this box is in use according to the given machine
index and returns the entries that appear to be using the box.
The entries returned, if any, are not tested for validity
with {MachineIndex::Entry#valid?}, so the caller should do that
if the caller cares.
@param [MachineIndex] index
@return [Array<MachineIndex::Entry>] | train | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L100-L116 | class Box
include Comparable
# Number of seconds to wait between checks for box updates
BOX_UPDATE_CHECK_INTERVAL = 3600
# The box name. This is the logical name used when adding the box.
#
# @return [String]
attr_reader :name
# This is the provider that this box is built for.
#
# @return [Symbol]
attr_reader :provider
# The version of this box.
#
# @return [String]
attr_reader :version
# This is the directory on disk where this box exists.
#
# @return [Pathname]
attr_reader :directory
# This is the metadata for the box. This is read from the "metadata.json"
# file that all boxes require.
#
# @return [Hash]
attr_reader :metadata
# This is the URL to the version info and other metadata for this
# box.
#
# @return [String]
attr_reader :metadata_url
# This is used to initialize a box.
#
# @param [String] name Logical name of the box.
# @param [Symbol] provider The provider that this box implements.
# @param [Pathname] directory The directory where this box exists on
# disk.
def initialize(name, provider, version, directory, **opts)
@name = name
@version = version
@provider = provider
@directory = directory
@metadata_url = opts[:metadata_url]
metadata_file = directory.join("metadata.json")
raise Errors::BoxMetadataFileNotFound, name: @name if !metadata_file.file?
begin
@metadata = JSON.parse(directory.join("metadata.json").read)
rescue JSON::ParserError
raise Errors::BoxMetadataCorrupted, name: @name
end
@logger = Log4r::Logger.new("vagrant::box")
end
# This deletes the box. This is NOT undoable.
def destroy!
# Delete the directory to delete the box.
FileUtils.rm_r(@directory)
# Just return true always
true
rescue Errno::ENOENT
# This means the directory didn't exist. Not a problem.
return true
end
# Checks if this box is in use according to the given machine
# index and returns the entries that appear to be using the box.
#
# The entries returned, if any, are not tested for validity
# with {MachineIndex::Entry#valid?}, so the caller should do that
# if the caller cares.
#
# @param [MachineIndex] index
# @return [Array<MachineIndex::Entry>]
# Loads the metadata URL and returns the latest metadata associated
# with this box.
#
# @param [Hash] download_options Options to pass to the downloader.
# @return [BoxMetadata]
def load_metadata(**download_options)
tf = Tempfile.new("vagrant-load-metadata")
tf.close
url = @metadata_url
if File.file?(url) || url !~ /^[a-z0-9]+:.*$/i
url = File.expand_path(url)
url = Util::Platform.cygwin_windows_path(url)
url = "file:#{url}"
end
opts = { headers: ["Accept: application/json"] }.merge(download_options)
Util::Downloader.new(url, tf.path, **opts).download!
BoxMetadata.new(File.open(tf.path, "r"))
rescue Errors::DownloaderError => e
raise Errors::BoxMetadataDownloadError,
message: e.extra_data[:message]
ensure
tf.unlink if tf
end
# Checks if the box has an update and returns the metadata, version,
# and provider. If the box doesn't have an update that satisfies the
# constraints, it will return nil.
#
# This will potentially make a network call if it has to load the
# metadata from the network.
#
# @param [String] version Version constraints the update must
# satisfy. If nil, the version constrain defaults to being a
# larger version than this box.
# @return [Array]
def has_update?(version=nil, download_options: {})
if !@metadata_url
raise Errors::BoxUpdateNoMetadata, name: @name
end
if download_options.delete(:automatic_check) && !automatic_update_check_allowed?
@logger.info("Skipping box update check")
return
end
version += ", " if version
version ||= ""
version += "> #{@version}"
md = self.load_metadata(download_options)
newer = md.version(version, provider: @provider)
return nil if !newer
[md, newer, newer.provider(@provider)]
end
# Check if a box update check is allowed. Uses a file
# in the box data directory to track when the last auto
# update check was performed and returns true if the
# BOX_UPDATE_CHECK_INTERVAL has passed.
#
# @return [Boolean]
def automatic_update_check_allowed?
check_path = directory.join("box_update_check")
if check_path.exist?
last_check_span = Time.now.to_i - check_path.mtime.to_i
if last_check_span < BOX_UPDATE_CHECK_INTERVAL
@logger.info("box update check is under the interval threshold")
return false
end
end
FileUtils.touch(check_path)
true
end
# This repackages this box and outputs it to the given path.
#
# @param [Pathname] path The full path (filename included) of where
# to output this box.
# @return [Boolean] true if this succeeds.
def repackage(path)
@logger.debug("Repackaging box '#{@name}' to: #{path}")
Util::SafeChdir.safe_chdir(@directory) do
# Find all the files in our current directory and tar it up!
files = Dir.glob(File.join(".", "**", "*")).select { |f| File.file?(f) }
# Package!
Util::Subprocess.execute("bsdtar", "-czf", path.to_s, *files)
end
@logger.info("Repackaged box '#{@name}' successfully: #{path}")
true
end
# Implemented for comparison with other boxes. Comparison is
# implemented by comparing names and providers.
def <=>(other)
return super if !other.is_a?(self.class)
# Comparison is done by composing the name and provider
"#{@name}-#{@version}-#{@provider}" <=>
"#{other.name}-#{other.version}-#{other.provider}"
end
end
|
david942j/seccomp-tools | lib/seccomp-tools/util.rb | SeccompTools.Util.supported_archs | ruby | def supported_archs
@supported_archs ||= Dir.glob(File.join(__dir__, 'consts', '*.rb'))
.map { |f| File.basename(f, '.rb').to_sym }
.sort
end | Get currently supported architectures.
@return [Array<Symbol>]
Architectures. | train | https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/util.rb#L9-L13 | module Util
module_function
# Get currently supported architectures.
# @return [Array<Symbol>]
# Architectures.
# Detect system architecture.
# @return [Symbol]
def system_arch
case RbConfig::CONFIG['host_cpu']
when /x86_64/ then :amd64
when /i386/ then :i386
else :unknown
end
end
# Enable colorize.
# @return [void]
def enable_color!
@disable_color = false
end
# Disable colorize.
# @return [void]
def disable_color!
@disable_color = true
end
# Is colorize enabled?
# @return [Boolean]
def colorize_enabled?
!@disable_color && $stdout.tty?
end
# Color codes for pretty print.
COLOR_CODE = {
esc_m: "\e[0m",
syscall: "\e[38;5;120m", # light green
arch: "\e[38;5;230m", # light yellow
gray: "\e[2m"
}.freeze
# Wrapper color codes.
# @param [String] s
# Contents to wrapper.
# @param [Symbol?] t
# Specific which kind of color to use, valid symbols are defined in {Util.COLOR_CODE}.
# @return [String]
# Wrapper with color codes.
def colorize(s, t: nil)
s = s.to_s
return s unless colorize_enabled?
cc = COLOR_CODE
color = cc[t]
"#{color}#{s.sub(cc[:esc_m], cc[:esc_m] + color)}#{cc[:esc_m]}"
end
# Get content of filename under directory templates/.
#
# @param [String] filename
# The filename.
#
# @return [String]
# Content of the file.
def template(filename)
IO.binread(File.join(__dir__, 'templates', filename))
end
end
|
ideonetwork/lato-blog | app/models/lato_blog/post.rb | LatoBlog.Post.check_lato_blog_post_parent | ruby | def check_lato_blog_post_parent
post_parent = LatoBlog::PostParent.find_by(id: lato_blog_post_parent_id)
if !post_parent
errors.add('Post parent', 'not exist for the post')
throw :abort
return
end
same_language_post = post_parent.posts.find_by(meta_language: meta_language)
if same_language_post && same_language_post.id != id
errors.add('Post parent', 'has another post for the same language')
throw :abort
return
end
end | This function check that the post parent exist and has not others post for the same language. | train | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/post.rb#L89-L103 | class Post < ApplicationRecord
include Post::EntityHelpers
include Post::SerializerHelpers
# Validations:
validates :title, presence: true, length: { maximum: 250 }
validates :meta_permalink, presence: true, uniqueness: true, length: { maximum: 250 }
validates :meta_status, presence: true, length: { maximum: 250 }, inclusion: { in: BLOG_POSTS_STATUS.values }
validates :meta_language, presence: true, length: { maximum: 250 }, inclusion: { in: ([nil] + BLOG_LANGUAGES_IDENTIFIER) }
# Relations:
belongs_to :post_parent, foreign_key: :lato_blog_post_parent_id,
class_name: 'LatoBlog::PostParent'
belongs_to :superuser_creator, foreign_key: :lato_core_superuser_creator_id,
class_name: 'LatoCore::Superuser'
has_many :post_fields, foreign_key: :lato_blog_post_id,
class_name: 'LatoBlog::PostField',
dependent: :destroy
has_many :category_relations, foreign_key: :lato_blog_post_id,
class_name: 'LatoBlog::CategoryPost',
dependent: :destroy
has_many :categories, through: :category_relations
has_many :tag_relations, foreign_key: :lato_blog_post_id,
class_name: 'LatoBlog::TagPost',
dependent: :destroy
has_many :tags, through: :tag_relations
# Scopes:
scope :published, -> { where(meta_status: BLOG_POSTS_STATUS[:published]) }
scope :drafted, -> { where(meta_status: BLOG_POSTS_STATUS[:drafted]) }
scope :deleted, -> { where(meta_status: BLOG_POSTS_STATUS[:deleted]) }
# Callbacks:
before_validation :check_meta_permalink, on: :create
before_save do
self.meta_permalink = meta_permalink.parameterize
meta_status.downcase!
meta_language.downcase!
check_lato_blog_post_parent
end
after_save do
blog__sync_config_post_fields_with_db_post_fields_for_post(self)
end
after_create do
add_to_default_category
end
after_destroy do
blog__clean_post_parents
end
private
# This function check if current permalink is valid. If it is not valid it
# generate a new from the post title.
def check_meta_permalink
candidate = (meta_permalink ? meta_permalink : title.parameterize)
accepted = nil
counter = 0
while accepted.nil?
if LatoBlog::Post.find_by(meta_permalink: candidate)
counter = counter + 1
candidate = "#{candidate}-#{counter}"
else
accepted = candidate
end
end
self.meta_permalink = accepted
end
# This function check that the post parent exist and has not others post for the same language.
# This function add the post to the default category.
def add_to_default_category
default_category_parent = LatoBlog::CategoryParent.find_by(meta_default: true)
return unless default_category_parent
category = default_category_parent.categories.find_by(meta_language: meta_language)
return unless category
LatoBlog::CategoryPost.create(lato_blog_post_id: id, lato_blog_category_id: category.id)
end
end
|
chef/mixlib-shellout | lib/mixlib/shellout.rb | Mixlib.ShellOut.gid | ruby | def gid
return group.kind_of?(Integer) ? group : Etc.getgrnam(group.to_s).gid if group
return Etc.getpwuid(uid).gid if using_login?
nil
end | The gid that the subprocess will switch to. If the group attribute is
given as a group name, it is converted to a gid by Etc.getgrnam
TODO migrate to shellout/unix.rb | train | https://github.com/chef/mixlib-shellout/blob/35f1d3636974838cd623c65f18b861fa2d16b777/lib/mixlib/shellout.rb#L219-L223 | class ShellOut
READ_WAIT_TIME = 0.01
READ_SIZE = 4096
DEFAULT_READ_TIMEOUT = 600
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
require "mixlib/shellout/windows"
include ShellOut::Windows
else
require "mixlib/shellout/unix"
include ShellOut::Unix
end
# User the command will run as. Normally set via options passed to new
attr_accessor :user
attr_accessor :domain
attr_accessor :password
# TODO remove
attr_accessor :with_logon
# Whether to simulate logon as the user. Normally set via options passed to new
# Always enabled on windows
attr_accessor :login
# Group the command will run as. Normally set via options passed to new
attr_accessor :group
# Working directory for the subprocess. Normally set via options to new
attr_accessor :cwd
# An Array of acceptable exit codes. #error? (and #error!) use this list
# to determine if the command was successful. Normally set via options to new
attr_accessor :valid_exit_codes
# When live_stdout is set, the stdout of the subprocess will be copied to it
# as the subprocess is running.
attr_accessor :live_stdout
# When live_stderr is set, the stderr of the subprocess will be copied to it
# as the subprocess is running.
attr_accessor :live_stderr
# ShellOut will push data from :input down the stdin of the subprocss.
# Normally set via options passed to new.
# Default: nil
attr_accessor :input
# If a logger is set, ShellOut will log a message before it executes the
# command.
attr_accessor :logger
# The log level at which ShellOut should log.
attr_accessor :log_level
# A string which will be prepended to the log message.
attr_accessor :log_tag
# The command to be executed.
attr_reader :command
# The umask that will be set for the subcommand.
attr_reader :umask
# Environment variables that will be set for the subcommand. Refer to the
# documentation of new to understand how ShellOut interprets this.
attr_accessor :environment
# The maximum time this command is allowed to run. Usually set via options
# to new
attr_writer :timeout
# The amount of time the subcommand took to execute
attr_reader :execution_time
# Data written to stdout by the subprocess
attr_reader :stdout
# Data written to stderr by the subprocess
attr_reader :stderr
# A Process::Status (or ducktype) object collected when the subprocess is
# reaped.
attr_reader :status
attr_reader :stdin_pipe, :stdout_pipe, :stderr_pipe, :process_status_pipe
# Runs windows process with elevated privileges. Required for Powershell commands which need elevated privileges
attr_accessor :elevated
attr_accessor :sensitive
# === Arguments:
# Takes a single command, or a list of command fragments. These are used
# as arguments to Kernel.exec. See the Kernel.exec documentation for more
# explanation of how arguments are evaluated. The last argument can be an
# options Hash.
# === Options:
# If the last argument is a Hash, it is removed from the list of args passed
# to exec and used as an options hash. The following options are available:
# * +user+: the user the commmand should run as. if an integer is given, it is
# used as a uid. A string is treated as a username and resolved to a uid
# with Etc.getpwnam
# * +group+: the group the command should run as. works similarly to +user+
# * +cwd+: the directory to chdir to before running the command
# * +umask+: a umask to set before running the command. If given as an Integer,
# be sure to use two leading zeros so it's parsed as Octal. A string will
# be treated as an octal integer
# * +returns+: one or more Integer values to use as valid exit codes for the
# subprocess. This only has an effect if you call +error!+ after
# +run_command+.
# * +environment+: a Hash of environment variables to set before the command
# is run.
# * +timeout+: a Numeric value for the number of seconds to wait on the
# child process before raising an Exception. This is calculated as the
# total amount of time that ShellOut waited on the child process without
# receiving any output (i.e., IO.select returned nil). Default is 600
# seconds. Note: the stdlib Timeout library is not used.
# * +input+: A String of data to be passed to the subcommand. This is
# written to the child process' stdin stream before the process is
# launched. The child's stdin stream will be a pipe, so the size of input
# data should not exceed the system's default pipe capacity (4096 bytes
# is a safe value, though on newer Linux systems the capacity is 64k by
# default).
# * +live_stream+: An IO or Logger-like object (must respond to the append
# operator +<<+) that will receive data as ShellOut reads it from the
# child process. Generally this is used to copy data from the child to
# the parent's stdout so that users may observe the progress of
# long-running commands.
# * +login+: Whether to simulate a login (set secondary groups, primary group, environment
# variables etc) as done by the OS in an actual login
# === Examples:
# Invoke find(1) to search for .rb files:
# find = Mixlib::ShellOut.new("find . -name '*.rb'")
# find.run_command
# # If all went well, the results are on +stdout+
# puts find.stdout
# # find(1) prints diagnostic info to STDERR:
# puts "error messages" + find.stderr
# # Raise an exception if it didn't exit with 0
# find.error!
# Run a command as the +www+ user with no extra ENV settings from +/tmp+
# cmd = Mixlib::ShellOut.new("apachectl", "start", :user => 'www', :env => nil, :cwd => '/tmp')
# cmd.run_command # etc.
def initialize(*command_args)
@stdout, @stderr, @process_status = "", "", ""
@live_stdout = @live_stderr = nil
@input = nil
@log_level = :debug
@log_tag = nil
@environment = {}
@cwd = nil
@valid_exit_codes = [0]
@terminate_reason = nil
@timeout = nil
@elevated = false
@sensitive = false
if command_args.last.is_a?(Hash)
parse_options(command_args.pop)
end
@command = command_args.size == 1 ? command_args.first : command_args
end
# Returns the stream that both is being used by both live_stdout and live_stderr, or nil
def live_stream
live_stdout == live_stderr ? live_stdout : nil
end
# A shortcut for setting both live_stdout and live_stderr, so that both the
# stdout and stderr from the subprocess will be copied to the same stream as
# the subprocess is running.
def live_stream=(stream)
@live_stdout = @live_stderr = stream
end
# Set the umask that the subprocess will have. If given as a string, it
# will be converted to an integer by String#oct.
def umask=(new_umask)
@umask = (new_umask.respond_to?(:oct) ? new_umask.oct : new_umask.to_i) & 007777
end
# The uid that the subprocess will switch to. If the user attribute was
# given as a username, it is converted to a uid by Etc.getpwnam
# TODO migrate to shellout/unix.rb
def uid
return nil unless user
user.kind_of?(Integer) ? user : Etc.getpwnam(user.to_s).uid
end
# The gid that the subprocess will switch to. If the group attribute is
# given as a group name, it is converted to a gid by Etc.getgrnam
# TODO migrate to shellout/unix.rb
def timeout
@timeout || DEFAULT_READ_TIMEOUT
end
# Creates a String showing the output of the command, including a banner
# showing the exact command executed. Used by +invalid!+ to show command
# results when the command exited with an unexpected status.
def format_for_exception
return "Command execution failed. STDOUT/STDERR suppressed for sensitive resource" if sensitive
msg = ""
msg << "#{@terminate_reason}\n" if @terminate_reason
msg << "---- Begin output of #{command} ----\n"
msg << "STDOUT: #{stdout.strip}\n"
msg << "STDERR: #{stderr.strip}\n"
msg << "---- End output of #{command} ----\n"
msg << "Ran #{command} returned #{status.exitstatus}" if status
msg
end
# The exit status of the subprocess. Will be nil if the command is still
# running or died without setting an exit status (e.g., terminated by
# `kill -9`).
def exitstatus
@status && @status.exitstatus
end
# Run the command, writing the command's standard out and standard error
# to +stdout+ and +stderr+, and saving its exit status object to +status+
# === Returns
# returns +self+; +stdout+, +stderr+, +status+, and +exitstatus+ will be
# populated with results of the command
# === Raises
# * Errno::EACCES when you are not privileged to execute the command
# * Errno::ENOENT when the command is not available on the system (or not
# in the current $PATH)
# * CommandTimeout when the command does not complete
# within +timeout+ seconds (default: 600s)
def run_command
if logger
log_message = (log_tag.nil? ? "" : "#{@log_tag} ") << "sh(#{@command})"
logger.send(log_level, log_message)
end
super
end
# Checks the +exitstatus+ against the set of +valid_exit_codes+.
# === Returns
# +true+ if +exitstatus+ is not in the list of +valid_exit_codes+, false
# otherwise.
def error?
!Array(valid_exit_codes).include?(exitstatus)
end
# If #error? is true, calls +invalid!+, which raises an Exception.
# === Returns
# nil::: always returns nil when it does not raise
# === Raises
# ::ShellCommandFailed::: via +invalid!+
def error!
invalid!("Expected process to exit with #{valid_exit_codes.inspect}, but received '#{exitstatus}'") if error?
end
# Raises a ShellCommandFailed exception, appending the
# command's stdout, stderr, and exitstatus to the exception message.
# === Arguments
# +msg+: A String to use as the basis of the exception message. The
# default explanation is very generic, providing a more informative message
# is highly encouraged.
# === Raises
# ShellCommandFailed always
def invalid!(msg = nil)
msg ||= "Command produced unexpected results"
raise ShellCommandFailed, msg + "\n" + format_for_exception
end
def inspect
"<#{self.class.name}##{object_id}: command: '#{@command}' process_status: #{@status.inspect} " +
"stdout: '#{stdout.strip}' stderr: '#{stderr.strip}' child_pid: #{@child_pid.inspect} " +
"environment: #{@environment.inspect} timeout: #{timeout} user: #{@user} group: #{@group} working_dir: #{@cwd} >"
end
private
def parse_options(opts)
opts.each do |option, setting|
case option.to_s
when "cwd"
self.cwd = setting
when "domain"
self.domain = setting
when "password"
self.password = setting
when "user"
self.user = setting
self.with_logon = setting
when "group"
self.group = setting
when "umask"
self.umask = setting
when "timeout"
self.timeout = setting
when "returns"
self.valid_exit_codes = Array(setting)
when "live_stream"
self.live_stdout = self.live_stderr = setting
when "live_stdout"
self.live_stdout = setting
when "live_stderr"
self.live_stderr = setting
when "input"
self.input = setting
when "logger"
self.logger = setting
when "log_level"
self.log_level = setting
when "log_tag"
self.log_tag = setting
when "environment", "env"
if setting
self.environment = Hash[setting.map { |(k, v)| [k.to_s, v] }]
else
self.environment = {}
end
when "login"
self.login = setting
when "elevated"
self.elevated = setting
when "sensitive"
self.sensitive = setting
else
raise InvalidCommandOption, "option '#{option.inspect}' is not a valid option for #{self.class.name}"
end
end
validate_options(opts)
end
def validate_options(opts)
if login && !user
raise InvalidCommandOption, "cannot set login without specifying a user"
end
super
end
end
|
tbuehlmann/ponder | lib/ponder/channel_list.rb | Ponder.ChannelList.remove_user | ruby | def remove_user(nick)
@mutex.synchronize do
channels = Set.new
@channels.each do |channel|
if channel.remove_user(nick)
channels << channel
end
end
channels
end
end | Removes a User from all Channels from the ChannelList.
Returning a Set of Channels in which the User was. | train | https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel_list.rb#L30-L42 | class ChannelList
attr_reader :channels
def initialize
@channels = Set.new
@mutex = Mutex.new
end
# Add a Channel to the ChannelList.
def add(channel)
@mutex.synchronize do
@channels << channel
end
end
# Removes a Channel from the ChannelList.
def remove(channel_or_channel_name)
@mutex.synchronize do
if channel_or_channel_name.is_a?(String)
channel_or_channel_name = find(channel_or_channel_name)
end
@channels.delete(channel_or_channel_name)
end
end
# Removes a User from all Channels from the ChannelList.
# Returning a Set of Channels in which the User was.
# Finding a Channel using the lowercased Channel name.
def find(channel_name)
@channels.find { |c| c.name.downcase == channel_name.downcase }
end
# Removes all Channels from the ChannelList and returns them.
def clear
@mutex.synchronize do
channels = @channels.dup
@channels.clear
channels
end
end
# Returns a Set of all Users that are in one of the Channels from the
# ChannelList.
def users
users = Set.new
@channels.each do |channel|
users.merge channel.users
end
users
end
end
|
bitbucket-rest-api/bitbucket | lib/bitbucket_rest_api/request.rb | BitBucket.Request._extract_mime_type | ruby | def _extract_mime_type(params, options) # :nodoc:
options['resource'] = params['resource'] ? params.delete('resource') : ''
options['mime_type'] = params['resource'] ? params.delete('mime_type') : ''
end | def extract_data_from_params(params) # :nodoc:
if params.has_key?('data') and !params['data'].nil?
params['data']
else
params
end
end | train | https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/request.rb#L70-L73 | module Request
METHODS = [:get, :post, :put, :delete, :patch]
METHODS_WITH_BODIES = [ :post, :put, :patch ]
def get_request(path, params={}, options={})
request(:get, path, params, options)
end
def patch_request(path, params={}, options={})
request(:patch, path, params, options)
end
def post_request(path, params={}, options={})
request(:post, path, params, options)
end
def put_request(path, params={}, options={})
request(:put, path, params, options)
end
def delete_request(path, params={}, options={})
request(:delete, path, params, options)
end
def request(method, path, params, options={})
if !METHODS.include?(method)
raise ArgumentError, "unkown http method: #{method}"
end
# _extract_mime_type(params, options)
puts "EXECUTED: #{method} - #{path} with #{params} and #{options}" if ENV['DEBUG']
conn = connection(options)
path = (conn.path_prefix + path).gsub(/\/\//,'/') if conn.path_prefix != '/'
response = conn.send(method) do |request|
request['Authorization'] = "Bearer #{new_access_token}" unless new_access_token.nil?
case method.to_sym
when *(METHODS - METHODS_WITH_BODIES)
request.body = params.delete('data') if params.has_key?('data')
request.url(path, params)
when *METHODS_WITH_BODIES
request.path = path
unless params.empty?
# data = extract_data_from_params(params)
# request.body = MultiJson.dump(data)
request.body = MultiJson.dump(params)
end
end
end
response.body
end
private
# def extract_data_from_params(params) # :nodoc:
# if params.has_key?('data') and !params['data'].nil?
# params['data']
# else
# params
# end
# end
end # Request
|
visoft/ruby_odata | lib/ruby_odata/service.rb | OData.Service.method_missing | ruby | def method_missing(name, *args)
# Queries
if @collections.include?(name.to_s)
@query = build_collection_query_object(name,@additional_params, *args)
return @query
# Adds
elsif name.to_s =~ /^AddTo(.*)/
type = $1
if @collections.include?(type)
@save_operations << Operation.new("Add", $1, args[0])
else
super
end
elsif @function_imports.include?(name.to_s)
execute_import_function(name.to_s, args)
else
super
end
end | Creates a new instance of the Service class
@param [String] service_uri the root URI of the OData service
@param [Hash] options the options to pass to the service
@option options [String] :username for http basic auth
@option options [String] :password for http basic auth
@option options [Object] :verify_ssl false if no verification, otherwise mode (OpenSSL::SSL::VERIFY_PEER is default)
@option options [Hash] :rest_options a hash of rest-client options that will be passed to all OData::Resource.new calls
@option options [Hash] :additional_params a hash of query string params that will be passed on all calls
@option options [Boolean, true] :eager_partial true if queries should consume partial feeds until the feed is complete, false if explicit calls to next must be performed
Handles the dynamic `AddTo<EntityName>` methods as well as the collections on the service | train | https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L24-L42 | class Service
attr_reader :classes, :class_metadata, :options, :collections, :edmx, :function_imports, :response
# Creates a new instance of the Service class
#
# @param [String] service_uri the root URI of the OData service
# @param [Hash] options the options to pass to the service
# @option options [String] :username for http basic auth
# @option options [String] :password for http basic auth
# @option options [Object] :verify_ssl false if no verification, otherwise mode (OpenSSL::SSL::VERIFY_PEER is default)
# @option options [Hash] :rest_options a hash of rest-client options that will be passed to all OData::Resource.new calls
# @option options [Hash] :additional_params a hash of query string params that will be passed on all calls
# @option options [Boolean, true] :eager_partial true if queries should consume partial feeds until the feed is complete, false if explicit calls to next must be performed
def initialize(service_uri, options = {})
@uri = service_uri.gsub!(/\/?$/, '')
set_options! options
default_instance_vars!
set_namespaces
build_collections_and_classes
end
# Handles the dynamic `AddTo<EntityName>` methods as well as the collections on the service
# Queues an object for deletion. To actually remove it from the server, you must call save_changes as well.
#
# @param [Object] obj the object to mark for deletion
#
# @raise [NotSupportedError] if the `obj` isn't a tracked entity
def delete_object(obj)
type = obj.class.to_s
if obj.respond_to?(:__metadata) && !obj.send(:__metadata).nil?
@save_operations << Operation.new("Delete", type, obj)
else
raise OData::NotSupportedError.new "You cannot delete a non-tracked entity"
end
end
# Queues an object for update. To actually update it on the server, you must call save_changes as well.
#
# @param [Object] obj the object to queue for update
#
# @raise [NotSupportedError] if the `obj` isn't a tracked entity
def update_object(obj)
type = obj.class.to_s
if obj.respond_to?(:__metadata) && !obj.send(:__metadata).nil?
@save_operations << Operation.new("Update", type, obj)
else
raise OData::NotSupportedError.new "You cannot update a non-tracked entity"
end
end
# Performs save operations (Create/Update/Delete) against the server
def save_changes
return nil if @save_operations.empty?
result = nil
begin
if @save_operations.length == 1
result = single_save(@save_operations[0])
else
result = batch_save(@save_operations)
end
# TODO: We should probably perform a check here
# to make sure everything worked before clearing it out
@save_operations.clear
return result
rescue Exception => e
handle_exception(e)
end
end
# Performs query operations (Read) against the server.
# Typically this returns an array of record instances, except in the case of count queries
# @raise [ServiceError] if there is an error when talking to the service
def execute
begin
@response = OData::Resource.new(build_query_uri, @rest_options).get
rescue Exception => e
handle_exception(e)
end
return Integer(@response.body) if @response.body =~ /\A\d+\z/
handle_collection_result(@response.body)
end
# Overridden to identify methods handled by method_missing
def respond_to?(method)
if @collections.include?(method.to_s)
return true
# Adds
elsif method.to_s =~ /^AddTo(.*)/
type = $1
if @collections.include?(type)
return true
else
super
end
# Function Imports
elsif @function_imports.include?(method.to_s)
return true
else
super
end
end
# Retrieves the next resultset of a partial result (if any). Does not honor the `:eager_partial` option.
def next
return if not partial?
handle_partial
end
# Does the most recent collection returned represent a partial collection? Will aways be false if a query hasn't executed, even if the query would have a partial
def partial?
@has_partial
end
# Lazy loads a navigation property on a model
#
# @param [Object] obj the object to fill
# @param [String] nav_prop the navigation property to fill
#
# @raise [NotSupportedError] if the `obj` isn't a tracked entity
# @raise [ArgumentError] if the `nav_prop` isn't a valid navigation property
def load_property(obj, nav_prop)
raise NotSupportedError, "You cannot load a property on an entity that isn't tracked" if obj.send(:__metadata).nil?
raise ArgumentError, "'#{nav_prop}' is not a valid navigation property" unless obj.respond_to?(nav_prop.to_sym)
raise ArgumentError, "'#{nav_prop}' is not a valid navigation property" unless @class_metadata[obj.class.to_s][nav_prop].nav_prop
results = OData::Resource.new(build_load_property_uri(obj, nav_prop), @rest_options).get
prop_results = build_classes_from_result(results.body)
obj.send "#{nav_prop}=", (singular?(nav_prop) ? prop_results.first : prop_results)
end
# Adds a child object to a parent object's collection
#
# @param [Object] parent the parent object
# @param [String] nav_prop the name of the navigation property to add the child to
# @param [Object] child the child object
# @raise [NotSupportedError] if the `parent` isn't a tracked entity
# @raise [ArgumentError] if the `nav_prop` isn't a valid navigation property
# @raise [NotSupportedError] if the `child` isn't a tracked entity
def add_link(parent, nav_prop, child)
raise NotSupportedError, "You cannot add a link on an entity that isn't tracked (#{parent.class})" if parent.send(:__metadata).nil?
raise ArgumentError, "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless parent.respond_to?(nav_prop.to_sym)
raise ArgumentError, "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless @class_metadata[parent.class.to_s][nav_prop].nav_prop
raise NotSupportedError, "You cannot add a link on a child entity that isn't tracked (#{child.class})" if child.send(:__metadata).nil?
@save_operations << Operation.new("AddLink", nav_prop, parent, child)
end
private
# Constructs a QueryBuilder instance for a collection using the arguments provided.
#
# @param [String] name the name of the collection
# @param [Hash] additional_parameters the additional parameters
# @param [Array] args the arguments to use for query
def build_collection_query_object(name, additional_parameters, *args)
root = "/#{name.to_s}"
if args.empty?
#nothing to add
elsif args.size == 1
if args.first.to_s =~ /\d+/
id_metadata = find_id_metadata(name.to_s)
root << build_id_path(args.first, id_metadata)
else
root << "(#{args.first})"
end
else
root << "(#{args.join(',')})"
end
QueryBuilder.new(root, additional_parameters)
end
# Finds the metadata associated with the given collection's first id property
# Remarks: This is used for single item lookup queries using the ID, e.g. Products(1), not complex primary keys
#
# @param [String] collection_name the name of the collection
def find_id_metadata(collection_name)
collection_data = @collections.fetch(collection_name)
class_metadata = @class_metadata.fetch(collection_data[:type].to_s)
key = class_metadata.select{|k,h| h.is_key }.collect{|k,h| h.name }[0]
class_metadata[key]
end
# Builds the ID expression of a given id for query
#
# @param [Object] id_value the actual value to be used
# @param [PropertyMetadata] id_metadata the property metadata object for the id
def build_id_path(id_value, id_metadata)
if id_metadata.type == "Edm.Int64"
"(#{id_value}L)"
else
"(#{id_value})"
end
end
def set_options!(options)
@options = options
if @options[:eager_partial].nil?
@options[:eager_partial] = true
end
@rest_options = { :verify_ssl => get_verify_mode, :user => @options[:username], :password => @options[:password] }
@rest_options.merge!(options[:rest_options] || {})
@additional_params = options[:additional_params] || {}
@namespace = options[:namespace]
@json_type = options[:json_type] || 'application/json'
end
def default_instance_vars!
@collections = {}
@function_imports = {}
@save_operations = []
@has_partial = false
@next_uri = nil
end
def set_namespaces
@edmx = Nokogiri::XML(OData::Resource.new(build_metadata_uri, @rest_options).get.body)
@ds_namespaces = {
"m" => "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"edmx" => "http://schemas.microsoft.com/ado/2007/06/edmx",
"ds" => "http://schemas.microsoft.com/ado/2007/08/dataservices",
"atom" => "http://www.w3.org/2005/Atom"
}
# Get the edm namespace from the edmx
edm_ns = @edmx.xpath("edmx:Edmx/edmx:DataServices/*", @namespaces).first.namespaces['xmlns'].to_s
@ds_namespaces.merge! "edm" => edm_ns
end
# Gets ssl certificate verification mode, or defaults to verify_peer
def get_verify_mode
if @options[:verify_ssl].nil?
return OpenSSL::SSL::VERIFY_PEER
else
return @options[:verify_ssl]
end
end
# Build the classes required by the metadata
def build_collections_and_classes
@classes = Hash.new
@class_metadata = Hash.new # This is used to store property information about a class
# Build complex types first, these will be used for entities
complex_types = @edmx.xpath("//edm:ComplexType", @ds_namespaces) || []
complex_types.each do |c|
name = qualify_class_name(c['Name'])
props = c.xpath(".//edm:Property", @ds_namespaces)
methods = props.collect { |p| p['Name'] } # Standard Properties
@classes[name] = ClassBuilder.new(name, methods, [], self, @namespace).build unless @classes.keys.include?(name)
end
entity_types = @edmx.xpath("//edm:EntityType", @ds_namespaces)
entity_types.each do |e|
next if e['Abstract'] == "true"
klass_name = qualify_class_name(e['Name'])
methods = collect_properties(klass_name, e, @edmx)
nav_props = collect_navigation_properties(klass_name, e, @edmx)
@classes[klass_name] = ClassBuilder.new(klass_name, methods, nav_props, self, @namespace).build unless @classes.keys.include?(klass_name)
end
# Fill in the collections instance variable
collections = @edmx.xpath("//edm:EntityContainer/edm:EntitySet", @ds_namespaces)
collections.each do |c|
entity_type = c["EntityType"]
@collections[c["Name"]] = { :edmx_type => entity_type, :type => convert_to_local_type(entity_type) }
end
build_function_imports
end
# Parses the function imports and fills the @function_imports collection
def build_function_imports
# Fill in the function imports
functions = @edmx.xpath("//edm:EntityContainer/edm:FunctionImport", @ds_namespaces)
functions.each do |f|
http_method_attribute = f.xpath("@m:HttpMethod", @ds_namespaces).first # HttpMethod is no longer required http://www.odata.org/2011/10/actions-in-odata/
is_side_effecting_attribute = f.xpath("@edm:IsSideEffecting", @ds_namespaces).first
http_method = 'POST' # default to POST
if http_method_attribute
http_method = http_method_attribute.content
elsif is_side_effecting_attribute
is_side_effecting = is_side_effecting_attribute.content
http_method = is_side_effecting ? 'POST' : 'GET'
end
return_type = f["ReturnType"]
inner_return_type = nil
unless return_type.nil?
return_type = (return_type =~ /^Collection/) ? Array : convert_to_local_type(return_type)
if f["ReturnType"] =~ /\((.*)\)/
inner_return_type = convert_to_local_type($~[1])
end
end
params = f.xpath("edm:Parameter", @ds_namespaces)
parameters = nil
if params.length > 0
parameters = {}
params.each do |p|
parameters[p["Name"]] = p["Type"]
end
end
@function_imports[f["Name"]] = {
:http_method => http_method,
:return_type => return_type,
:inner_return_type => inner_return_type,
:parameters => parameters }
end
end
# Converts the EDMX model type to the local model type
def convert_to_local_type(edmx_type)
return edm_to_ruby_type(edmx_type) if edmx_type =~ /^Edm/
klass_name = qualify_class_name(edmx_type.split('.').last)
klass_name.camelize.constantize
end
# Converts a class name to its fully qualified name (if applicable) and returns the new name
def qualify_class_name(klass_name)
unless @namespace.nil? || @namespace.blank? || klass_name.include?('::')
namespaces = @namespace.split(/\.|::/)
namespaces << klass_name
klass_name = namespaces.join '::'
end
klass_name.camelize
end
# Builds the metadata need for each property for things like feed customizations and navigation properties
def build_property_metadata(props, keys=[])
metadata = {}
props.each do |property_element|
prop_meta = PropertyMetadata.new(property_element)
prop_meta.is_key = keys.include?(prop_meta.name)
# If this is a navigation property, we need to add the association to the property metadata
prop_meta.association = Association.new(property_element, @edmx) if prop_meta.nav_prop
metadata[prop_meta.name] = prop_meta
end
metadata
end
# Handle parsing of OData Atom result and return an array of Entry classes
def handle_collection_result(result)
results = build_classes_from_result(result)
while partial? && @options[:eager_partial]
results.concat handle_partial
end
results
end
# Handles errors from the OData service
def handle_exception(e)
raise e unless defined?(e.response) && e.response != nil
code = e.response[:status]
error = Nokogiri::XML(e.response[:body])
message = if error.xpath("m:error/m:message", @ds_namespaces).first
error.xpath("m:error/m:message", @ds_namespaces).first.content
else
"Server returned error but no message."
end
raise ServiceError.new(code), message
end
# Loops through the standard properties (non-navigation) for a given class and returns the appropriate list of methods
def collect_properties(klass_name, element, doc)
props = element.xpath(".//edm:Property", @ds_namespaces)
key_elemnts = element.xpath(".//edm:Key//edm:PropertyRef", @ds_namespaces)
keys = key_elemnts.collect { |k| k['Name'] }
@class_metadata[klass_name] = build_property_metadata(props, keys)
methods = props.collect { |p| p['Name'] }
unless element["BaseType"].nil?
base = element["BaseType"].split(".").last()
baseType = doc.xpath("//edm:EntityType[@Name=\"#{base}\"]", @ds_namespaces).first()
props = baseType.xpath(".//edm:Property", @ds_namespaces)
@class_metadata[klass_name].merge!(build_property_metadata(props))
methods = methods.concat(props.collect { |p| p['Name']})
end
methods
end
# Similar to +collect_properties+, but handles the navigation properties
def collect_navigation_properties(klass_name, element, doc)
nav_props = element.xpath(".//edm:NavigationProperty", @ds_namespaces)
@class_metadata[klass_name].merge!(build_property_metadata(nav_props))
nav_props.collect { |p| p['Name'] }
end
# Helper to loop through a result and create an instance for each entity in the results
def build_classes_from_result(result)
doc = Nokogiri::XML(result)
is_links = doc.at_xpath("/ds:links", @ds_namespaces)
return parse_link_results(doc) if is_links
entries = doc.xpath("//atom:entry[not(ancestor::atom:entry)]", @ds_namespaces)
extract_partial(doc)
results = []
entries.each do |entry|
results << entry_to_class(entry)
end
return results
end
# Converts an XML Entry into a class
def entry_to_class(entry)
# Retrieve the class name from the fully qualified name (the last string after the last dot)
klass_name = entry.xpath("./atom:category/@term", @ds_namespaces).to_s.split('.')[-1]
# Is the category missing? See if there is a title that we can use to build the class
if klass_name.nil?
title = entry.xpath("./atom:title", @ds_namespaces).first
return nil if title.nil?
klass_name = title.content.to_s
end
return nil if klass_name.nil?
properties = entry.xpath("./atom:content/m:properties/*", @ds_namespaces)
klass = @classes[qualify_class_name(klass_name)].new
# Fill metadata
meta_id = entry.xpath("./atom:id", @ds_namespaces)[0].content
klass.send :__metadata=, { :uri => meta_id }
# Fill properties
for prop in properties
prop_name = prop.name
klass.send "#{prop_name}=", parse_value_xml(prop)
end
# Fill properties represented outside of the properties collection
@class_metadata[qualify_class_name(klass_name)].select { |k,v| v.fc_keep_in_content == false }.each do |k, meta|
if meta.fc_target_path == "SyndicationTitle"
title = entry.xpath("./atom:title", @ds_namespaces).first
klass.send "#{meta.name}=", title.content
elsif meta.fc_target_path == "SyndicationSummary"
summary = entry.xpath("./atom:summary", @ds_namespaces).first
klass.send "#{meta.name}=", summary.content
end
end
inline_links = entry.xpath("./atom:link[m:inline]", @ds_namespaces)
for link in inline_links
# TODO: Use the metadata's associations to determine the multiplicity instead of this "hack"
property_name = link.attributes['title'].to_s
if singular?(property_name)
inline_entry = link.xpath("./m:inline/atom:entry", @ds_namespaces).first
inline_klass = build_inline_class(klass, inline_entry, property_name)
klass.send "#{property_name}=", inline_klass
else
inline_classes, inline_entries = [], link.xpath("./m:inline/atom:feed/atom:entry", @ds_namespaces)
for inline_entry in inline_entries
# Build the class
inline_klass = entry_to_class(inline_entry)
# Add the property to the temp collection
inline_classes << inline_klass
end
# Assign the array of classes to the property
property_name = link.xpath("@title", @ds_namespaces)
klass.send "#{property_name}=", inline_classes
end
end
klass
end
# Tests for and extracts the next href of a partial
def extract_partial(doc)
next_links = doc.xpath('//atom:link[@rel="next"]', @ds_namespaces)
@has_partial = next_links.any?
if @has_partial
uri = Addressable::URI.parse(next_links[0]['href'])
uri.query_values = uri.query_values.merge @additional_params unless @additional_params.empty?
@next_uri = uri.to_s
end
end
def handle_partial
if @next_uri
result = OData::Resource.new(@next_uri, @rest_options).get
results = handle_collection_result(result.body)
end
results
end
# Handle link results
def parse_link_results(doc)
uris = doc.xpath("/ds:links/ds:uri", @ds_namespaces)
results = []
uris.each do |uri_el|
link = uri_el.content
results << URI.parse(link)
end
results
end
# Build URIs
def build_metadata_uri
uri = "#{@uri}/$metadata"
uri << "?#{@additional_params.to_query}" unless @additional_params.empty?
uri
end
def build_query_uri
"#{@uri}#{@query.query}"
end
def build_save_uri(operation)
uri = "#{@uri}/#{operation.klass_name}"
uri << "?#{@additional_params.to_query}" unless @additional_params.empty?
uri
end
def build_add_link_uri(operation)
uri = operation.klass.send(:__metadata)[:uri].dup
uri << "/$links/#{operation.klass_name}"
uri << "?#{@additional_params.to_query}" unless @additional_params.empty?
uri
end
def build_resource_uri(operation)
uri = operation.klass.send(:__metadata)[:uri].dup
uri << "?#{@additional_params.to_query}" unless @additional_params.empty?
uri
end
def build_batch_uri
uri = "#{@uri}/$batch"
uri << "?#{@additional_params.to_query}" unless @additional_params.empty?
uri
end
def build_load_property_uri(obj, property)
uri = obj.__metadata[:uri].dup
uri << "/#{property}"
uri
end
def build_function_import_uri(name, params)
uri = "#{@uri}/#{name}"
params.merge! @additional_params
uri << "?#{params.to_query}" unless params.empty?
uri
end
def build_inline_class(klass, entry, property_name)
# Build the class
inline_klass = entry_to_class(entry)
# Add the property
klass.send "#{property_name}=", inline_klass
end
# Used to link a child object to its parent and vice-versa after a add_link operation
def link_child_to_parent(operation)
child_collection = operation.klass.send("#{operation.klass_name}") || []
child_collection << operation.child_klass
operation.klass.send("#{operation.klass_name}=", child_collection)
# Attach the parent to the child
parent_meta = @class_metadata[operation.klass.class.to_s][operation.klass_name]
child_meta = @class_metadata[operation.child_klass.class.to_s]
# Find the matching relationship on the child object
child_properties = Helpers.normalize_to_hash(
child_meta.select { |k, prop|
prop.nav_prop &&
prop.association.relationship == parent_meta.association.relationship })
child_property_to_set = child_properties.keys.first # There should be only one match
# TODO: Handle many to many scenarios where the child property is an enumerable
operation.child_klass.send("#{child_property_to_set}=", operation.klass)
end
def single_save(operation)
if operation.kind == "Add"
save_uri = build_save_uri(operation)
json_klass = operation.klass.to_json(:type => :add)
post_result = OData::Resource.new(save_uri, @rest_options).post json_klass, {:content_type => @json_type}
return build_classes_from_result(post_result.body)
elsif operation.kind == "Update"
update_uri = build_resource_uri(operation)
json_klass = operation.klass.to_json
update_result = OData::Resource.new(update_uri, @rest_options).put json_klass, {:content_type => @json_type}
return (update_result.status == 204)
elsif operation.kind == "Delete"
delete_uri = build_resource_uri(operation)
delete_result = OData::Resource.new(delete_uri, @rest_options).delete
return (delete_result.status == 204)
elsif operation.kind == "AddLink"
save_uri = build_add_link_uri(operation)
json_klass = operation.child_klass.to_json(:type => :link)
post_result = OData::Resource.new(save_uri, @rest_options).post json_klass, {:content_type => @json_type}
# Attach the child to the parent
link_child_to_parent(operation) if (post_result.status == 204)
return(post_result.status == 204)
end
end
# Batch Saves
def generate_guid
rand(36**12).to_s(36).insert(4, "-").insert(9, "-")
end
def batch_save(operations)
batch_num = generate_guid
changeset_num = generate_guid
batch_uri = build_batch_uri
body = build_batch_body(operations, batch_num, changeset_num)
result = OData::Resource.new( batch_uri, @rest_options).post body, {:content_type => "multipart/mixed; boundary=batch_#{batch_num}"}
# TODO: More result validation needs to be done.
# The result returns HTTP 202 even if there is an error in the batch
return (result.status == 202)
end
def build_batch_body(operations, batch_num, changeset_num)
# Header
body = "--batch_#{batch_num}\n"
body << "Content-Type: multipart/mixed;boundary=changeset_#{changeset_num}\n\n"
# Operations
operations.each do |operation|
body << build_batch_operation(operation, changeset_num)
body << "\n"
end
# Footer
body << "\n\n--changeset_#{changeset_num}--\n"
body << "--batch_#{batch_num}--"
return body
end
def build_batch_operation(operation, changeset_num)
accept_headers = "Accept-Charset: utf-8\n"
accept_headers << "Content-Type: application/json;charset=utf-8\n" unless operation.kind == "Delete"
accept_headers << "\n"
content = "--changeset_#{changeset_num}\n"
content << "Content-Type: application/http\n"
content << "Content-Transfer-Encoding: binary\n\n"
if operation.kind == "Add"
save_uri = "#{@uri}/#{operation.klass_name}"
json_klass = operation.klass.to_json(:type => :add)
content << "POST #{save_uri} HTTP/1.1\n"
content << accept_headers
content << json_klass
elsif operation.kind == "Update"
update_uri = operation.klass.send(:__metadata)[:uri]
json_klass = operation.klass.to_json
content << "PUT #{update_uri} HTTP/1.1\n"
content << accept_headers
content << json_klass
elsif operation.kind == "Delete"
delete_uri = operation.klass.send(:__metadata)[:uri]
content << "DELETE #{delete_uri} HTTP/1.1\n"
content << accept_headers
elsif
save_uri = build_add_link_uri(operation)
json_klass = operation.child_klass.to_json(:type => :link)
content << "POST #{save_uri} HTTP/1.1\n"
content << accept_headers
content << json_klass
link_child_to_parent(operation)
end
return content
end
# Complex Types
def complex_type_to_class(complex_type_xml)
type = Helpers.get_namespaced_attribute(complex_type_xml, 'type', 'm')
is_collection = false
# Extract the class name in case this is a Collection
if type =~ /\(([^)]*)\)/m
type = $~[1]
is_collection = true
collection = []
end
klass_name = qualify_class_name(type.split('.')[-1])
if is_collection
# extract the elements from the collection
elements = complex_type_xml.xpath(".//d:element", @namespaces)
elements.each do |e|
if type.match(/^Edm/)
collection << parse_value(e.content, type)
else
element = @classes[klass_name].new
fill_complex_type_properties(e, element)
collection << element
end
end
return collection
else
klass = @classes[klass_name].new
# Fill in the properties
fill_complex_type_properties(complex_type_xml, klass)
return klass
end
end
# Helper method for complex_type_to_class
def fill_complex_type_properties(complex_type_xml, klass)
properties = complex_type_xml.xpath(".//*")
properties.each do |prop|
klass.send "#{prop.name}=", parse_value_xml(prop)
end
end
# Field Converters
# Handles parsing datetimes from a string
def parse_date(sdate)
# Assume this is UTC if no timezone is specified
sdate = sdate + "Z" unless sdate.match(/Z|([+|-]\d{2}:\d{2})$/)
# This is to handle older versions of Ruby (e.g. ruby 1.8.7 (2010-12-23 patchlevel 330) [i386-mingw32])
# See http://makandra.com/notes/1017-maximum-representable-value-for-a-ruby-time-object
# In recent versions of Ruby, Time has a much larger range
begin
result = Time.parse(sdate)
rescue ArgumentError
result = DateTime.parse(sdate)
end
return result
end
# Parses a value into the proper type based on an xml property element
def parse_value_xml(property_xml)
property_type = Helpers.get_namespaced_attribute(property_xml, 'type', 'm')
property_null = Helpers.get_namespaced_attribute(property_xml, 'null', 'm')
if property_type.nil? || (property_type && property_type.match(/^Edm/))
return parse_value(property_xml.content, property_type, property_null)
end
complex_type_to_class(property_xml)
end
def parse_value(content, property_type = nil, property_null = nil)
# Handle anything marked as null
return nil if !property_null.nil? && property_null == "true"
# Handle a nil property type, this is a string
return content if property_type.nil?
# Handle integers
return content.to_i if property_type.match(/^Edm.Int/)
# Handle decimals
return content.to_d if property_type.match(/Edm.Decimal/)
# Handle DateTimes
# return Time.parse(property_xml.content) if property_type.match(/Edm.DateTime/)
return parse_date(content) if property_type.match(/Edm.DateTime/)
# If we can't parse the value, just return the element's content
content
end
# Parses a value into the proper type based on a specified return type
def parse_primative_type(value, return_type)
return value.to_i if return_type == Fixnum
return value.to_d if return_type == Float
return parse_date(value.to_s) if return_type == Time
return value.to_s
end
# Converts an edm type (string) to a ruby type
def edm_to_ruby_type(edm_type)
return String if edm_type =~ /Edm.String/
return Fixnum if edm_type =~ /^Edm.Int/
return Float if edm_type =~ /Edm.Decimal/
return Time if edm_type =~ /Edm.DateTime/
return String
end
# Method Missing Handlers
# Executes an import function
def execute_import_function(name, *args)
func = @function_imports[name]
# Check the args making sure that more weren't passed in than the function needs
param_count = func[:parameters].nil? ? 0 : func[:parameters].count
arg_count = args.nil? ? 0 : args[0].count
if arg_count > param_count
raise ArgumentError, "wrong number of arguments (#{arg_count} for #{param_count})"
end
# Convert the parameters to a hash
params = {}
func[:parameters].keys.each_with_index { |key, i| params[key] = args[0][i] } unless func[:parameters].nil?
function_uri = build_function_import_uri(name, params)
result = OData::Resource.new(function_uri, @rest_options).send(func[:http_method].downcase, {})
# Is this a 204 (No content) result?
return true if result.status == 204
# No? Then we need to parse the results. There are 4 kinds...
if func[:return_type] == Array
# a collection of entites
return build_classes_from_result(result.body) if @classes.include?(func[:inner_return_type].to_s)
# a collection of native types
elements = Nokogiri::XML(result.body).xpath("//ds:element", @ds_namespaces)
results = []
elements.each do |e|
results << parse_primative_type(e.content, func[:inner_return_type])
end
return results
end
# a single entity
if @classes.include?(func[:return_type].to_s)
entry = Nokogiri::XML(result.body).xpath("atom:entry[not(ancestor::atom:entry)]", @ds_namespaces)
return entry_to_class(entry)
end
# or a single native type
unless func[:return_type].nil?
e = Nokogiri::XML(result.body).xpath("/*").first
return parse_primative_type(e.content, func[:return_type])
end
# Nothing could be parsed, so just return if we got a 200 or not
return (result.status == 200)
end
# Helpers
def singular?(value)
value.singularize == value
end
end
|
iyuuya/jkf | lib/jkf/parser/kif.rb | Jkf::Parser.Kif.parse_fugou | ruby | def parse_fugou
s0 = @current_pos
s1 = parse_place
if s1 != :failed
s2 = parse_piece
if s2 != :failed
s3 = match_str("成")
s3 = nil if s3 == :failed
@reported_pos = s0
s0 = { "to" => s1, "piece" => s2, "promote" => !!s3 }
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
s0
end | fugou : place piece "成"? | train | https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kif.rb#L276-L295 | class Kif < Base
include Kifuable
protected
# kifu : skipline* header* initialboard? header* split? moves fork* nl?
def parse_root
@input += "\n" unless @input.end_with?("\n")
s0 = @current_pos
s1 = []
s2 = parse_skipline
while s2 != :failed
s1 << s2
s2 = parse_skipline
end
s2 = []
s3 = parse_header
while s3 != :failed
s2 << s3
s3 = parse_header
end
s3 = parse_initialboard
s3 = nil if s3 == :failed
s4 = []
s5 = parse_header
while s5 != :failed
s4 << s5
s5 = parse_header
end
parse_split
s6 = parse_moves
if s6 != :failed
s7 = []
s8 = parse_fork
while s8 != :failed
s7 << s8
s8 = parse_fork
end
parse_nl
@reported_pos = s0
s0 = transform_root(s2, s3, s4, s6, s7)
else
@current_pos = s0
s0 = :failed
end
s0
end
# header : [^:\r\n]+ ":" nonls nl
# | turn "手番" nl
# | "盤面回転" nl
def parse_header
s0 = @current_pos
s2 = match_regexp(/^[^:\r\n]/)
if s2 != :failed
s1 = []
while s2 != :failed
s1 << s2
s2 = match_regexp(/^[^:\r\n]/)
end
else
s1 = :failed
end
if s1 != :failed
if match_str(":") != :failed
s3 = parse_nonls
if parse_nl != :failed
@reported_pos = s0
s1 = { "k" => s1.join, "v" => s3.join }
s0 = s1
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
if s0 == :failed
s0 = @current_pos
s1 = parse_turn
if s1 != :failed
if match_str("手番") != :failed
if parse_nl != :failed
@reported_pos = s0
s0 = { "k" => "手番", "v" => s1 }
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
if s0 == :failed
s0 = @current_pos
if match_str("盤面回転") != :failed
if parse_nl != :failed
@reported_pos = s0
s0 = nil
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
end
end
s0
end
# turn : [先後上下]
def parse_turn
match_regexp(/^[先後上下]/)
end
# split : "手数----指手--" "-------消費時間--"? nl
def parse_split
s0 = @current_pos
s1 = match_str("手数----指手--")
if s1 != :failed
s2 = match_str("-------消費時間--")
s2 = nil if s2 == :failed
s3 = parse_nl
if s3 != :failed
s0 = [s1, s2, s3]
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
s0
end
# moves : firstboard split? move* result?
def parse_moves
s0 = @current_pos
s1 = parse_firstboard
if s1 != :failed
parse_split
s2 = []
s3 = parse_move
while s3 != :failed
s2 << s3
s3 = parse_move
end
parse_result
@reported_pos = s0
s0 = s2.unshift(s1)
else
@current_pos = s0
s0 = :failed
end
s0
end
# firstboard : comment* pointer?
def parse_firstboard
s0 = @current_pos
s1 = []
s2 = parse_comment
while s2 != :failed
s1 << s2
s2 = parse_comment
end
parse_pointer
@reported_pos = s0
s0 = s1.empty? ? {} : { "comments" => s1 }
s0
end
# move : line comment* pointer?
def parse_move
s0 = @current_pos
s1 = parse_line
if s1 != :failed
s2 = []
s3 = parse_comment
while s3 != :failed
s2 << s3
s3 = parse_comment
end
parse_pointer
@reported_pos = s0
s0 = transform_move(s1, s2)
else
@current_pos = s0
s0 = :failed
end
s0
end
# line : " "* te " "* (fugou from | [^\r\n ]*) " "* time? "+"? nl
def parse_line
s0 = @current_pos
match_spaces
s2 = parse_te
if s2 != :failed
match_spaces
s4 = @current_pos
s5 = parse_fugou
if s5 != :failed
s6 = parse_from
if s6 != :failed
@reported_pos = s4
s4 = transform_teban_fugou_from(s2, s5, s6)
else
@current_pos = s4
s4 = :failed
end
else
@current_pos = s4
s4 = :failed
end
if s4 == :failed
s4 = @current_pos
s5 = []
s6 = match_regexp(/^[^\r\n ]/)
while s6 != :failed
s5 << s6
s6 = match_regexp(/^[^\r\n ]/)
end
@reported_pos = s4
s4 = s5.join
end
if s4 != :failed
match_spaces
s6 = parse_time
s6 = nil if s6 == :failed
match_str("+")
if parse_nl != :failed
@reported_pos = s0
s0 = { "move" => s4, "time" => s6 }
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
s0
end
# te : [0-9]+
def parse_te
match_digits!
end
# fugou : place piece "成"?
# place : num numkan | "同 "
def parse_place
s0 = @current_pos
s1 = parse_num
if s1 != :failed
s2 = parse_numkan
if s2 != :failed
@reported_pos = s0
s0 = { "x" => s1, "y" => s2 }
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
if s0 == :failed
s0 = @current_pos
s1 = match_str("同 ")
if s1 != :failed
@reported_pos = s0
s1 = nil
end
s0 = s1
end
s0
end
# from : "打" | "(" [1-9] [1-9] ")"
def parse_from
s0 = @current_pos
s1 = match_str("打")
if s1 != :failed
@reported_pos = s0
s1 = nil
end
s0 = s1
if s0 == :failed
s0 = @current_pos
if match_str("(") != :failed
s2 = match_regexp(/^[1-9]/)
if s2 != :failed
s3 = match_regexp(/^[1-9]/)
if s3 != :failed
if match_str(")") != :failed
@reported_pos = s0
s0 = { "x" => s2.to_i, "y" => s3.to_i }
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
end
s0
end
# time : "(" " "* ms " "* "/" " "* (hms | ms) " "* ")"
def parse_time
s0 = @current_pos
if match_str("(") != :failed
match_spaces
s3 = parse_ms
if s3 != :failed
match_spaces
if match_str("/") != :failed
match_spaces
s5 = parse_hms
s5 = parse_ms(with_hour: true) if s5 == :failed
if s5 != :failed
match_spaces
if match_str(")") != :failed
@reported_pos = s0
s0 = { "now" => s3, "total" => s5 }
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
s0
end
# hms : [0-9]+ ":" [0-9]+ ":" [0-9]+
def parse_hms
s0 = @current_pos
s1 = match_digits!
if s1 != :failed
if match_str(":") != :failed
s3 = match_digits!
if s3 != :failed
if match_str(":") != :failed
s5 = match_digits!
if s5 != :failed
@reported_pos = s0
s0 = { "h" => s1.join.to_i, "m" => s3.join.to_i, "s" => s5.join.to_i }
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
s0
end
# ms : [0-9]+ ":" [0-9]+
def parse_ms(with_hour: false)
s0 = @current_pos
s1 = match_digits!
if s1 != :failed
if match_str(":") != :failed
s3 = match_digits!
if s3 != :failed
@reported_pos = s0
m = s1.join.to_i
s = s3.join.to_i
if with_hour
h = m / 60
m = m % 60
s0 = { "h" => h, "m" => m, "s" => s }
else
s0 = { "m" => m, "s" => s }
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
s0
end
# comment : "*" nonls nl | "&" nonls nl
def parse_comment
s0 = @current_pos
if match_str("*") != :failed
s2 = parse_nonls
if parse_nl != :failed
@reported_pos = s0
s0 = s2.join
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
if s0 == :failed
s0 = @current_pos
s1 = match_str("&")
if s1 != :failed
s2 = parse_nonls
if parse_nl != :failed
@reported_pos = s0
s0 = "&" + s2.join
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
end
s0
end
# fork : "変化:" " "* [0-9]+ "手" nl moves
def parse_fork
s0 = @current_pos
if match_str("変化:") != :failed
match_spaces
s3 = parse_te
if s3 != :failed
if match_str("手") != :failed
if parse_nl != :failed
s6 = parse_moves
if s6 != :failed
@reported_pos = s0
s0 = { "te" => s3.join.to_i, "moves" => s6[1..-1] }
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
else
@current_pos = s0
s0 = :failed
end
s0
end
# transfrom to jkf
def transform_root(headers, ini, headers2, moves, forks)
ret = { "header" => {}, "moves" => moves }
headers.compact.each { |h| ret["header"][h["k"]] = h["v"] }
headers2.compact.each { |h| ret["header"][h["k"]] = h["v"] }
if ini
ret["initial"] = ini
elsif ret["header"]["手合割"]
preset = preset2str(ret["header"]["手合割"])
ret["initial"] = { "preset" => preset } if preset && preset != "OTHER"
end
transform_root_header_data(ret) if ret["initial"] && ret["initial"]["data"]
transform_root_forks(forks, moves)
if ret["initial"] && ret["initial"]["data"] && ret["initial"]["data"]["color"] == 1
reverse_color(ret["moves"])
end
ret
end
# transform move to jkf
def transform_move(line, c)
ret = {}
ret["comments"] = c if !c.empty?
if line["move"].is_a? Hash
ret["move"] = line["move"]
else
ret["special"] = special2csa(line["move"])
end
ret["time"] = line["time"] if line["time"]
ret
end
# transform teban-fugou-from to jkf
def transform_teban_fugou_from(teban, fugou, from)
ret = { "color" => teban2color(teban.join), "piece" => fugou["piece"] }
if fugou["to"]
ret["to"] = fugou["to"]
else
ret["same"] = true
end
ret["promote"] = true if fugou["promote"]
ret["from"] = from if from
ret
end
# special string to csa
def special2csa(str)
{
"中断" => "CHUDAN",
"投了" => "TORYO",
"持将棋" => "JISHOGI",
"千日手" => "SENNICHITE",
"詰み" => "TSUMI",
"不詰" => "FUZUMI",
"切れ負け" => "TIME_UP",
"反則勝ち" => "ILLEGAL_ACTION", # 直前の手が反則(先頭に+か-で反則した側の情報を含める必要が有る)
"反則負け" => "ILLEGAL_MOVE" # ここで手番側が反則,反則の内容はコメントで表現
}[str] || (raise ParseError)
end
# teban to color
def teban2color(teban)
teban = teban.to_i unless teban.is_a? Fixnum
(teban + 1) % 2
end
# generate motigoma
def make_hand(str)
# Kifu for iPhoneは半角スペース区切り
ret = { "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 }
return ret if str.empty?
str.split(/[ ]/).each do |kind|
next if kind.empty?
ret[kind2csa(kind[0])] = kind.length == 1 ? 1 : kan2n2(kind[1..-1])
end
ret
end
# exchange sente gote
def reverse_color(moves)
moves.each do |move|
if move["move"] && move["move"]["color"]
move["move"]["color"] = (move["move"]["color"] + 1) % 2
end
move["forks"].each { |_fork| reverse_color(_fork) } if move["forks"]
end
end
end
|
mongodb/mongo-ruby-driver | lib/mongo/session.rb | Mongo.Session.abort_transaction | ruby | def abort_transaction
check_if_ended!
check_if_no_transaction!
if within_states?(TRANSACTION_COMMITTED_STATE)
raise Mongo::Error::InvalidTransactionOperation.new(
Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg(
:commitTransaction, :abortTransaction))
end
if within_states?(TRANSACTION_ABORTED_STATE)
raise Mongo::Error::InvalidTransactionOperation.new(
Mongo::Error::InvalidTransactionOperation.cannot_call_twice_msg(:abortTransaction))
end
begin
unless starting_transaction?
write_with_retry(self, txn_options[:write_concern], true) do |server, txn_num|
Operation::Command.new(
selector: { abortTransaction: 1 },
db_name: 'admin',
session: self,
txn_num: txn_num
).execute(server)
end
end
@state = TRANSACTION_ABORTED_STATE
rescue Mongo::Error::InvalidTransactionOperation
raise
rescue Mongo::Error
@state = TRANSACTION_ABORTED_STATE
rescue Exception
@state = TRANSACTION_ABORTED_STATE
raise
end
end | Abort the currently active transaction without making any changes to the database.
@example Abort the transaction.
session.abort_transaction
@raise [ Error::InvalidTransactionOperation ] If there is no active transaction.
@since 2.6.0 | train | https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L688-L724 | class Session
extend Forwardable
include Retryable
include Loggable
# Get the options for this session.
#
# @since 2.5.0
attr_reader :options
# Get the client through which this session was created.
#
# @since 2.5.1
attr_reader :client
# The cluster time for this session.
#
# @since 2.5.0
attr_reader :cluster_time
# The latest seen operation time for this session.
#
# @since 2.5.0
attr_reader :operation_time
# The options for the transaction currently being executed on the session.
#
# @since 2.6.0
attr_reader :txn_options
# Error message indicating that the session was retrieved from a client with a different cluster than that of the
# client through which it is currently being used.
#
# @since 2.5.0
MISMATCHED_CLUSTER_ERROR_MSG = 'The configuration of the client used to create this session does not match that ' +
'of the client owning this operation. Please only use this session for operations through its parent ' +
'client.'.freeze
# Error message describing that the session cannot be used because it has already been ended.
#
# @since 2.5.0
SESSION_ENDED_ERROR_MSG = 'This session has ended and cannot be used. Please create a new one.'.freeze
# Error message describing that sessions are not supported by the server version.
#
# @since 2.5.0
SESSIONS_NOT_SUPPORTED = 'Sessions are not supported by the connected servers.'.freeze
# The state of a session in which the last operation was not related to
# any transaction or no operations have yet occurred.
#
# @since 2.6.0
NO_TRANSACTION_STATE = :no_transaction
# The state of a session in which a user has initiated a transaction but
# no operations within the transactions have occurred yet.
#
# @since 2.6.0
STARTING_TRANSACTION_STATE = :starting_transaction
# The state of a session in which a transaction has been started and at
# least one operation has occurred, but the transaction has not yet been
# committed or aborted.
#
# @since 2.6.0
TRANSACTION_IN_PROGRESS_STATE = :transaction_in_progress
# The state of a session in which the last operation executed was a transaction commit.
#
# @since 2.6.0
TRANSACTION_COMMITTED_STATE = :transaction_committed
# The state of a session in which the last operation executed was a transaction abort.
#
# @since 2.6.0
TRANSACTION_ABORTED_STATE = :transaction_aborted
UNLABELED_WRITE_CONCERN_CODES = [
79, # UnknownReplWriteConcern
100, # CannotSatisfyWriteConcern,
].freeze
# Initialize a Session.
#
# @note Applications should use Client#start_session to begin a session.
#
# @example
# Session.new(server_session, client, options)
#
# @param [ ServerSession ] server_session The server session this session is associated with.
# @param [ Client ] client The client through which this session is created.
# @param [ Hash ] options The options for this session.
#
# @option options [ true|false ] :causal_consistency Whether to enable
# causal consistency for this session.
# @option options [ Hash ] :default_transaction_options Options to pass
# to start_transaction by default, can contain any of the options that
# start_transaction accepts.
# @option options [ true|false ] :implicit For internal driver use only -
# specifies whether the session is implicit.
# @option options [ Hash ] :read_preference The read preference options hash,
# with the following optional keys:
# - *:mode* -- the read preference as a string or symbol; valid values are
# *:primary*, *:primary_preferred*, *:secondary*, *:secondary_preferred*
# and *:nearest*.
#
# @since 2.5.0
# @api private
def initialize(server_session, client, options = {})
@server_session = server_session
options = options.dup
# Because the read preference will need to be inserted into a command as a string, we convert
# it from a symbol immediately upon receiving it.
if options[:read_preference] && options[:read_preference][:mode]
options[:read_preference][:mode] = options[:read_preference][:mode].to_s
end
@client = client.use(:admin)
@options = options.freeze
@cluster_time = nil
@state = NO_TRANSACTION_STATE
end
# Get a formatted string for use in inspection.
#
# @example Inspect the session object.
# session.inspect
#
# @return [ String ] The session inspection.
#
# @since 2.5.0
def inspect
"#<Mongo::Session:0x#{object_id} session_id=#{session_id} options=#{@options}>"
end
# End this session.
#
# @example
# session.end_session
#
# @return [ nil ] Always nil.
#
# @since 2.5.0
def end_session
if !ended? && @client
if within_states?(TRANSACTION_IN_PROGRESS_STATE)
begin
abort_transaction
rescue Mongo::Error
end
end
@client.cluster.session_pool.checkin(@server_session)
end
ensure
@server_session = nil
end
# Whether this session has ended.
#
# @example
# session.ended?
#
# @return [ true, false ] Whether the session has ended.
#
# @since 2.5.0
def ended?
@server_session.nil?
end
# Add the autocommit field to a command document if applicable.
#
# @example
# session.add_autocommit!(cmd)
#
# @return [ Hash, BSON::Document ] The command document.
#
# @since 2.6.0
# @api private
def add_autocommit!(command)
command.tap do |c|
c[:autocommit] = false if in_transaction?
end
end
# Add this session's id to a command document.
#
# @example
# session.add_id!(cmd)
#
# @return [ Hash, BSON::Document ] The command document.
#
# @since 2.5.0
# @api private
def add_id!(command)
command.merge!(lsid: session_id)
end
# Add the startTransaction field to a command document if applicable.
#
# @example
# session.add_start_transaction!(cmd)
#
# @return [ Hash, BSON::Document ] The command document.
#
# @since 2.6.0
# @api private
def add_start_transaction!(command)
command.tap do |c|
if starting_transaction?
c[:startTransaction] = true
end
end
end
# Add the transaction number to a command document if applicable.
#
# @example
# session.add_txn_num!(cmd)
#
# @return [ Hash, BSON::Document ] The command document.
#
# @since 2.6.0
# @api private
def add_txn_num!(command)
command.tap do |c|
c[:txnNumber] = BSON::Int64.new(@server_session.txn_num) if in_transaction?
end
end
# Add the transactions options if applicable.
#
# @example
# session.add_txn_opts!(cmd)
#
# @return [ Hash, BSON::Document ] The command document.
#
# @since 2.6.0
# @api private
def add_txn_opts!(command, read)
command.tap do |c|
# The read preference should be added for all read operations.
if read && txn_read_pref = txn_read_preference
Mongo::Lint.validate_underscore_read_preference(txn_read_pref)
txn_read_pref = txn_read_pref.dup
txn_read_pref[:mode] = txn_read_pref[:mode].to_s.gsub(/(_\w)/) { |match| match[1].upcase }
Mongo::Lint.validate_camel_case_read_preference(txn_read_pref)
c['$readPreference'] = txn_read_pref
end
# The read concern should be added to any command that starts a transaction.
if starting_transaction?
# https://jira.mongodb.org/browse/SPEC-1161: transaction's
# read concern overrides collection/database/client read concerns,
# even if transaction's read concern is not set.
# Read concern here is the one sent to the server and may
# include afterClusterTime.
if rc = c[:readConcern]
rc = rc.dup
rc.delete(:level)
end
if txn_read_concern
if rc
rc.update(txn_read_concern)
else
rc = txn_read_concern.dup
end
end
if rc.nil? || rc.empty?
c.delete(:readConcern)
else
c[:readConcern ] = rc
end
end
# We need to send the read concern level as a string rather than a symbol.
if c[:readConcern] && c[:readConcern][:level]
c[:readConcern][:level] = c[:readConcern][:level].to_s
end
# The write concern should be added to any abortTransaction or commitTransaction command.
if (c[:abortTransaction] || c[:commitTransaction])
if @already_committed
wc = BSON::Document.new(c[:writeConcern] || txn_write_concern || {})
wc.merge!(w: :majority)
wc[:wtimeout] ||= 10000
c[:writeConcern] = wc
elsif txn_write_concern
c[:writeConcern] ||= txn_write_concern
end
end
# A non-numeric write concern w value needs to be sent as a string rather than a symbol.
if c[:writeConcern] && c[:writeConcern][:w] && c[:writeConcern][:w].is_a?(Symbol)
c[:writeConcern][:w] = c[:writeConcern][:w].to_s
end
end
end
# Remove the read concern and/or write concern from the command if not applicable.
#
# @example
# session.suppress_read_write_concern!(cmd)
#
# @return [ Hash, BSON::Document ] The command document.
#
# @since 2.6.0
# @api private
def suppress_read_write_concern!(command)
command.tap do |c|
next unless in_transaction?
c.delete(:readConcern) unless starting_transaction?
c.delete(:writeConcern) unless c[:commitTransaction] || c[:abortTransaction]
end
end
# Ensure that the read preference of a command primary.
#
# @example
# session.validate_read_preference!(command)
#
# @raise [ Mongo::Error::InvalidTransactionOperation ] If the read preference of the command is
# not primary.
#
# @since 2.6.0
# @api private
def validate_read_preference!(command)
return unless in_transaction? && non_primary_read_preference_mode?(command)
raise Mongo::Error::InvalidTransactionOperation.new(
Mongo::Error::InvalidTransactionOperation::INVALID_READ_PREFERENCE)
end
# Update the state of the session due to a (non-commit and non-abort) operation being run.
#
# @since 2.6.0
# @api private
def update_state!
case @state
when STARTING_TRANSACTION_STATE
@state = TRANSACTION_IN_PROGRESS_STATE
when TRANSACTION_COMMITTED_STATE, TRANSACTION_ABORTED_STATE
@state = NO_TRANSACTION_STATE
end
end
# Validate the session.
#
# @example
# session.validate!(cluster)
#
# @param [ Cluster ] cluster The cluster the session is attempted to be used with.
#
# @return [ nil ] nil if the session is valid.
#
# @raise [ Mongo::Error::InvalidSession ] Raise error if the session is not valid.
#
# @since 2.5.0
# @api private
def validate!(cluster)
check_matching_cluster!(cluster)
check_if_ended!
self
end
# Process a response from the server that used this session.
#
# @example Process a response from the server.
# session.process(result)
#
# @param [ Operation::Result ] result The result from the operation.
#
# @return [ Operation::Result ] The result.
#
# @since 2.5.0
# @api private
def process(result)
unless implicit?
set_operation_time(result)
set_cluster_time(result)
end
@server_session.set_last_use!
result
end
# Advance the cached cluster time document for this session.
#
# @example Advance the cluster time.
# session.advance_cluster_time(doc)
#
# @param [ BSON::Document, Hash ] new_cluster_time The new cluster time.
#
# @return [ BSON::Document, Hash ] The new cluster time.
#
# @since 2.5.0
def advance_cluster_time(new_cluster_time)
if @cluster_time
@cluster_time = [ @cluster_time, new_cluster_time ].max_by { |doc| doc[Cluster::CLUSTER_TIME] }
else
@cluster_time = new_cluster_time
end
end
# Advance the cached operation time for this session.
#
# @example Advance the operation time.
# session.advance_operation_time(timestamp)
#
# @param [ BSON::Timestamp ] new_operation_time The new operation time.
#
# @return [ BSON::Timestamp ] The max operation time, considering the current and new times.
#
# @since 2.5.0
def advance_operation_time(new_operation_time)
if @operation_time
@operation_time = [ @operation_time, new_operation_time ].max
else
@operation_time = new_operation_time
end
end
# Whether reads executed with this session can be retried according to
# the modern retryable reads specification.
#
# If this method returns true, the modern retryable reads have been
# requested by the application. If the server selected for a read operation
# supports modern retryable reads, they will be used for that particular
# operation. If the server selected for a read operation does not support
# modern retryable reads, the read will not be retried.
#
# If this method returns false, legacy retryable reads have been requested
# by the application. Legacy retryable read logic will be used regardless
# of server version of the server(s) that the client is connected to.
# The number of read retries is given by :max_read_retries client option,
# which is 1 by default and can be set to 0 to disable legacy read retries.
#
# @api private
def retry_reads?
client.options[:retry_reads] != false
end
# Will writes executed with this session be retried.
#
# @example Will writes be retried.
# session.retry_writes?
#
# @return [ true, false ] If writes will be retried.
#
# @note Retryable writes are only available on server versions at least 3.6
# and with sharded clusters or replica sets.
#
# @since 2.5.0
def retry_writes?
!!client.options[:retry_writes] && (cluster.replica_set? || cluster.sharded?)
end
# Get the server session id of this session, if the session was not ended.
# If the session was ended, returns nil.
#
# @example Get the session id.
# session.session_id
#
# @return [ BSON::Document ] The server session id.
#
# @since 2.5.0
def session_id
if ended?
raise Error::SessionEnded
end
@server_session.session_id
end
# Increment and return the next transaction number.
#
# @example Get the next transaction number.
# session.next_txn_num
#
# @return [ Integer ] The next transaction number.
#
# @since 2.5.0
# @api private
def next_txn_num
if ended?
raise Error::SessionEnded
end
@server_session.next_txn_num
end
# Get the current transaction number.
#
# @example Get the current transaction number.
# session.txn_num
#
# @return [ Integer ] The current transaction number.
#
# @since 2.6.0
def txn_num
if ended?
raise Error::SessionEnded
end
@server_session.txn_num
end
# Is this session an implicit one (not user-created).
#
# @example Is the session implicit?
# session.implicit?
#
# @return [ true, false ] Whether this session is implicit.
#
# @since 2.5.1
def implicit?
@implicit ||= !!(@options.key?(:implicit) && @options[:implicit] == true)
end
# Is this session an explicit one (i.e. user-created).
#
# @example Is the session explicit?
# session.explicit?
#
# @return [ true, false ] Whether this session is explicit.
#
# @since 2.5.2
def explicit?
@explicit ||= !implicit?
end
# Places subsequent operations in this session into a new transaction.
#
# Note that the transaction will not be started on the server until an
# operation is performed after start_transaction is called.
#
# @example Start a new transaction
# session.start_transaction(options)
#
# @param [ Hash ] options The options for the transaction being started.
#
# @option options [ Hash ] read_concern The read concern options hash,
# with the following optional keys:
# - *:level* -- the read preference level as a symbol; valid values
# are *:local*, *:majority*, and *:snapshot*
# @option options [ Hash ] :write_concern The write concern options. Can be :w =>
# Integer|String, :fsync => Boolean, :j => Boolean.
# @option options [ Hash ] :read The read preference options. The hash may have the following
# items:
# - *:mode* -- read preference specified as a symbol; the only valid value is
# *:primary*.
#
# @raise [ Error::InvalidTransactionOperation ] If a transaction is already in
# progress or if the write concern is unacknowledged.
#
# @since 2.6.0
def start_transaction(options = nil)
if options
Lint.validate_read_concern_option(options[:read_concern])
end
check_if_ended!
if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE)
raise Mongo::Error::InvalidTransactionOperation.new(
Mongo::Error::InvalidTransactionOperation::TRANSACTION_ALREADY_IN_PROGRESS)
end
next_txn_num
@txn_options = options || @options[:default_transaction_options] || {}
if txn_write_concern && WriteConcern.send(:unacknowledged?, txn_write_concern)
raise Mongo::Error::InvalidTransactionOperation.new(
Mongo::Error::InvalidTransactionOperation::UNACKNOWLEDGED_WRITE_CONCERN)
end
@state = STARTING_TRANSACTION_STATE
@already_committed = false
end
# Commit the currently active transaction on the session.
#
# @example Commits the transaction.
# session.commit_transaction
#
# @option options :write_concern [ nil | WriteConcern::Base ] The write
# concern to use for this operation.
#
# @raise [ Error::InvalidTransactionOperation ] If there is no active transaction.
#
# @since 2.6.0
def commit_transaction(options=nil)
check_if_ended!
check_if_no_transaction!
if within_states?(TRANSACTION_ABORTED_STATE)
raise Mongo::Error::InvalidTransactionOperation.new(
Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg(
:abortTransaction, :commitTransaction))
end
options ||= {}
begin
# If commitTransaction is called twice, we need to run the same commit
# operation again, so we revert the session to the previous state.
if within_states?(TRANSACTION_COMMITTED_STATE)
@state = @last_commit_skipped ? STARTING_TRANSACTION_STATE : TRANSACTION_IN_PROGRESS_STATE
@already_committed = true
end
if starting_transaction?
@last_commit_skipped = true
else
@last_commit_skipped = false
write_concern = options[:write_concern] || txn_options[:write_concern]
if write_concern && !write_concern.is_a?(WriteConcern::Base)
write_concern = WriteConcern.get(write_concern)
end
write_with_retry(self, write_concern, true) do |server, txn_num, is_retry|
if is_retry
if write_concern
wco = write_concern.options.merge(w: :majority)
wco[:wtimeout] ||= 10000
write_concern = WriteConcern.get(wco)
else
write_concern = WriteConcern.get(w: :majority, wtimeout: 10000)
end
end
Operation::Command.new(
selector: { commitTransaction: 1 },
db_name: 'admin',
session: self,
txn_num: txn_num,
write_concern: write_concern,
).execute(server)
end
end
rescue Mongo::Error::NoServerAvailable, Mongo::Error::SocketError => e
e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)
raise e
rescue Mongo::Error::OperationFailure => e
err_doc = e.instance_variable_get(:@result).send(:first_document)
if e.write_retryable? || (err_doc['writeConcernError'] &&
!UNLABELED_WRITE_CONCERN_CODES.include?(err_doc['writeConcernError']['code']))
e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)
end
raise e
ensure
@state = TRANSACTION_COMMITTED_STATE
end
end
# Abort the currently active transaction without making any changes to the database.
#
# @example Abort the transaction.
# session.abort_transaction
#
# @raise [ Error::InvalidTransactionOperation ] If there is no active transaction.
#
# @since 2.6.0
# Whether or not the session is currently in a transaction.
#
# @example Is the session in a transaction?
# session.in_transaction?
#
# @return [ true | false ] Whether or not the session in a transaction.
#
# @since 2.6.0
def in_transaction?
within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE)
end
# Executes the provided block in a transaction, retrying as necessary.
#
# Returns the return value of the block.
#
# Exact number of retries and when they are performed are implementation
# details of the driver; the provided block should be idempotent, and
# should be prepared to be called more than once. The driver may retry
# the commit command within an active transaction or it may repeat the
# transaction and invoke the block again, depending on the error
# encountered if any. Note also that the retries may be executed against
# different servers.
#
# Transactions cannot be nested - InvalidTransactionOperation will be raised
# if this method is called when the session already has an active transaction.
#
# Exceptions raised by the block which are not derived from Mongo::Error
# stop processing, abort the transaction and are propagated out of
# with_transaction. Exceptions derived from Mongo::Error may be
# handled by with_transaction, resulting in retries of the process.
#
# Currently, with_transaction will retry commits and block invocations
# until at least 120 seconds have passed since with_transaction started
# executing. This timeout is not configurable and may change in a future
# driver version.
#
# @note with_transaction contains a loop, therefore the if with_transaction
# itself is placed in a loop, its block should not call next or break to
# control the outer loop because this will instead affect the loop in
# with_transaction. The driver will warn and abort the transaction
# if it detects this situation.
#
# @example Execute a statement in a transaction
# session.with_transaction(write_concern: {w: :majority}) do
# collection.update_one({ id: 3 }, { '$set' => { status: 'Inactive'} },
# session: session)
#
# end
#
# @example Execute a statement in a transaction, limiting total time consumed
# Timeout.timeout(5) do
# session.with_transaction(write_concern: {w: :majority}) do
# collection.update_one({ id: 3 }, { '$set' => { status: 'Inactive'} },
# session: session)
#
# end
# end
#
# @param [ Hash ] options The options for the transaction being started.
# These are the same options that start_transaction accepts.
#
# @raise [ Error::InvalidTransactionOperation ] If a transaction is already in
# progress or if the write concern is unacknowledged.
#
# @since 2.7.0
def with_transaction(options=nil)
# Non-configurable 120 second timeout for the entire operation
deadline = Time.now + 120
transaction_in_progress = false
loop do
commit_options = {}
if options
commit_options[:write_concern] = options[:write_concern]
end
start_transaction(options)
transaction_in_progress = true
begin
rv = yield self
rescue Exception => e
if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE)
abort_transaction
transaction_in_progress = false
end
if Time.now >= deadline
transaction_in_progress = false
raise
end
if e.is_a?(Mongo::Error) && e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL)
next
end
raise
else
if within_states?(TRANSACTION_ABORTED_STATE, NO_TRANSACTION_STATE, TRANSACTION_COMMITTED_STATE)
transaction_in_progress = false
return rv
end
begin
commit_transaction(commit_options)
transaction_in_progress = false
return rv
rescue Mongo::Error => e
if e.label?(Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)
# WriteConcernFailed
if e.is_a?(Mongo::Error::OperationFailure) && e.code == 64 && e.wtimeout?
transaction_in_progress = false
raise
end
if Time.now >= deadline
transaction_in_progress = false
raise
end
wc_options = case v = commit_options[:write_concern]
when WriteConcern::Base
v.options
when nil
{}
else
v
end
commit_options[:write_concern] = wc_options.merge(w: :majority)
retry
elsif e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL)
if Time.now >= deadline
transaction_in_progress = false
raise
end
next
else
transaction_in_progress = false
raise
end
end
end
end
ensure
if transaction_in_progress
log_warn('with_transaction callback altered with_transaction loop, aborting transaction')
begin
abort_transaction
rescue Error::OperationFailure, Error::InvalidTransactionOperation
end
end
end
# Get the read preference the session will use in the currently
# active transaction.
#
# This is a driver style hash with underscore keys.
#
# @example Get the transaction's read preference
# session.txn_read_preference
#
# @return [ Hash ] The read preference of the transaction.
#
# @since 2.6.0
def txn_read_preference
rp = txn_options && txn_options[:read_preference] ||
@client.read_preference
Mongo::Lint.validate_underscore_read_preference(rp)
rp
end
def cluster
@client.cluster
end
protected
# Get the read concern the session will use when starting a transaction.
#
# This is a driver style hash with underscore keys.
#
# @example Get the session's transaction read concern.
# session.txn_read_concern
#
# @return [ Hash ] The read concern used for starting transactions.
#
# @since 2.9.0
def txn_read_concern
# Read concern is inherited from client but not db or collection.
txn_options && txn_options[:read_concern] || @client.read_concern
end
private
def within_states?(*states)
states.include?(@state)
end
def starting_transaction?
within_states?(STARTING_TRANSACTION_STATE)
end
def check_if_no_transaction!
return unless within_states?(NO_TRANSACTION_STATE)
raise Mongo::Error::InvalidTransactionOperation.new(
Mongo::Error::InvalidTransactionOperation::NO_TRANSACTION_STARTED)
end
def txn_write_concern
(txn_options && txn_options[:write_concern]) ||
(@client.write_concern && @client.write_concern.options)
end
def non_primary_read_preference_mode?(command)
return false unless command['$readPreference']
mode = command['$readPreference']['mode'] || command['$readPreference'][:mode]
mode && mode != 'primary'
end
# Returns causal consistency document if the last operation time is
# known and causal consistency is enabled, otherwise returns nil.
def causal_consistency_doc
if operation_time && causal_consistency?
{:afterClusterTime => operation_time}
else
nil
end
end
def causal_consistency?
@causal_consistency ||= (if @options.key?(:causal_consistency)
!!@options[:causal_consistency]
else
true
end)
end
def set_operation_time(result)
if result && result.operation_time
@operation_time = result.operation_time
end
end
def set_cluster_time(result)
if cluster_time_doc = result.cluster_time
if @cluster_time.nil?
@cluster_time = cluster_time_doc
elsif cluster_time_doc[Cluster::CLUSTER_TIME] > @cluster_time[Cluster::CLUSTER_TIME]
@cluster_time = cluster_time_doc
end
end
end
def check_if_ended!
raise Mongo::Error::InvalidSession.new(SESSION_ENDED_ERROR_MSG) if ended?
end
def check_matching_cluster!(cluster)
if @client.cluster != cluster
raise Mongo::Error::InvalidSession.new(MISMATCHED_CLUSTER_ERROR_MSG)
end
end
end
|
dicom/rtp-connect | lib/rtp-connect/plan_to_dcm.rb | RTP.Plan.create_dose_reference | ruby | def create_dose_reference(dcm, description)
dr_seq = DICOM::Sequence.new('300A,0010', :parent => dcm)
dr_item = DICOM::Item.new(:parent => dr_seq)
# Dose Reference Number:
DICOM::Element.new('300A,0012', '1', :parent => dr_item)
# Dose Reference Structure Type:
DICOM::Element.new('300A,0014', 'SITE', :parent => dr_item)
# Dose Reference Description:
DICOM::Element.new('300A,0016', description, :parent => dr_item)
# Dose Reference Type:
DICOM::Element.new('300A,0020', 'TARGET', :parent => dr_item)
dr_seq
end | Creates a dose reference sequence in the given DICOM object.
@param [DICOM::DObject] dcm the DICOM object in which to insert the sequence
@param [String] description the value to use for Dose Reference Description
@return [DICOM::Sequence] the constructed dose reference sequence | train | https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L619-L631 | class Plan < Record
attr_accessor :current_gantry
attr_accessor :current_collimator
attr_accessor :current_couch_angle
attr_accessor :current_couch_pedestal
attr_accessor :current_couch_lateral
attr_accessor :current_couch_longitudinal
attr_accessor :current_couch_vertical
# Converts the Plan (and child) records to a
# DICOM::DObject of modality RTPLAN.
#
# @note Only photon plans have been tested.
# Electron beams beams may give an invalid DICOM file.
# Also note that, due to limitations in the RTP file format, some original
# values can not be recreated, like e.g. Study UID or Series UID.
# @param [Hash] options the options to use for creating the DICOM object
# @option options [Boolean] :dose_ref if set, Dose Reference & Referenced Dose Reference sequences will be included in the generated DICOM file
# @option options [String] :manufacturer the value used for the manufacturer tag (0008,0070) in the beam sequence
# @option options [String] :model the value used for the manufacturer's model name tag (0008,1090) in the beam sequence
# @option options [Symbol] :scale if set, relevant device parameters are converted from native readout format to IEC1217 (supported values are :elekta & :varian)
# @option options [String] :serial_number the value used for the device serial number tag (0018,1000) in the beam sequence
# @return [DICOM::DObject] the converted DICOM object
#
def to_dcm(options={})
#
# FIXME: This method is rather big, with a few sections of somewhat similar, repeating code.
# Refactoring and simplifying it at some stage might be a good idea.
#
require 'dicom'
original_level = DICOM.logger.level
DICOM.logger.level = Logger::FATAL
p = @prescriptions.first
# If no prescription is present, we are not going to be able to make a valid DICOM object:
logger.error("No Prescription Record present. Unable to build a valid RTPLAN DICOM object.") unless p
dcm = DICOM::DObject.new
#
# TOP LEVEL TAGS:
#
# Specific Character Set:
DICOM::Element.new('0008,0005', 'ISO_IR 100', :parent => dcm)
# Instance Creation Date
DICOM::Element.new('0008,0012', Time.now.strftime("%Y%m%d"), :parent => dcm)
# Instance Creation Time:
DICOM::Element.new('0008,0013', Time.now.strftime("%H%M%S"), :parent => dcm)
# SOP Class UID:
DICOM::Element.new('0008,0016', '1.2.840.10008.5.1.4.1.1.481.5', :parent => dcm)
# SOP Instance UID (if an original UID is not present, we make up a UID):
begin
sop_uid = p.fields.first.extended_field.original_plan_uid.empty? ? DICOM.generate_uid : p.fields.first.extended_field.original_plan_uid
rescue
sop_uid = DICOM.generate_uid
end
DICOM::Element.new('0008,0018', sop_uid, :parent => dcm)
# Study Date
DICOM::Element.new('0008,0020', Time.now.strftime("%Y%m%d"), :parent => dcm)
# Study Time:
DICOM::Element.new('0008,0030', Time.now.strftime("%H%M%S"), :parent => dcm)
# Accession Number:
DICOM::Element.new('0008,0050', '', :parent => dcm)
# Modality:
DICOM::Element.new('0008,0060', 'RTPLAN', :parent => dcm)
# Manufacturer:
DICOM::Element.new('0008,0070', 'rtp-connect', :parent => dcm)
# Referring Physician's Name:
DICOM::Element.new('0008,0090', "#{@md_last_name}^#{@md_first_name}^#{@md_middle_name}^^", :parent => dcm)
# Operator's Name:
DICOM::Element.new('0008,1070', "#{@author_last_name}^#{@author_first_name}^#{@author_middle_name}^^", :parent => dcm)
# Patient's Name:
DICOM::Element.new('0010,0010', "#{@patient_last_name}^#{@patient_first_name}^#{@patient_middle_name}^^", :parent => dcm)
# Patient ID:
DICOM::Element.new('0010,0020', @patient_id, :parent => dcm)
# Patient's Birth Date:
DICOM::Element.new('0010,0030', '', :parent => dcm)
# Patient's Sex:
DICOM::Element.new('0010,0040', '', :parent => dcm)
# Manufacturer's Model Name:
DICOM::Element.new('0008,1090', 'RTP-to-DICOM', :parent => dcm)
# Software Version(s):
DICOM::Element.new('0018,1020', "RubyRTP#{VERSION}", :parent => dcm)
# Study Instance UID:
DICOM::Element.new('0020,000D', DICOM.generate_uid, :parent => dcm)
# Series Instance UID:
DICOM::Element.new('0020,000E', DICOM.generate_uid, :parent => dcm)
# Study ID:
DICOM::Element.new('0020,0010', '1', :parent => dcm)
# Series Number:
DICOM::Element.new('0020,0011', '1', :parent => dcm)
# Frame of Reference UID (if an original UID is not present, we make up a UID):
begin
for_uid = p.site_setup.frame_of_ref_uid.empty? ? DICOM.generate_uid : p.site_setup.frame_of_ref_uid
rescue
for_uid = DICOM.generate_uid
end
DICOM::Element.new('0020,0052', for_uid, :parent => dcm)
# Position Reference Indicator:
DICOM::Element.new('0020,1040', '', :parent => dcm)
# RT Plan Label (max 16 characters):
plan_label = p ? p.rx_site_name[0..15] : @course_id
DICOM::Element.new('300A,0002', plan_label, :parent => dcm)
# RT Plan Name:
plan_name = p ? p.rx_site_name : @course_id
DICOM::Element.new('300A,0003', plan_name, :parent => dcm)
# RT Plan Description:
plan_desc = p ? p.technique : @diagnosis
DICOM::Element.new('300A,0004', plan_desc, :parent => dcm)
# RT Plan Date:
plan_date = @plan_date.empty? ? Time.now.strftime("%Y%m%d") : @plan_date
DICOM::Element.new('300A,0006', plan_date, :parent => dcm)
# RT Plan Time:
plan_time = @plan_time.empty? ? Time.now.strftime("%H%M%S") : @plan_time
DICOM::Element.new('300A,0007', plan_time, :parent => dcm)
# Approval Status:
DICOM::Element.new('300E,0002', 'UNAPPROVED', :parent => dcm)
#
# SEQUENCES:
#
# Tolerance Table Sequence:
if p && p.fields.first && !p.fields.first.tolerance_table.empty?
tt_seq = DICOM::Sequence.new('300A,0040', :parent => dcm)
tt_item = DICOM::Item.new(:parent => tt_seq)
# Tolerance Table Number:
DICOM::Element.new('300A,0042', p.fields.first.tolerance_table, :parent => tt_item)
end
# Structure set information:
if p && p.site_setup && !p.site_setup.structure_set_uid.empty?
#
# Referenced Structure Set Sequence:
#
ss_seq = DICOM::Sequence.new('300C,0060', :parent => dcm)
ss_item = DICOM::Item.new(:parent => ss_seq)
# Referenced SOP Class UID:
DICOM::Element.new('0008,1150', '1.2.840.10008.5.1.4.1.1.481.3', :parent => ss_item)
DICOM::Element.new('0008,1155', p.site_setup.structure_set_uid, :parent => ss_item)
# RT Plan Geometry:
DICOM::Element.new('300A,000C', 'PATIENT', :parent => dcm)
else
# RT Plan Geometry:
DICOM::Element.new('300A,000C', 'TREATMENT_DEVICE', :parent => dcm)
end
#
# Patient Setup Sequence:
#
ps_seq = DICOM::Sequence.new('300A,0180', :parent => dcm)
ps_item = DICOM::Item.new(:parent => ps_seq)
# Patient Position:
begin
pat_pos = p.site_setup.patient_orientation.empty? ? 'HFS' : p.site_setup.patient_orientation
rescue
pat_pos = 'HFS'
end
DICOM::Element.new('0018,5100', pat_pos, :parent => ps_item)
# Patient Setup Number:
DICOM::Element.new('300A,0182', '1', :parent => ps_item)
# Setup Technique (assume Isocentric):
DICOM::Element.new('300A,01B0', 'ISOCENTRIC', :parent => ps_item)
#
# Dose Reference Sequence:
#
create_dose_reference(dcm, plan_name) if options[:dose_ref]
#
# Fraction Group Sequence:
#
fg_seq = DICOM::Sequence.new('300A,0070', :parent => dcm)
fg_item = DICOM::Item.new(:parent => fg_seq)
# Fraction Group Number:
DICOM::Element.new('300A,0071', '1', :parent => fg_item)
# Number of Fractions Planned (try to derive from total dose/fraction dose, or use 1 as default):
begin
num_frac = p.dose_ttl.empty? || p.dose_tx.empty? ? '1' : (p.dose_ttl.to_i / p.dose_tx.to_f).round.to_s
rescue
num_frac = '0'
end
DICOM::Element.new('300A,0078', num_frac, :parent => fg_item)
# Number of Brachy Application Setups:
DICOM::Element.new('300A,00A0', '0', :parent => fg_item)
# Referenced Beam Sequence (items created for each beam below):
rb_seq = DICOM::Sequence.new('300C,0004', :parent => fg_item)
#
# Beam Sequence:
#
b_seq = DICOM::Sequence.new('300A,00B0', :parent => dcm)
if p
# If no fields are present, we are not going to be able to make a valid DICOM object:
logger.error("No Field Record present. Unable to build a valid RTPLAN DICOM object.") unless p.fields.length > 0
p.fields.each_with_index do |field, i|
# Fields with modality 'Unspecified' (e.g. CT or 2dkV) must be skipped:
unless field.modality == 'Unspecified'
# If this is an electron beam, a warning should be printed, as these are less reliably converted:
logger.warn("This is not a photon beam (#{field.modality}). Beware that DICOM conversion of Electron beams are experimental, and other modalities are unsupported.") if field.modality != 'Xrays'
# Reset control point 'current value' attributes:
reset_cp_current_attributes
# Beam number and name:
beam_number = field.extended_field ? field.extended_field.original_beam_number : (i + 1).to_s
beam_name = field.extended_field ? field.extended_field.original_beam_name : field.field_name
# Ref Beam Item:
rb_item = DICOM::Item.new(:parent => rb_seq)
# Beam Dose (convert from cGy to Gy):
field_dose = field.field_dose.empty? ? '' : (field.field_dose.to_f * 0.01).round(4).to_s
DICOM::Element.new('300A,0084', field_dose, :parent => rb_item)
# Beam Meterset:
DICOM::Element.new('300A,0086', field.field_monitor_units, :parent => rb_item)
# Referenced Beam Number:
DICOM::Element.new('300C,0006', beam_number, :parent => rb_item)
# Beam Item:
b_item = DICOM::Item.new(:parent => b_seq)
# Optional method values:
# Manufacturer:
DICOM::Element.new('0008,0070', options[:manufacturer], :parent => b_item) if options[:manufacturer]
# Manufacturer's Model Name:
DICOM::Element.new('0008,1090', options[:model], :parent => b_item) if options[:model]
# Device Serial Number:
DICOM::Element.new('0018,1000', options[:serial_number], :parent => b_item) if options[:serial_number]
# Treatment Machine Name (max 16 characters):
DICOM::Element.new('300A,00B2', field.treatment_machine[0..15], :parent => b_item)
# Primary Dosimeter Unit:
DICOM::Element.new('300A,00B3', 'MU', :parent => b_item)
# Source-Axis Distance (convert to mm):
DICOM::Element.new('300A,00B4', "#{field.sad.to_f * 10}", :parent => b_item)
# Beam Number:
DICOM::Element.new('300A,00C0', beam_number, :parent => b_item)
# Beam Name:
DICOM::Element.new('300A,00C2', beam_name, :parent => b_item)
# Beam Description:
DICOM::Element.new('300A,00C3', field.field_note, :parent => b_item)
# Beam Type:
beam_type = case field.treatment_type
when 'Static' then 'STATIC'
when 'StepNShoot' then 'STATIC'
when 'VMAT' then 'DYNAMIC'
else logger.error("The beam type (treatment type) #{field.treatment_type} is not yet supported.")
end
DICOM::Element.new('300A,00C4', beam_type, :parent => b_item)
# Radiation Type:
rad_type = case field.modality
when 'Elect' then 'ELECTRON'
when 'Xrays' then 'PHOTON'
else logger.error("The radiation type (modality) #{field.modality} is not yet supported.")
end
DICOM::Element.new('300A,00C6', rad_type, :parent => b_item)
# Treatment Delivery Type:
DICOM::Element.new('300A,00CE', 'TREATMENT', :parent => b_item)
# Number of Wedges:
DICOM::Element.new('300A,00D0', (field.wedge.empty? ? '0' : '1'), :parent => b_item)
# Number of Compensators:
DICOM::Element.new('300A,00E0', (field.compensator.empty? ? '0' : '1'), :parent => b_item)
# Number of Boli:
DICOM::Element.new('300A,00ED', (field.bolus.empty? ? '0' : '1'), :parent => b_item)
# Number of Blocks:
DICOM::Element.new('300A,00F0', (field.block.empty? ? '0' : '1'), :parent => b_item)
# Final Cumulative Meterset Weight:
DICOM::Element.new('300A,010E', 1, :parent => b_item)
# Referenced Patient Setup Number:
DICOM::Element.new('300C,006A', '1', :parent => b_item)
#
# Beam Limiting Device Sequence:
#
create_beam_limiting_devices(b_item, field)
#
# Block Sequence (if any):
# FIXME: It seems that the Block Sequence (300A,00F4) may be
# difficult (impossible?) to reconstruct based on the RTP file's
# information, and thus it is skipped altogether.
#
#
# Applicator Sequence (if any):
#
unless field.e_applicator.empty?
app_seq = DICOM::Sequence.new('300A,0107', :parent => b_item)
app_item = DICOM::Item.new(:parent => app_seq)
# Applicator ID:
DICOM::Element.new('300A,0108', field.e_field_def_aperture, :parent => app_item)
# Applicator Type:
DICOM::Element.new('300A,0109', "ELECTRON_#{field.e_applicator.upcase}", :parent => app_item)
# Applicator Description:
DICOM::Element.new('300A,010A', "Appl. #{field.e_field_def_aperture}", :parent => app_item)
end
#
# Control Point Sequence:
#
# A field may have 0 (no MLC), 1 (conventional beam with MLC) or 2n (IMRT) control points.
# The DICOM file shall always contain 2n control points (minimum 2).
#
cp_seq = DICOM::Sequence.new('300A,0111', :parent => b_item)
if field.control_points.length < 2
# When we have 0 or 1 control point, use settings from field, and insert MLC settings if present:
# First CP:
cp_item = DICOM::Item.new(:parent => cp_seq)
# Control Point Index:
DICOM::Element.new('300A,0112', "0", :parent => cp_item)
# Nominal Beam Energy:
DICOM::Element.new('300A,0114', "#{field.energy.to_f}", :parent => cp_item)
# Dose Rate Set:
DICOM::Element.new('300A,0115', field.doserate, :parent => cp_item)
# Gantry Angle:
DICOM::Element.new('300A,011E', field.gantry_angle, :parent => cp_item)
# Gantry Rotation Direction:
DICOM::Element.new('300A,011F', (field.arc_direction.empty? ? 'NONE' : field.arc_direction), :parent => cp_item)
# Beam Limiting Device Angle:
DICOM::Element.new('300A,0120', field.collimator_angle, :parent => cp_item)
# Beam Limiting Device Rotation Direction:
DICOM::Element.new('300A,0121', 'NONE', :parent => cp_item)
# Patient Support Angle:
DICOM::Element.new('300A,0122', field.couch_pedestal, :parent => cp_item)
# Patient Support Rotation Direction:
DICOM::Element.new('300A,0123', 'NONE', :parent => cp_item)
# Table Top Eccentric Angle:
DICOM::Element.new('300A,0125', field.couch_angle, :parent => cp_item)
# Table Top Eccentric Rotation Direction:
DICOM::Element.new('300A,0126', 'NONE', :parent => cp_item)
# Table Top Vertical Position:
couch_vert = field.couch_vertical.empty? ? '' : (field.couch_vertical.to_f * 10).to_s
DICOM::Element.new('300A,0128', couch_vert, :parent => cp_item)
# Table Top Longitudinal Position:
couch_long = field.couch_longitudinal.empty? ? '' : (field.couch_longitudinal.to_f * 10).to_s
DICOM::Element.new('300A,0129', couch_long, :parent => cp_item)
# Table Top Lateral Position:
couch_lat = field.couch_lateral.empty? ? '' : (field.couch_lateral.to_f * 10).to_s
DICOM::Element.new('300A,012A', couch_lat, :parent => cp_item)
# Isocenter Position (x\y\z):
if p.site_setup
DICOM::Element.new('300A,012C', "#{(p.site_setup.iso_pos_x.to_f * 10).round(2)}\\#{(p.site_setup.iso_pos_y.to_f * 10).round(2)}\\#{(p.site_setup.iso_pos_z.to_f * 10).round(2)}", :parent => cp_item)
else
logger.warn("No Site Setup record exists for this plan. Unable to provide an isosenter position.")
DICOM::Element.new('300A,012C', '', :parent => cp_item)
end
# Source to Surface Distance:
add_ssd(field.ssd, cp_item)
# Cumulative Meterset Weight:
DICOM::Element.new('300A,0134', '0', :parent => cp_item)
# Beam Limiting Device Position Sequence:
if field.control_points.length > 0
create_beam_limiting_device_positions(cp_item, field.control_points.first, options)
else
create_beam_limiting_device_positions_from_field(cp_item, field, options)
end
# Referenced Dose Reference Sequence:
create_referenced_dose_reference(cp_item) if options[:dose_ref]
# Second CP:
cp_item = DICOM::Item.new(:parent => cp_seq)
# Control Point Index:
DICOM::Element.new('300A,0112', "1", :parent => cp_item)
# Cumulative Meterset Weight:
DICOM::Element.new('300A,0134', '1', :parent => cp_item)
else
# When we have multiple (2 or more) control points, iterate each control point:
field.control_points.each { |cp| create_control_point(cp, cp_seq, options) }
# Make sure that hte cumulative meterset weight of the last control
# point is '1' (exactly equal to final cumulative meterset weight):
cp_seq.items.last['300A,0134'].value = '1'
end
# Number of Control Points:
DICOM::Element.new('300A,0110', b_item['300A,0111'].items.length, :parent => b_item)
end
end
# Number of Beams:
DICOM::Element.new('300A,0080', fg_item['300C,0004'].items.length, :parent => fg_item)
end
# Restore the DICOM logger:
DICOM.logger.level = original_level
return dcm
end
private
# Adds an angular type value to a Control Point Item, by creating the
# necessary DICOM elements.
# Note that the element is only added if there is no 'current' attribute
# defined, or the given value is different form the current attribute.
#
# @param [DICOM::Item] item the DICOM control point item in which to create the elements
# @param [String] angle_tag the DICOM tag of the angle element
# @param [String] direction_tag the DICOM tag of the direction element
# @param [String, NilClass] angle the collimator angle attribute
# @param [String, NilClass] direction the collimator rotation direction attribute
# @param [Symbol] current_angle the instance variable that keeps track of the current value of this attribute
#
def add_angle(item, angle_tag, direction_tag, angle, direction, current_angle)
if !self.send(current_angle) || angle != self.send(current_angle)
self.send("#{current_angle}=", angle)
DICOM::Element.new(angle_tag, angle, :parent => item)
DICOM::Element.new(direction_tag, (direction.empty? ? 'NONE' : direction), :parent => item)
end
end
# Adds a Table Top Position element to a Control Point Item.
# Note that the element is only added if there is no 'current' attribute
# defined, or the given value is different form the current attribute.
#
# @param [DICOM::Item] item the DICOM control point item in which to create the element
# @param [String] tag the DICOM tag of the couch position element
# @param [String, NilClass] value the couch position
# @param [Symbol] current the instance variable that keeps track of the current value of this attribute
#
def add_couch_position(item, tag, value, current)
if !self.send(current) || value != self.send(current)
self.send("#{current}=", value)
DICOM::Element.new(tag, (value.empty? ? '' : value.to_f * 10), :parent => item)
end
end
# Adds a Dose Rate Set element to a Control Point Item.
# Note that the element is only added if there is no 'current' attribute
# defined, or the given value is different form the current attribute.
#
# @param [String, NilClass] value the doserate attribute
# @param [DICOM::Item] item the DICOM control point item in which to create an element
#
def add_doserate(value, item)
if !@current_doserate || value != @current_doserate
@current_doserate = value
DICOM::Element.new('300A,0115', value, :parent => item)
end
end
# Adds a Nominal Beam Energy element to a Control Point Item.
# Note that the element is only added if there is no 'current' attribute
# defined, or the given value is different form the current attribute.
#
# @param [String, NilClass] value the energy attribute
# @param [DICOM::Item] item the DICOM control point item in which to create an element
#
def add_energy(value, item)
if !@current_energy || value != @current_energy
@current_energy = value
DICOM::Element.new('300A,0114', "#{value.to_f}", :parent => item)
end
end
# Adds an Isosenter element to a Control Point Item.
# Note that the element is only added if there is a Site Setup record present,
# and it contains a real (non-empty) value. Also, the element is only added if there
# is no 'current' attribute defined, or the given value is different form the current attribute.
#
# @param [SiteSetup, NilClass] site_setup the associated site setup record
# @param [DICOM::Item] item the DICOM control point item in which to create an element
#
def add_isosenter(site_setup, item)
if site_setup
# Create an element if the value is new or unique:
if !@current_isosenter
iso = "#{(site_setup.iso_pos_x.to_f * 10).round(2)}\\#{(site_setup.iso_pos_y.to_f * 10).round(2)}\\#{(site_setup.iso_pos_z.to_f * 10).round(2)}"
if iso != @current_isosenter
@current_isosenter = iso
DICOM::Element.new('300A,012C', iso, :parent => item)
end
end
else
# Log a warning if this is the first control point:
unless @current_isosenter
logger.warn("No Site Setup record exists for this plan. Unable to provide an isosenter position.")
end
end
end
# Adds a Source to Surface Distance element to a Control Point Item.
# Note that the element is only added if the SSD attribute contains
# real (non-empty) value.
#
# @param [String, NilClass] value the SSD attribute
# @param [DICOM::Item] item the DICOM control point item in which to create an element
#
def add_ssd(value, item)
DICOM::Element.new('300A,0130', "#{value.to_f * 10}", :parent => item) if value && !value.empty?
end
# Creates a control point item in the given control point sequence, based
# on an RTP control point record.
#
# @param [ControlPoint] cp the RTP ControlPoint record to convert
# @param [DICOM::Sequence] sequence the DICOM parent sequence of the item to be created
# @param [Hash] options the options to use for creating the control point
# @option options [Boolean] :dose_ref if set, a Referenced Dose Reference sequence will be included in the generated control point item
# @return [DICOM::Item] the constructed control point DICOM item
#
def create_control_point(cp, sequence, options={})
cp_item = DICOM::Item.new(:parent => sequence)
# Some CP attributes will always be written (CP index, BLD positions & Cumulative meterset weight).
# The other attributes are only written if they are different from the previous control point.
# Control Point Index:
DICOM::Element.new('300A,0112', "#{cp.index}", :parent => cp_item)
# Beam Limiting Device Position Sequence:
create_beam_limiting_device_positions(cp_item, cp, options)
# Source to Surface Distance:
add_ssd(cp.ssd, cp_item)
# Cumulative Meterset Weight:
DICOM::Element.new('300A,0134', cp.monitor_units.to_f, :parent => cp_item)
# Referenced Dose Reference Sequence:
create_referenced_dose_reference(cp_item) if options[:dose_ref]
# Attributes that are only added if they carry an updated value:
# Nominal Beam Energy:
add_energy(cp.energy, cp_item)
# Dose Rate Set:
add_doserate(cp.doserate, cp_item)
# Gantry Angle & Rotation Direction:
add_angle(cp_item, '300A,011E', '300A,011F', cp.gantry_angle, cp.gantry_dir, :current_gantry)
# Beam Limiting Device Angle & Rotation Direction:
add_angle(cp_item, '300A,0120', '300A,0121', cp.collimator_angle, cp.collimator_dir, :current_collimator)
# Patient Support Angle & Rotation Direction:
add_angle(cp_item, '300A,0122', '300A,0123', cp.couch_pedestal, cp.couch_ped_dir, :current_couch_pedestal)
# Table Top Eccentric Angle & Rotation Direction:
add_angle(cp_item, '300A,0125', '300A,0126', cp.couch_angle, cp.couch_dir, :current_couch_angle)
# Table Top Vertical Position:
add_couch_position(cp_item, '300A,0128', cp.couch_vertical, :current_couch_vertical)
# Table Top Longitudinal Position:
add_couch_position(cp_item, '300A,0129', cp.couch_longitudinal, :current_couch_longitudinal)
# Table Top Lateral Position:
add_couch_position(cp_item, '300A,012A', cp.couch_lateral, :current_couch_lateral)
# Isocenter Position (x\y\z):
add_isosenter(cp.parent.parent.site_setup, cp_item)
cp_item
end
# Creates a beam limiting device sequence in the given DICOM object.
#
# @param [DICOM::Item] beam_item the DICOM beam item in which to insert the sequence
# @param [Field] field the RTP field to fetch device parameters from
# @return [DICOM::Sequence] the constructed beam limiting device sequence
#
def create_beam_limiting_devices(beam_item, field)
bl_seq = DICOM::Sequence.new('300A,00B6', :parent => beam_item)
# The ASYMX item ('backup jaws') doesn't exist on all models:
if ['SYM', 'ASY'].include?(field.field_x_mode.upcase)
bl_item_x = DICOM::Item.new(:parent => bl_seq)
DICOM::Element.new('300A,00B8', "ASYMX", :parent => bl_item_x)
DICOM::Element.new('300A,00BC', "1", :parent => bl_item_x)
end
# The ASYMY item is always created:
bl_item_y = DICOM::Item.new(:parent => bl_seq)
# RT Beam Limiting Device Type:
DICOM::Element.new('300A,00B8', "ASYMY", :parent => bl_item_y)
# Number of Leaf/Jaw Pairs:
DICOM::Element.new('300A,00BC', "1", :parent => bl_item_y)
# MLCX item is only created if leaves are defined:
# (NB: The RTP file doesn't specify leaf position boundaries, so we
# have to set these based on a set of known MLC types, their number
# of leaves, and their leaf boundary positions.)
if field.control_points.length > 0
bl_item_mlcx = DICOM::Item.new(:parent => bl_seq)
DICOM::Element.new('300A,00B8', "MLCX", :parent => bl_item_mlcx)
num_leaves = field.control_points.first.mlc_leaves.to_i
DICOM::Element.new('300A,00BC', num_leaves.to_s, :parent => bl_item_mlcx)
DICOM::Element.new('300A,00BE', "#{RTP.leaf_boundaries(num_leaves).join("\\")}", :parent => bl_item_mlcx)
end
bl_seq
end
# Creates a beam limiting device positions sequence in the given DICOM object.
#
# @param [DICOM::Item] cp_item the DICOM control point item in which to insert the sequence
# @param [ControlPoint] cp the RTP control point to fetch device parameters from
# @return [DICOM::Sequence] the constructed beam limiting device positions sequence
#
def create_beam_limiting_device_positions(cp_item, cp, options={})
dp_seq = DICOM::Sequence.new('300A,011A', :parent => cp_item)
# The ASYMX item ('backup jaws') doesn't exist on all models:
if ['SYM', 'ASY'].include?(cp.parent.field_x_mode.upcase)
dp_item_x = create_asym_item(cp, dp_seq, axis=:x, options)
end
# Always create one ASYMY item:
dp_item_y = create_asym_item(cp, dp_seq, axis=:y, options)
# MLCX:
dp_item_mlcx = DICOM::Item.new(:parent => dp_seq)
# RT Beam Limiting Device Type:
DICOM::Element.new('300A,00B8', "MLCX", :parent => dp_item_mlcx)
# Leaf/Jaw Positions:
DICOM::Element.new('300A,011C', cp.dcm_mlc_positions(options[:scale]), :parent => dp_item_mlcx)
dp_seq
end
# Creates an ASYMX or ASYMY item.
#
# @param [ControlPoint] cp the RTP control point to fetch device parameters from
# @param [DICOM::Sequence] dcm_parent the DICOM sequence in which to insert the item
# @param [Symbol] axis the axis for the item (:x or :y)
# @return [DICOM::Item] the constructed ASYMX or ASYMY item
#
def create_asym_item(cp, dcm_parent, axis, options={})
val1 = cp.send("dcm_collimator_#{axis.to_s}1", options[:scale])
val2 = cp.send("dcm_collimator_#{axis.to_s}2", options[:scale])
item = DICOM::Item.new(:parent => dcm_parent)
# RT Beam Limiting Device Type:
DICOM::Element.new('300A,00B8', "ASYM#{axis.to_s.upcase}", :parent => item)
# Leaf/Jaw Positions:
DICOM::Element.new('300A,011C', "#{val1}\\#{val2}", :parent => item)
item
end
# Creates a beam limiting device positions sequence in the given DICOM object.
#
# @param [DICOM::Item] cp_item the DICOM control point item in which to insert the sequence
# @param [Field] field the RTP treatment field to fetch device parameters from
# @return [DICOM::Sequence] the constructed beam limiting device positions sequence
#
def create_beam_limiting_device_positions_from_field(cp_item, field, options={})
dp_seq = DICOM::Sequence.new('300A,011A', :parent => cp_item)
# ASYMX:
dp_item_x = DICOM::Item.new(:parent => dp_seq)
DICOM::Element.new('300A,00B8', "ASYMX", :parent => dp_item_x)
DICOM::Element.new('300A,011C', "#{field.dcm_collimator_x1}\\#{field.dcm_collimator_x2}", :parent => dp_item_x)
# ASYMY:
dp_item_y = DICOM::Item.new(:parent => dp_seq)
DICOM::Element.new('300A,00B8', "ASYMY", :parent => dp_item_y)
DICOM::Element.new('300A,011C', "#{field.dcm_collimator_y1}\\#{field.dcm_collimator_y2}", :parent => dp_item_y)
dp_seq
end
# Creates a dose reference sequence in the given DICOM object.
#
# @param [DICOM::DObject] dcm the DICOM object in which to insert the sequence
# @param [String] description the value to use for Dose Reference Description
# @return [DICOM::Sequence] the constructed dose reference sequence
#
# Creates a referenced dose reference sequence in the given DICOM object.
#
# @param [DICOM::Item] cp_item the DICOM item in which to insert the sequence
# @return [DICOM::Sequence] the constructed referenced dose reference sequence
#
def create_referenced_dose_reference(cp_item)
# Referenced Dose Reference Sequence:
rd_seq = DICOM::Sequence.new('300C,0050', :parent => cp_item)
rd_item = DICOM::Item.new(:parent => rd_seq)
# Cumulative Dose Reference Coeffecient:
DICOM::Element.new('300A,010C', '', :parent => rd_item)
# Referenced Dose Reference Number:
DICOM::Element.new('300C,0051', '1', :parent => rd_item)
rd_seq
end
# Resets the types of control point attributes that are only written to the
# first control point item, and for following control point items only when
# they are different from the 'current' value. When a new field is reached,
# it is essential to reset these attributes, or else we could risk to start
# the field with a control point with missing attributes, if one of its first
# attributes is equal to the last attribute of the previous field.
#
def reset_cp_current_attributes
@current_gantry = nil
@current_collimator = nil
@current_couch_pedestal = nil
@current_couch_angle = nil
@current_couch_vertical = nil
@current_couch_longitudinal = nil
@current_couch_lateral = nil
@current_isosenter = nil
end
end
|
mhs/rvideo | lib/rvideo/inspector.rb | RVideo.Inspector.duration | ruby | def duration
return nil unless valid?
units = raw_duration.split(":")
(units[0].to_i * 60 * 60 * 1000) + (units[1].to_i * 60 * 1000) + (units[2].to_f * 1000).to_i
end | The duration of the movie in milliseconds, as an integer.
Example:
24400 # 24.4 seconds
Note that the precision of the duration is in tenths of a second, not
thousandths, but milliseconds are a more standard unit of time than
deciseconds. | train | https://github.com/mhs/rvideo/blob/5d12bafc5b63888f01c42de272fddcef0ac528b1/lib/rvideo/inspector.rb#L304-L309 | class Inspector
attr_reader :filename, :path, :full_filename, :raw_response, :raw_metadata
attr_accessor :ffmpeg_binary
#
# To inspect a video or audio file, initialize an Inspector object.
#
# file = RVideo::Inspector.new(options_hash)
#
# Inspector accepts three options: file, raw_response, and ffmpeg_binary.
# Either raw_response or file is required; ffmpeg binary is optional.
#
# :file is a path to a file to be inspected.
#
# :raw_response is the full output of "ffmpeg -i [file]". If the
# :raw_response option is used, RVideo will not actually inspect a file;
# it will simply parse the provided response. This is useful if your
# application has already collected the ffmpeg -i response, and you don't
# want to call it again.
#
# :ffmpeg_binary is an optional argument that specifies the path to the
# ffmpeg binary to be used. If a path is not explicitly declared, RVideo
# will assume that ffmpeg exists in the Unix path. Type "which ffmpeg" to
# check if ffmpeg is installed and exists in your operating system's path.
#
def initialize(options = {})
if options[:raw_response]
@raw_response = options[:raw_response]
elsif options[:file]
if options[:ffmpeg_binary]
@ffmpeg_binary = options[:ffmpeg_binary]
raise RuntimeError, "ffmpeg could not be found (trying #{@ffmpeg_binary})" unless FileTest.exist?(@ffmpeg_binary)
else
# assume it is in the unix path
raise RuntimeError, 'ffmpeg could not be found (expected ffmpeg to be found in the Unix path)' unless FileTest.exist?(`which ffmpeg`.chomp)
@ffmpeg_binary = "ffmpeg"
end
file = options[:file]
@filename = File.basename(file)
@path = File.dirname(file)
@full_filename = file
raise TranscoderError::InputFileNotFound, "File not found (#{@full_filename})" unless FileTest.exist?(@full_filename)
@raw_response = `#{@ffmpeg_binary} -i #{Shellwords.shellescape @full_filename} 2>&1`
else
raise ArgumentError, "Must supply either an input file or a pregenerated response" if options[:raw_response].nil? and file.nil?
end
metadata = metadata_match
if /Unknown format/i.match(@raw_response) || metadata.nil?
@unknown_format = true
elsif /Duration: N\/A/im.match(@raw_response)
# elsif /Duration: N\/A|bitrate: N\/A/im.match(@raw_response)
@unreadable_file = true
@raw_metadata = metadata[1] # in this case, we can at least still get the container type
else
@raw_metadata = metadata[1]
end
end
#
# Returns true if the file can be read successfully. Returns false otherwise.
#
def valid?
if @unknown_format or @unreadable_file
false
else
true
end
end
#
# Returns false if the file can be read successfully. Returns false otherwise.
#
def invalid?
!valid?
end
#
# True if the format is not understood ("Unknown Format")
#
def unknown_format?
if @unknown_format
true
else
false
end
end
#
# True if the file is not readable ("Duration: N/A, bitrate: N/A")
#
def unreadable_file?
if @unreadable_file
true
else
false
end
end
#
# Does the file have an audio stream?
#
def audio?
if audio_match.nil?
false
else
true
end
end
#
# Does the file have a video stream?
#
def video?
if video_match.nil?
false
else
true
end
end
#
# Take a screengrab of a movie. Requires an input file and a time parameter, and optionally takes an output filename. If no output filename is specfied, constructs one.
#
# Three types of time parameters are accepted - percentage (e.g. 3%), time in seconds (e.g. 60 seconds), and raw frame (e.g. 37). Will raise an exception if the time in seconds or the frame are out of the bounds of the input file.
#
# Types:
# 37s (37 seconds)
# 37f (frame 37)
# 37% (37 percent)
# 37 (default to seconds)
#
# If a time is outside of the duration of the file, it will choose a frame at the 99% mark.
#
# Example:
#
# t = RVideo::Transcoder.new('path/to/input_file.mp4')
# t.capture_frame('10%') # => '/path/to/screenshot/input-10p.jpg'
#
def capture_frame(timecode, output_file = nil)
t = calculate_time(timecode)
unless output_file
output_file = "#{TEMP_PATH}/#{File.basename(@full_filename, ".*")}-#{timecode.gsub("%","p")}.jpg"
end
# do the work
# mplayer $input_file$ -ss $start_time$ -frames 1 -vo jpeg -o $output_file$
# ffmpeg -i $input_file$ -v nopb -ss $start_time$ -b $bitrate$ -an -vframes 1 -y $output_file$
command = "ffmpeg -i #{@full_filename} -ss #{t} -t 00:00:01 -r 1 -vframes 1 -f image2 #{output_file}"
Transcoder.logger.info("\nCreating Screenshot: #{command}\n")
frame_result = `#{command} 2>&1`
# Different versions of ffmpeg report errors differently when a screenshot cannot be extracted from
# a video given its set of options. Some versions return a non-zero exit code and report errors while
# others simply
unless File.exists?(output_file)
msg = <<-EOT.gsub(/(^\s+|\n)/, '')
This means that ffmpeg could not extract a screenshot from the video. It may indicate that
the video file was corrupt or that the requested frame to be captured was outside the length
of the video. Full command: #{command}
EOT
Transcoder.logger.error msg
raise TranscoderError::OutputFileNotFound, msg
end
Transcoder.logger.info("\nScreenshot results: #{frame_result}")
output_file
end
def calculate_time(timecode)
m = /\A([0-9\.\,]*)(s|f|%)?\Z/.match(timecode)
if m.nil? or m[1].nil? or m[1].empty?
raise TranscoderError::ParameterError, "Invalid timecode for frame capture: #{timecode}. Must be a number, optionally followed by s, f, or %."
end
case m[2]
when "s", nil
t = m[1].to_f
when "f"
t = m[1].to_f / fps.to_f
when "%"
# milliseconds / 1000 * percent / 100
t = (duration.to_i / 1000.0) * (m[1].to_f / 100.0)
else
raise TranscoderError::ParameterError, "Invalid timecode for frame capture: #{timecode}. Must be a number, optionally followed by s, f, or p."
end
if (t * 1000) > duration
calculate_time("99%")
else
t
end
end
#
# Returns the version of ffmpeg used, In practice, this may or may not be
# useful.
#
# Examples:
#
# SVN-r6399
# CVS
#
def ffmpeg_version
@ffmpeg_version = @raw_response.split("\n").first.split("version").last.split(",").first.strip
end
#
# Returns the configuration options used to build ffmpeg.
#
# Example:
#
# --enable-mp3lame --enable-gpl --disable-ffplay --disable-ffserver
# --enable-a52 --enable-xvid
#
def ffmpeg_configuration
/(\s*configuration:)(.*)\n/.match(@raw_response)[2].strip
end
#
# Returns the versions of libavutil, libavcodec, and libavformat used by
# ffmpeg.
#
# Example:
#
# libavutil version: 49.0.0
# libavcodec version: 51.9.0
# libavformat version: 50.4.0
#
def ffmpeg_libav
/^(\s*lib.*\n)+/.match(@raw_response)[0].split("\n").each {|l| l.strip! }
end
#
# Returns the build description for ffmpeg.
#
# Example:
#
# built on Apr 15 2006 04:58:19, gcc: 4.0.1 (Apple Computer, Inc. build
# 5250)
#
def ffmpeg_build
/(\n\s*)(built on.*)(\n)/.match(@raw_response)[2]
end
#
# Returns the container format for the file. Instead of returning a single
# format, this may return a string of related formats.
#
# Examples:
#
# "avi"
#
# "mov,mp4,m4a,3gp,3g2,mj2"
#
def container
return nil if @unknown_format
/Input \#\d+\,\s*(\S+),\s*from/.match(@raw_metadata)[1]
end
#
# The duration of the movie, as a string.
#
# Example:
#
# "00:00:24.4" # 24.4 seconds
#
def raw_duration
return nil unless valid?
/Duration:\s*([0-9\:\.]+),/.match(@raw_metadata)[1]
end
#
# The duration of the movie in milliseconds, as an integer.
#
# Example:
#
# 24400 # 24.4 seconds
#
# Note that the precision of the duration is in tenths of a second, not
# thousandths, but milliseconds are a more standard unit of time than
# deciseconds.
#
#
# The bitrate of the movie.
#
# Example:
#
# 3132
#
def bitrate
return nil unless valid?
bitrate_match[1].to_i
end
#
# The bitrate units used. In practice, this may always be kb/s.
#
# Example:
#
# "kb/s"
#
def bitrate_units
return nil unless valid?
bitrate_match[2]
end
def audio_bit_rate # :nodoc:
nil
end
def audio_stream
return nil unless valid?
#/\n\s*Stream.*Audio:.*\n/.match(@raw_response)[0].strip
match = /\n\s*Stream.*Audio:.*\n/.match(@raw_response)
return match[0].strip if match
end
#
# The audio codec used.
#
# Example:
#
# "aac"
#
def audio_codec
return nil unless audio?
audio_match[2]
end
#
# The sampling rate of the audio stream.
#
# Example:
#
# 44100
#
def audio_sample_rate
return nil unless audio?
audio_match[3].to_i
end
#
# The units used for the sampling rate. May always be Hz.
#
# Example:
#
# "Hz"
#
def audio_sample_units
return nil unless audio?
audio_match[4]
end
#
# The channels used in the audio stream.
#
# Examples:
# "stereo"
# "mono"
# "5:1"
#
def audio_channels_string
return nil unless audio?
audio_match[5]
end
def audio_channels
return nil unless audio?
case audio_match[5]
when "mono"
1
when "stereo"
2
when "5.1"
6
else
raise RuntimeError, "Unknown number of channels: #{audio_match[5]}"
end
end
#
# The ID of the audio stream (useful for troubleshooting).
#
# Example:
# #0.1
#
def audio_stream_id
return nil unless audio?
audio_match[1]
end
def video_stream
return nil unless valid?
match = /\n\s*Stream.*Video:.*\n/.match(@raw_response)
return match[0].strip unless match.nil?
nil
end
#
# The ID of the video stream (useful for troubleshooting).
#
# Example:
# #0.0
#
def video_stream_id
return nil unless video?
video_match[1]
end
#
# The video codec used.
#
# Example:
#
# "mpeg4"
#
def video_codec
return nil unless video?
video_match[2]
end
#
# The colorspace of the video stream.
#
# Example:
#
# "yuv420p"
#
def video_colorspace
return nil unless video?
video_match[3]
end
#
# The width of the video in pixels.
#
def width
return nil unless video?
video_match[4].to_i
end
#
# The height of the video in pixels.
#
def height
return nil unless video?
video_match[5].to_i
end
#
# width x height, as a string.
#
# Examples:
# 320x240
# 1280x720
#
def resolution
return nil unless video?
"#{width}x#{height}"
end
#
# The frame rate of the video in frames per second
#
# Example:
#
# "29.97"
#
def fps
return nil unless video?
/([0-9\.]+) (fps|tb)/.match(video_stream)[1]
end
private
def metadata_match
[
/(Input \#.*)\nMust/m, # ffmpeg
/(Input \#.*)\nAt least/m # ffmpeg macports
].each do |rgx|
if md=rgx.match(@raw_response)
return md
end
end
nil
end
def bitrate_match
/bitrate: ([0-9\.]+)\s*(.*)\s+/.match(@raw_metadata)
end
def audio_match
return nil unless valid?
/Stream\s*(.*?)[,|:|\(|\[].*?\s*Audio:\s*(.*?),\s*([0-9\.]*) (\w*),\s*([a-zA-Z:5\.1]*)/.match(audio_stream)
end
def video_match
return nil unless valid?
match = /Stream\s*(.*?)[,|:|\(|\[].*?\s*Video:\s*(.*?),\s*(.*?),\s*(\d*)x(\d*)/.match(video_stream)
# work-around for Apple Intermediate format, which does not have a color space
# I fake up a match data object (yea, duck typing!) with an empty spot where
# the color space would be.
if match.nil?
match = /Stream\s*(.*?)[,|:|\(|\[].*?\s*Video:\s*(.*?),\s*(\d*)x(\d*)/.match(video_stream)
match = [nil, match[1], match[2], nil, match[3], match[4]] unless match.nil?
end
match
end
end
|
moneta-rb/moneta | lib/moneta/mixins.rb | Moneta.IncrementSupport.increment | ruby | def increment(key, amount = 1, options = {})
value = Utils.to_int(load(key, options)) + amount
store(key, value.to_s, options)
value
end | (see Defaults#increment) | train | https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L409-L413 | module IncrementSupport
# (see Defaults#increment)
def self.included(base)
base.supports(:increment) if base.respond_to?(:supports)
end
end
|
docwhat/lego_nxt | lib/lego_nxt/low_level/usb_connection.rb | LegoNXT::LowLevel.UsbConnection.open | ruby | def open
context = LIBUSB::Context.new
device = context.devices(:idVendor => LEGO_VENDOR_ID, :idProduct => NXT_PRODUCT_ID).first
raise ::LegoNXT::NoDeviceError.new("Please make sure the device is plugged in and powered on") if device.nil?
@handle = device.open
@handle.claim_interface(0)
end | Opens the connection
This is triggered automatically by intantiating the object.
@return [nil] | train | https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/usb_connection.rb#L107-L113 | class UsbConnection
# The USB idVendor code
LEGO_VENDOR_ID = 0x0694
# The USB idProduct code
NXT_PRODUCT_ID = 0x0002
# The USB endpoint (communication channel) to send data out to the NXT brick
USB_ENDPOINT_OUT = 0x01
# The USB endpoint (communication channel) to receive data from the NXT brick
USB_ENDPOINT_IN = 0x82
# Creates a connection to the NXT brick.
#
def initialize
open
end
# Sends a packed string of bits.
#
# Example:
#
# # Causes the brick to beep
# conn.transmit [0x80, 0x03, 0xf4, 0x01, 0xf4, 0x01].pack('C*')'
#
# @see The LEGO MINDSTORMS NXT Communications Protocol (Appendex 1 of the Bluetooth Development Kit)
#
# @param {String} bits This must be a binary string. Use `Array#pack('C*')` to generate the string.
# @return [Boolean] Returns true if all the data was sent and received by the NXT.
def transmit! bits
bytes_sent = @handle.bulk_transfer dataOut: bits, endpoint: USB_ENDPOINT_OUT
bytes_sent == bits.length
end
# {include:UsbConnection#transmit!}
#
# Unlike {#transmit!}, this command will raise an error for some badly formed op codes.
#
# @raise [BadOpCodeError] Raised when the first bit is not a `NO_RESPONSE` op code.
# @param {String} bits This must be a binary string. Use `Array#pack('C*')` to generate the string.
# @return [Boolean] Returns true if all the data was sent and received by the NXT.
def transmit bits
raise ::LegoNXT::BadOpCodeError unless bytestring(DirectOps::NO_RESPONSE, SystemOps::NO_RESPONSE).include? bits[0]
transmit! bits
end
# Sends a packet string of bits and then receives a result.
#
# Example:
#
# # Causes the brick to beep
# conn.transceive [0x80, 0x03, 0xf4, 0x01, 0xf4, 0x01].pack('C*')'
#
# @see The LEGO MINDSTORMS NXT Communications Protocol (Appendex 1 of the Bluetooth Development Kit)
#
# @param {String} bits This must be a binary string. Use `Array#pack('C*')` to generate the string.
# @raise {LegoNXT::TransmitError} Raised if the {#transmit} fails.
# @return [String] A packed string of the response bits. Use `String#unpack('C*')`.
def transceive bits
raise ::LegoNXT::BadOpCodeError unless bytestring(DirectOps::REQUIRE_RESPONSE, SystemOps::REQUIRE_RESPONSE).include? bits[0]
raise ::LegoNXT::TransmitError unless transmit! bits
bytes_received = @handle.bulk_transfer dataIn: 64, endpoint: USB_ENDPOINT_IN
return bytes_received
end
# Closes the connection
#
# @return [nil]
def close
return if @handle.nil?
@handle.close
@handle = nil
end
private
# Opens the connection
#
# This is triggered automatically by intantiating the object.
#
# @return [nil]
end
|
litaio/lita | lib/lita/configuration_builder.rb | Lita.ConfigurationBuilder.validate | ruby | def validate(&block)
validator = block
unless value.nil?
error = validator.call(value)
raise ValidationError, error if error
end
@validator = block
end | Declares a block to be used to validate the value of an attribute whenever it's set.
Validation blocks should return any object to indicate an error, or +nil+/+false+ if
validation passed.
@yield The code that performs validation.
@return [void] | train | https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_builder.rb#L155-L164 | class ConfigurationBuilder
# An array of any nested configuration builders.
# @return [Array<ConfigurationBuilder>] The array of child configuration builders.
# @api private
attr_reader :children
# An array of valid types for the attribute.
# @return [Array<Object>] The array of valid types.
# @api private
attr_reader :types
# A block used to validate the attribute.
# @return [Proc] The validation block.
# @api private
attr_reader :validator
# The name of the configuration attribute.
# @return [String, Symbol] The attribute's name.
# @api private
attr_accessor :name
# The value of the configuration attribute.
# @return [Object] The attribute's value.
# @api private
attr_reader :value
# A boolean indicating whether or not the attribute must be set.
# @return [Boolean] Whether or not the attribute is required.
# @api private
attr_accessor :required
alias required? required
class << self
# Deeply freezes a configuration object so that it can no longer be modified.
# @param config [Configuration] The configuration object to freeze.
# @return [void]
# @api private
def freeze_config(config)
IceNine.deep_freeze!(config)
end
# Loads configuration from a user configuration file.
# @param config_path [String] The path to the configuration file.
# @return [void]
# @api private
def load_user_config(config_path = nil)
config_path ||= "lita_config.rb"
if File.exist?(config_path)
begin
load(config_path)
rescue ValidationError
abort
rescue Exception => e
Lita.logger.fatal I18n.t(
"lita.config.exception",
message: e.message,
backtrace: e.backtrace.join("\n")
)
abort
end
end
end
end
def initialize
@children = []
@name = :root
end
# Builds a {Configuration} object from the attributes defined on the builder.
# @param object [Configuration] The empty configuration object that will be extended to
# create the final form.
# @return [Configuration] The fully built configuration object.
# @api private
def build(object = Configuration.new)
container = if children.empty?
build_leaf(object)
else
build_nested(object)
end
container.public_send(name)
end
# Returns a boolean indicating whether or not the attribute has any child attributes.
# @return [Boolean] Whether or not the attribute has any child attributes.
# @api private
def children?
!children.empty?
end
# Merges two configuration builders by making one an attribute on the other.
# @param name [String, Symbol] The name of the new attribute.
# @param attribute [ConfigurationBuilder] The configuration builder that should be its
# value.
# @return [void]
# @api private
def combine(name, attribute)
attribute.name = name
children << attribute
end
# Declares a configuration attribute.
# @param name [String, Symbol] The attribute's name.
# @param types [Object, Array<Object>] Optional: One or more types that the attribute's value
# must be.
# @param type [Object, Array<Object>] Optional: One or more types that the attribute's value
# must be.
# @param required [Boolean] Whether or not this attribute must be set. If required, and Lita
# is run without it set, Lita will abort on start up with a message about it.
# @param default [Object] An optional default value for the attribute.
# @yield A block to be evaluated in the context of the new attribute. Used for
# defining nested configuration attributes and validators.
# @return [void]
def config(name, types: nil, type: nil, required: false, default: nil, &block)
attribute = self.class.new
attribute.name = name
attribute.types = types || type
attribute.required = required
attribute.value = default
attribute.instance_exec(&block) if block
children << attribute
end
# Sets the valid types for the configuration attribute.
# @param types [Object, Array<Object>] One or more valid types.
# @return [void]
# @api private
def types=(types)
@types = Array(types) if types
end
# Declares a block to be used to validate the value of an attribute whenever it's set.
# Validation blocks should return any object to indicate an error, or +nil+/+false+ if
# validation passed.
# @yield The code that performs validation.
# @return [void]
# Sets the value of the attribute, raising an error if it is not among the valid types.
# @param value [Object] The new value of the attribute.
# @return [void]
# @raise [TypeError] If the new value is not among the declared valid types.
# @api private
def value=(value)
ensure_valid_default_value(value)
@value = value
end
private
# Finalize a nested object.
def build_leaf(object)
this = self
run_validator = method(:run_validator)
check_types = method(:check_types)
object.instance_exec do
define_singleton_method(this.name) { this.value }
define_singleton_method("#{this.name}=") do |value|
run_validator.call(value)
check_types.call(value)
this.value = value
end
end
object
end
# Finalize the root builder or any builder with children.
def build_nested(object)
this = self
nested_object = Configuration.new
children.each { |child| child.build(nested_object) }
object.instance_exec { define_singleton_method(this.name) { nested_object } }
object
end
# Check's the value's type from inside the finalized object.
def check_types(value)
if types&.none? { |type| type === value }
Lita.logger.fatal(
I18n.t("lita.config.type_error", attribute: name, types: types.join(", "))
)
raise ValidationError
end
end
# Raise if value is non-nil and isn't one of the specified types.
def ensure_valid_default_value(value)
if !value.nil? && types && types.none? { |type| type === value }
raise TypeError, I18n.t("lita.config.type_error", attribute: name, types: types.join(", "))
end
end
# Runs the validator from inside the build configuration object.
def run_validator(value)
return unless validator
error = validator.call(value)
if error
Lita.logger.fatal(
I18n.t("lita.config.validation_error", attribute: name, message: error)
)
raise ValidationError
end
end
end
|
hashicorp/vagrant | lib/vagrant/registry.rb | Vagrant.Registry.get | ruby | def get(key)
return nil if !@items.key?(key)
return @results_cache[key] if @results_cache.key?(key)
@results_cache[key] = @items[key].call
end | Get a value by the given key.
This will evaluate the block given to `register` and return the
resulting value. | train | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/registry.rb#L24-L28 | class Registry
def initialize
@items = {}
@results_cache = {}
end
# Register a key with a lazy-loaded value.
#
# If a key with the given name already exists, it is overwritten.
def register(key, &block)
raise ArgumentError, "block required" if !block_given?
@items[key] = block
end
# Get a value by the given key.
#
# This will evaluate the block given to `register` and return the
# resulting value.
alias :[] :get
# Checks if the given key is registered with the registry.
#
# @return [Boolean]
def key?(key)
@items.key?(key)
end
alias_method :has_key?, :key?
# Returns an array populated with the keys of this object.
#
# @return [Array]
def keys
@items.keys
end
# Iterate over the keyspace.
def each(&block)
@items.each do |key, _|
yield key, get(key)
end
end
# Return the number of elements in this registry.
#
# @return [Integer]
def length
@items.keys.length
end
alias_method :size, :length
# Checks if this registry has any items.
#
# @return [Boolean]
def empty?
@items.keys.empty?
end
# Merge one registry with another and return a completely new
# registry. Note that the result cache is completely busted, so
# any gets on the new registry will result in a cache miss.
def merge(other)
self.class.new.tap do |result|
result.merge!(self)
result.merge!(other)
end
end
# Like #{merge} but merges into self.
def merge!(other)
@items.merge!(other.__internal_state[:items])
self
end
# Converts this registry to a hash
def to_hash
result = {}
self.each do |key, value|
result[key] = value
end
result
end
def __internal_state
{
items: @items,
results_cache: @results_cache
}
end
end
|
algolia/algoliasearch-client-ruby | lib/algolia/index.rb | Algolia.Index.get_settings | ruby | def get_settings(options = {}, request_options = {})
options['getVersion'] = 2 if !options[:getVersion] && !options['getVersion']
client.get(Protocol.settings_uri(name, options).to_s, :read, request_options)
end | Get settings of this index | train | https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L617-L620 | class Index
attr_accessor :name, :client
def initialize(name, client = nil)
self.name = name
self.client = client || Algolia.client
end
#
# Delete an index
#
# @param request_options contains extra parameters to send with your query
#
# return an hash of the form { "deletedAt" => "2013-01-18T15:33:13.556Z", "taskID" => "42" }
#
def delete(request_options = {})
client.delete(Protocol.index_uri(name), :write, request_options)
end
alias_method :delete_index, :delete
#
# Delete an index and wait until the deletion has been processed
#
# @param request_options contains extra parameters to send with your query
#
# return an hash of the form { "deletedAt" => "2013-01-18T15:33:13.556Z", "taskID" => "42" }
#
def delete!(request_options = {})
res = delete(request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
alias_method :delete_index!, :delete!
#
# Add an object in this index
#
# @param object the object to add to the index.
# The object is represented by an associative array
# @param objectID (optional) an objectID you want to attribute to this object
# (if the attribute already exist the old object will be overridden)
# @param request_options contains extra parameters to send with your query
#
def add_object(object, objectID = nil, request_options = {})
check_object(object)
if objectID.nil? || objectID.to_s.empty?
client.post(Protocol.index_uri(name), object.to_json, :write, request_options)
else
client.put(Protocol.object_uri(name, objectID), object.to_json, :write, request_options)
end
end
#
# Add an object in this index and wait end of indexing
#
# @param object the object to add to the index.
# The object is represented by an associative array
# @param objectID (optional) an objectID you want to attribute to this object
# (if the attribute already exist the old object will be overridden)
# @param Request options object. Contains extra URL parameters or headers
#
def add_object!(object, objectID = nil, request_options = {})
res = add_object(object, objectID, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Add several objects in this index
#
# @param objects the array of objects to add inside the index.
# Each object is represented by an associative array
# @param request_options contains extra parameters to send with your query
#
def add_objects(objects, request_options = {})
batch(build_batch('addObject', objects, false), request_options)
end
#
# Add several objects in this index and wait end of indexing
#
# @param objects the array of objects to add inside the index.
# Each object is represented by an associative array
# @param request_options contains extra parameters to send with your query
#
def add_objects!(objects, request_options = {})
res = add_objects(objects, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Search inside the index
#
# @param query the full text query
# @param args (optional) if set, contains an associative array with query parameters:
# - page: (integer) Pagination parameter used to select the page to retrieve.
# Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9
# - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
# - attributesToRetrieve: a string that contains the list of object attributes you want to retrieve (let you minimize the answer size).
# Attributes are separated with a comma (for example "name,address").
# You can also use a string array encoding (for example ["name","address"]).
# By default, all attributes are retrieved. You can also use '*' to retrieve all values when an attributesToRetrieve setting is specified for your index.
# - attributesToHighlight: a string that contains the list of attributes you want to highlight according to the query.
# Attributes are separated by a comma. You can also use a string array encoding (for example ["name","address"]).
# If an attribute has no match for the query, the raw value is returned. By default all indexed text attributes are highlighted.
# You can use `*` if you want to highlight all textual attributes. Numerical attributes are not highlighted.
# A matchLevel is returned for each highlighted attribute and can contain:
# - full: if all the query terms were found in the attribute,
# - partial: if only some of the query terms were found,
# - none: if none of the query terms were found.
# - attributesToSnippet: a string that contains the list of attributes to snippet alongside the number of words to return (syntax is `attributeName:nbWords`).
# Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
# You can also use a string array encoding (Example: attributesToSnippet: ["name:10","content:10"]). By default no snippet is computed.
# - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. Defaults to 3.
# - minWordSizefor2Typos: the minimum number of characters in a query word to accept two typos in this word. Defaults to 7.
# - getRankingInfo: if set to 1, the result hits will contain ranking information in _rankingInfo attribute.
# - aroundLatLng: search for entries around a given latitude/longitude (specified as two floats separated by a comma).
# For example aroundLatLng=47.316669,5.016670).
# You can specify the maximum distance in meters with the aroundRadius parameter (in meters) and the precision for ranking with aroundPrecision
# (for example if you set aroundPrecision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter).
# At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
# - insideBoundingBox: search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
# For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
# At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
# - numericFilters: a string that contains the list of numeric filters you want to apply separated by a comma.
# The syntax of one filter is `attributeName` followed by `operand` followed by `value`. Supported operands are `<`, `<=`, `=`, `>` and `>=`.
# You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
# You can also use a string array encoding (for example numericFilters: ["price>100","price<1000"]).
# - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
# To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
# You can also use a string array encoding, for example tagFilters: ["tag1",["tag2","tag3"]] means tag1 AND (tag2 OR tag3).
# At indexing, tags should be added in the _tags** attribute of objects (for example {"_tags":["tag1","tag2"]}).
# - facetFilters: filter the query by a list of facets.
# Facets are separated by commas and each facet is encoded as `attributeName:value`.
# For example: `facetFilters=category:Book,author:John%20Doe`.
# You can also use a string array encoding (for example `["category:Book","author:John%20Doe"]`).
# - facets: List of object attributes that you want to use for faceting.
# Attributes are separated with a comma (for example `"category,author"` ).
# You can also use a JSON string array encoding (for example ["category","author"]).
# Only attributes that have been added in **attributesForFaceting** index setting can be used in this parameter.
# You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
# - queryType: select how the query words are interpreted, it can be one of the following value:
# - prefixAll: all query words are interpreted as prefixes,
# - prefixLast: only the last word is interpreted as a prefix (default behavior),
# - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
# - optionalWords: a string that contains the list of words that should be considered as optional when found in the query.
# The list of words is comma separated.
# - distinct: If set to 1, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set.
# This feature is similar to the SQL "distinct" keyword: when enabled in a query with the distinct=1 parameter,
# all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
# For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best
# one is kept and others are removed.
# @param request_options contains extra parameters to send with your query
#
def search(query, params = {}, request_options = {})
encoded_params = Hash[params.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }]
encoded_params[:query] = query
client.post(Protocol.search_post_uri(name), { :params => Protocol.to_query(encoded_params) }.to_json, :search, request_options)
end
class IndexBrowser
def initialize(client, name, params)
@client = client
@name = name
@params = params
@cursor = params[:cursor] || params['cursor'] || nil
end
def browse(request_options = {}, &block)
loop do
answer = @client.get(Protocol.browse_uri(@name, @params.merge({ :cursor => @cursor })), :read, request_options)
answer['hits'].each do |hit|
if block.arity == 2
yield hit, @cursor
else
yield hit
end
end
@cursor = answer['cursor']
break if @cursor.nil?
end
end
end
#
# Browse all index content
#
# @param queryParameters The hash of query parameters to use to browse
# To browse from a specific cursor, just add a ":cursor" parameters
# @param queryParameters An optional second parameters hash here for backward-compatibility (which will be merged with the first)
# @param request_options contains extra parameters to send with your query
#
# @DEPRECATED:
# @param page Pagination parameter used to select the page to retrieve.
# @param hits_per_page Pagination parameter used to select the number of hits per page. Defaults to 1000.
#
def browse(page_or_query_parameters = nil, hits_per_page = nil, request_options = {}, &block)
params = {}
if page_or_query_parameters.is_a?(Hash)
params.merge!(page_or_query_parameters)
else
params[:page] = page_or_query_parameters unless page_or_query_parameters.nil?
end
if hits_per_page.is_a?(Hash)
params.merge!(hits_per_page)
else
params[:hitsPerPage] = hits_per_page unless hits_per_page.nil?
end
if block_given?
IndexBrowser.new(client, name, params).browse(request_options, &block)
else
params[:page] ||= 0
params[:hitsPerPage] ||= 1000
client.get(Protocol.browse_uri(name, params), :read, request_options)
end
end
#
# Browse a single page from a specific cursor
#
# @param request_options contains extra parameters to send with your query
#
def browse_from(cursor, hits_per_page = 1000, request_options = {})
client.post(Protocol.browse_uri(name), { :cursor => cursor, :hitsPerPage => hits_per_page }.to_json, :read, request_options)
end
#
# Get an object from this index
#
# @param objectID the unique identifier of the object to retrieve
# @param attributes_to_retrieve (optional) if set, contains the list of attributes to retrieve as an array of strings of a string separated by ","
# @param request_options contains extra parameters to send with your query
#
def get_object(objectID, attributes_to_retrieve = nil, request_options = {})
attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array)
if attributes_to_retrieve.nil?
client.get(Protocol.object_uri(name, objectID, nil), :read, request_options)
else
client.get(Protocol.object_uri(name, objectID, { :attributes => attributes_to_retrieve }), :read, request_options)
end
end
#
# Get a list of objects from this index
#
# @param objectIDs the array of unique identifier of the objects to retrieve
# @param attributes_to_retrieve (optional) if set, contains the list of attributes to retrieve as an array of strings of a string separated by ","
# @param request_options contains extra parameters to send with your query
#
def get_objects(objectIDs, attributes_to_retrieve = nil, request_options = {})
attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array)
requests = objectIDs.map do |objectID|
req = { :indexName => name, :objectID => objectID.to_s }
req[:attributesToRetrieve] = attributes_to_retrieve unless attributes_to_retrieve.nil?
req
end
client.post(Protocol.objects_uri, { :requests => requests }.to_json, :read, request_options)['results']
end
#
# Check the status of a task on the server.
# All server task are asynchronous and you can check the status of a task with this method.
#
# @param taskID the id of the task returned by server
# @param request_options contains extra parameters to send with your query
#
def get_task_status(taskID, request_options = {})
client.get_task_status(name, taskID, request_options)
end
#
# Wait the publication of a task on the server.
# All server task are asynchronous and you can check with this method that the task is published.
#
# @param taskID the id of the task returned by server
# @param time_before_retry the time in milliseconds before retry (default = 100ms)
# @param request_options contains extra parameters to send with your query
#
def wait_task(taskID, time_before_retry = WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options = {})
client.wait_task(name, taskID, time_before_retry, request_options)
end
#
# Override the content of an object
#
# @param object the object to save
# @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key
# @param request_options contains extra parameters to send with your query
#
def save_object(object, objectID = nil, request_options = {})
client.put(Protocol.object_uri(name, get_objectID(object, objectID)), object.to_json, :write, request_options)
end
#
# Override the content of object and wait end of indexing
#
# @param object the object to save
# @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key
# @param request_options contains extra parameters to send with your query
#
def save_object!(object, objectID = nil, request_options = {})
res = save_object(object, objectID, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Override the content of several objects
#
# @param objects the array of objects to save, each object must contain an 'objectID' key
# @param request_options contains extra parameters to send with your query
#
def save_objects(objects, request_options = {})
batch(build_batch('updateObject', objects, true), request_options)
end
#
# Override the content of several objects and wait end of indexing
#
# @param objects the array of objects to save, each object must contain an objectID attribute
# @param request_options contains extra parameters to send with your query
#
def save_objects!(objects, request_options = {})
res = save_objects(objects, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Override the current objects by the given array of objects and wait end of indexing. Settings,
# synonyms and query rules are untouched. The objects are replaced without any downtime.
#
# @param objects the array of objects to save
# @param request_options contains extra parameters to send with your query
#
def replace_all_objects(objects, request_options = {})
safe = request_options[:safe] || request_options['safe'] || false
request_options.delete(:safe)
request_options.delete('safe')
tmp_index = @client.init_index(@name + '_tmp_' + rand(10000000).to_s)
responses = []
scope = ['settings', 'synonyms', 'rules']
res = @client.copy_index(@name, tmp_index.name, scope, request_options)
responses << res
if safe
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
end
batch = []
batch_size = 1000
count = 0
objects.each do |object|
batch << object
count += 1
if count == batch_size
res = tmp_index.add_objects(batch, request_options)
responses << res
batch = []
count = 0
end
end
if batch.any?
res = tmp_index.add_objects(batch, request_options)
responses << res
end
if safe
responses.each do |res|
tmp_index.wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
end
end
res = @client.move_index(tmp_index.name, @name, request_options)
responses << res
if safe
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
end
responses
end
#
# Override the current objects by the given array of objects and wait end of indexing
#
# @param objects the array of objects to save
# @param request_options contains extra parameters to send with your query
#
def replace_all_objects!(objects, request_options = {})
replace_all_objects(objects, request_options.merge(:safe => true))
end
#
# Update partially an object (only update attributes passed in argument)
#
# @param object the object attributes to override
# @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key
# @param create_if_not_exits a boolean, if true creates the object if this one doesn't exist
# @param request_options contains extra parameters to send with your query
#
def partial_update_object(object, objectID = nil, create_if_not_exits = true, request_options = {})
client.post(Protocol.partial_object_uri(name, get_objectID(object, objectID), create_if_not_exits), object.to_json, :write, request_options)
end
#
# Partially override the content of several objects
#
# @param objects an array of objects to update (each object must contains a objectID attribute)
# @param create_if_not_exits a boolean, if true create the objects if they don't exist
# @param request_options contains extra parameters to send with your query
#
def partial_update_objects(objects, create_if_not_exits = true, request_options = {})
if create_if_not_exits
batch(build_batch('partialUpdateObject', objects, true), request_options)
else
batch(build_batch('partialUpdateObjectNoCreate', objects, true), request_options)
end
end
#
# Partially override the content of several objects and wait end of indexing
#
# @param objects an array of objects to update (each object must contains a objectID attribute)
# @param create_if_not_exits a boolean, if true create the objects if they don't exist
# @param request_options contains extra parameters to send with your query
#
def partial_update_objects!(objects, create_if_not_exits = true, request_options = {})
res = partial_update_objects(objects, create_if_not_exits, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Update partially an object (only update attributes passed in argument) and wait indexing
#
# @param object the attributes to override
# @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key
# @param create_if_not_exits a boolean, if true creates the object if this one doesn't exist
# @param request_options contains extra parameters to send with your query
#
def partial_update_object!(object, objectID = nil, create_if_not_exits = true, request_options = {})
res = partial_update_object(object, objectID, create_if_not_exits, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Delete an object from the index
#
# @param objectID the unique identifier of object to delete
# @param request_options contains extra parameters to send with your query
#
def delete_object(objectID, request_options = {})
raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == ''
client.delete(Protocol.object_uri(name, objectID), :write, request_options)
end
#
# Delete an object from the index and wait end of indexing
#
# @param objectID the unique identifier of object to delete
# @param request_options contains extra parameters to send with your query
#
def delete_object!(objectID, request_options = {})
res = delete_object(objectID, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Delete several objects
#
# @param objects an array of objectIDs
# @param request_options contains extra parameters to send with your query
#
def delete_objects(objects, request_options = {})
check_array(objects)
batch(build_batch('deleteObject', objects.map { |objectID| { :objectID => objectID } }, false), request_options)
end
#
# Delete several objects and wait end of indexing
#
# @param objects an array of objectIDs
# @param request_options contains extra parameters to send with your query
#
def delete_objects!(objects, request_options = {})
res = delete_objects(objects, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Delete all objects matching a query
# This method retrieves all objects synchronously but deletes in batch
# asynchronously
#
# @param query the query string
# @param params the optional query parameters
# @param request_options contains extra parameters to send with your query
#
def delete_by_query(query, params = nil, request_options = {})
raise ArgumentError.new('query cannot be nil, use the `clear` method to wipe the entire index') if query.nil? && params.nil?
params = sanitized_delete_by_query_params(params)
params[:query] = query
params[:hitsPerPage] = 1000
params[:distinct] = false
params[:attributesToRetrieve] = ['objectID']
params[:cursor] = ''
ids = []
while params[:cursor] != nil
result = browse(params, nil, request_options)
params[:cursor] = result['cursor']
hits = result['hits']
break if hits.empty?
ids += hits.map { |hit| hit['objectID'] }
end
delete_objects(ids, request_options)
end
#
# Delete all objects matching a query and wait end of indexing
#
# @param query the query string
# @param params the optional query parameters
# @param request_options contains extra parameters to send with your query
#
def delete_by_query!(query, params = nil, request_options = {})
res = delete_by_query(query, params, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) if res
res
end
#
# Delete all objects matching a query (doesn't work with actual text queries)
# This method deletes every record matching the filters provided
#
# @param params query parameters
# @param request_options contains extra parameters to send with your query
#
def delete_by(params, request_options = {})
raise ArgumentError.new('params cannot be nil, use the `clear` method to wipe the entire index') if params.nil?
params = sanitized_delete_by_query_params(params)
client.post(Protocol.delete_by_uri(name), params.to_json, :write, request_options)
end
#
# Delete all objects matching a query (doesn't work with actual text queries)
# This method deletes every record matching the filters provided and waits for the end of indexing
# @param params query parameters
# @param request_options contains extra parameters to send with your query
#
def delete_by!(params, request_options = {})
res = delete_by(params, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) if res
res
end
#
# Delete the index content
#
# @param request_options contains extra parameters to send with your query
#
def clear(request_options = {})
client.post(Protocol.clear_uri(name), {}, :write, request_options)
end
alias_method :clear_index, :clear
#
# Delete the index content and wait end of indexing
#
def clear!(request_options = {})
res = clear(request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
alias_method :clear_index!, :clear!
#
# Set settings for this index
#
def set_settings(new_settings, options = {}, request_options = {})
client.put(Protocol.settings_uri(name, options), new_settings.to_json, :write, request_options)
end
#
# Set settings for this index and wait end of indexing
#
def set_settings!(new_settings, options = {}, request_options = {})
res = set_settings(new_settings, options, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Get settings of this index
#
#
# List all existing user keys with their associated ACLs
#
# Deprecated: Please us `client.list_api_keys` instead.
def list_api_keys(request_options = {})
client.get(Protocol.index_keys_uri(name), :read, request_options)
end
#
# Get ACL of a user key
#
# Deprecated: Please us `client.get_api_key` instead.
def get_api_key(key, request_options = {})
client.get(Protocol.index_key_uri(name, key), :read, request_options)
end
#
# Create a new user key
#
# @param object can be two different parameters:
# The list of parameters for this key. Defined by a Hash that can
# contains the following values:
# - acl: array of string
# - validity: int
# - referers: array of string
# - description: string
# - maxHitsPerQuery: integer
# - queryParameters: string
# - maxQueriesPerIPPerHour: integer
# Or the list of ACL for this key. Defined by an array of String that
# can contains the following values:
# - search: allow to search (https and http)
# - addObject: allows to add/update an object in the index (https only)
# - deleteObject : allows to delete an existing object (https only)
# - deleteIndex : allows to delete index content (https only)
# - settings : allows to get index settings (https only)
# - editSettings : allows to change index settings (https only)
# @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
# @param max_queries_per_IP_per_hour the maximum number of API calls allowed from an IP address per hour (0 means unlimited)
# @param max_hits_per_query the maximum number of hits this API key can retrieve in one call (0 means unlimited)
# @param request_options contains extra parameters to send with your query
#
# Deprecated: Please use `client.add_api_key` instead
def add_api_key(object, validity = 0, max_queries_per_IP_per_hour = 0, max_hits_per_query = 0, request_options = {})
if object.instance_of?(Array)
params = { :acl => object }
else
params = object
end
params['validity'] = validity.to_i if validity != 0
params['maxHitsPerQuery'] = max_hits_per_query.to_i if max_hits_per_query != 0
params['maxQueriesPerIPPerHour'] = max_queries_per_IP_per_hour.to_i if max_queries_per_IP_per_hour != 0
client.post(Protocol.index_keys_uri(name), params.to_json, :write, request_options)
end
#
# Update a user key
#
# @param object can be two different parameters:
# The list of parameters for this key. Defined by a Hash that
# can contains the following values:
# - acl: array of string
# - validity: int
# - referers: array of string
# - description: string
# - maxHitsPerQuery: integer
# - queryParameters: string
# - maxQueriesPerIPPerHour: integer
# Or the list of ACL for this key. Defined by an array of String that
# can contains the following values:
# - search: allow to search (https and http)
# - addObject: allows to add/update an object in the index (https only)
# - deleteObject : allows to delete an existing object (https only)
# - deleteIndex : allows to delete index content (https only)
# - settings : allows to get index settings (https only)
# - editSettings : allows to change index settings (https only)
# @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
# @param max_queries_per_IP_per_hour the maximum number of API calls allowed from an IP address per hour (0 means unlimited)
# @param max_hits_per_query the maximum number of hits this API key can retrieve in one call (0 means unlimited)
# @param request_options contains extra parameters to send with your query
#
# Deprecated: Please use `client.update_api_key` instead
def update_api_key(key, object, validity = 0, max_queries_per_IP_per_hour = 0, max_hits_per_query = 0, request_options = {})
if object.instance_of?(Array)
params = { :acl => object }
else
params = object
end
params['validity'] = validity.to_i if validity != 0
params['maxHitsPerQuery'] = max_hits_per_query.to_i if max_hits_per_query != 0
params['maxQueriesPerIPPerHour'] = max_queries_per_IP_per_hour.to_i if max_queries_per_IP_per_hour != 0
client.put(Protocol.index_key_uri(name, key), params.to_json, :write, request_options)
end
#
# Delete an existing user key
#
# Deprecated: Please use `client.delete_api_key` instead
def delete_api_key(key, request_options = {})
client.delete(Protocol.index_key_uri(name, key), :write, request_options)
end
#
# Send a batch request
#
def batch(request, request_options = {})
client.post(Protocol.batch_uri(name), request.to_json, :batch, request_options)
end
#
# Send a batch request and wait the end of the indexing
#
def batch!(request, request_options = {})
res = batch(request, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Search for facet values
#
# @param facet_name Name of the facet to search. It must have been declared in the
# index's`attributesForFaceting` setting with the `searchable()` modifier.
# @param facet_query Text to search for in the facet's values
# @param search_parameters An optional query to take extra search parameters into account.
# These parameters apply to index objects like in a regular search query.
# Only facet values contained in the matched objects will be returned.
# @param request_options contains extra parameters to send with your query
#
def search_for_facet_values(facet_name, facet_query, search_parameters = {}, request_options = {})
params = search_parameters.clone
params['facetQuery'] = facet_query
client.post(Protocol.search_facet_uri(name, facet_name), params.to_json, :read, request_options)
end
# deprecated
alias_method :search_facet, :search_for_facet_values
#
# Perform a search with disjunctive facets generating as many queries as number of disjunctive facets
#
# @param query the query
# @param disjunctive_facets the array of disjunctive facets
# @param params a hash representing the regular query parameters
# @param refinements a hash ("string" -> ["array", "of", "refined", "values"]) representing the current refinements
# ex: { "my_facet1" => ["my_value1", ["my_value2"], "my_disjunctive_facet1" => ["my_value1", "my_value2"] }
# @param request_options contains extra parameters to send with your query
#
def search_disjunctive_faceting(query, disjunctive_facets, params = {}, refinements = {}, request_options = {})
raise ArgumentError.new('Argument "disjunctive_facets" must be a String or an Array') unless disjunctive_facets.is_a?(String) || disjunctive_facets.is_a?(Array)
raise ArgumentError.new('Argument "refinements" must be a Hash of Arrays') if !refinements.is_a?(Hash) || !refinements.select { |k, v| !v.is_a?(Array) }.empty?
# extract disjunctive facets & associated refinements
disjunctive_facets = disjunctive_facets.split(',') if disjunctive_facets.is_a?(String)
disjunctive_refinements = {}
refinements.each do |k, v|
disjunctive_refinements[k] = v if disjunctive_facets.include?(k) || disjunctive_facets.include?(k.to_s)
end
# build queries
queries = []
## hits + regular facets query
filters = []
refinements.to_a.each do |k, values|
r = values.map { |v| "#{k}:#{v}" }
if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym]
# disjunctive refinements are ORed
filters << r
else
# regular refinements are ANDed
filters += r
end
end
queries << params.merge({ :index_name => self.name, :query => query, :facetFilters => filters })
## one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet)
disjunctive_facets.each do |disjunctive_facet|
filters = []
refinements.each do |k, values|
if k.to_s != disjunctive_facet.to_s
r = values.map { |v| "#{k}:#{v}" }
if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym]
# disjunctive refinements are ORed
filters << r
else
# regular refinements are ANDed
filters += r
end
end
end
queries << params.merge({
:index_name => self.name,
:query => query,
:page => 0,
:hitsPerPage => 1,
:attributesToRetrieve => [],
:attributesToHighlight => [],
:attributesToSnippet => [],
:facets => disjunctive_facet,
:facetFilters => filters,
:analytics => false
})
end
answers = client.multiple_queries(queries, { :request_options => request_options })
# aggregate answers
## first answer stores the hits + regular facets
aggregated_answer = answers['results'][0]
## others store the disjunctive facets
aggregated_answer['disjunctiveFacets'] = {}
answers['results'].each_with_index do |a, i|
next if i == 0
a['facets'].each do |facet, values|
## add the facet to the disjunctive facet hash
aggregated_answer['disjunctiveFacets'][facet] = values
## concatenate missing refinements
(disjunctive_refinements[facet.to_s] || disjunctive_refinements[facet.to_sym] || []).each do |r|
if aggregated_answer['disjunctiveFacets'][facet][r].nil?
aggregated_answer['disjunctiveFacets'][facet][r] = 0
end
end
end
end
aggregated_answer
end
#
# Alias of Algolia.list_indexes
#
# @param request_options contains extra parameters to send with your query
#
def Index.all(request_options = {})
Algolia.list_indexes(request_options)
end
#
# Search synonyms
#
# @param query the query
# @param params an optional hash of :type, :page, :hitsPerPage
# @param request_options contains extra parameters to send with your query
#
def search_synonyms(query, params = {}, request_options = {})
type = params[:type] || params['type']
type = type.join(',') if type.is_a?(Array)
page = params[:page] || params['page'] || 0
hits_per_page = params[:hitsPerPage] || params['hitsPerPage'] || 20
params = {
:query => query,
:type => type.to_s,
:page => page,
:hitsPerPage => hits_per_page
}
client.post(Protocol.search_synonyms_uri(name), params.to_json, :read, request_options)
end
#
# Get a synonym
#
# @param objectID the synonym objectID
# @param request_options contains extra parameters to send with your query
def get_synonym(objectID, request_options = {})
client.get(Protocol.synonym_uri(name, objectID), :read, request_options)
end
#
# Delete a synonym
#
# @param objectID the synonym objectID
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def delete_synonym(objectID, forward_to_replicas = false, request_options = {})
client.delete("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", :write, request_options)
end
#
# Delete a synonym and wait the end of indexing
#
# @param objectID the synonym objectID
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def delete_synonym!(objectID, forward_to_replicas = false, request_options = {})
res = delete_synonym(objectID, forward_to_replicas, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Save a synonym
#
# @param objectID the synonym objectID
# @param synonym the synonym
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def save_synonym(objectID, synonym, forward_to_replicas = false, request_options = {})
client.put("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", synonym.to_json, :write, request_options)
end
#
# Save a synonym and wait the end of indexing
#
# @param objectID the synonym objectID
# @param synonym the synonym
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def save_synonym!(objectID, synonym, forward_to_replicas = false, request_options = {})
res = save_synonym(objectID, synonym, forward_to_replicas, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Clear all synonyms
#
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def clear_synonyms(forward_to_replicas = false, request_options = {})
client.post("#{Protocol.clear_synonyms_uri(name)}?forwardToReplicas=#{forward_to_replicas}", {}, :write, request_options)
end
#
# Clear all synonyms and wait the end of indexing
#
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def clear_synonyms!(forward_to_replicas = false, request_options = {})
res = clear_synonyms(forward_to_replicas, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Add/Update an array of synonyms
#
# @param synonyms the array of synonyms to add/update
# @param forward_to_replicas should we forward the delete to replica indices
# @param replace_existing_synonyms should we replace the existing synonyms before adding the new ones
# @param request_options contains extra parameters to send with your query
#
def batch_synonyms(synonyms, forward_to_replicas = false, replace_existing_synonyms = false, request_options = {})
client.post("#{Protocol.batch_synonyms_uri(name)}?forwardToReplicas=#{forward_to_replicas}&replaceExistingSynonyms=#{replace_existing_synonyms}", synonyms.to_json, :batch, request_options)
end
#
# Add/Update an array of synonyms and wait the end of indexing
#
# @param synonyms the array of synonyms to add/update
# @param forward_to_replicas should we forward the delete to replica indices
# @param replace_existing_synonyms should we replace the existing synonyms before adding the new ones
# @param request_options contains extra parameters to send with your query
#
def batch_synonyms!(synonyms, forward_to_replicas = false, replace_existing_synonyms = false, request_options = {})
res = batch_synonyms(synonyms, forward_to_replicas, replace_existing_synonyms, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Replace synonyms in the index by the given array of synonyms
#
# @param synonyms the array of synonyms to add
# @param request_options contains extra parameters to send with your query
#
def replace_all_synonyms(synonyms, request_options = {})
forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false
batch_synonyms(synonyms, forward_to_replicas, true, request_options)
end
#
# Replace synonyms in the index by the given array of synonyms and wait the end of indexing
#
# @param synonyms the array of synonyms to add
# @param request_options contains extra parameters to send with your query
#
def replace_all_synonyms!(synonyms, request_options = {})
res = replace_all_synonyms(synonyms, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Export the full list of synonyms
# Accepts an optional block to which it will pass each synonym
# Also returns an array with all the synonyms
#
# @param hits_per_page Amount of synonyms to retrieve on each internal request - Optional - Default: 100
# @param request_options contains extra parameters to send with your query - Optional
#
def export_synonyms(hits_per_page = 100, request_options = {}, &_block)
res = []
page = 0
loop do
curr = search_synonyms('', { :hitsPerPage => hits_per_page, :page => page }, request_options)['hits']
curr.each do |synonym|
res << synonym
yield synonym if block_given?
end
break if curr.size < hits_per_page
page += 1
end
res
end
#
# Search rules
#
# @param query the query
# @param params an optional hash of :anchoring, :context, :page, :hitsPerPage
# @param request_options contains extra parameters to send with your query
#
def search_rules(query, params = {}, request_options = {})
anchoring = params[:anchoring]
context = params[:context]
page = params[:page] || params['page'] || 0
hits_per_page = params[:hitsPerPage] || params['hitsPerPage'] || 20
params = {
:query => query,
:page => page,
:hitsPerPage => hits_per_page
}
params[:anchoring] = anchoring unless anchoring.nil?
params[:context] = context unless context.nil?
client.post(Protocol.search_rules_uri(name), params.to_json, :read, request_options)
end
#
# Get a rule
#
# @param objectID the rule objectID
# @param request_options contains extra parameters to send with your query
#
def get_rule(objectID, request_options = {})
client.get(Protocol.rule_uri(name, objectID), :read, request_options)
end
#
# Delete a rule
#
# @param objectID the rule objectID
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def delete_rule(objectID, forward_to_replicas = false, request_options = {})
client.delete("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", :write, request_options)
end
#
# Delete a rule and wait the end of indexing
#
# @param objectID the rule objectID
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def delete_rule!(objectID, forward_to_replicas = false, request_options = {})
res = delete_rule(objectID, forward_to_replicas, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
return res
end
#
# Save a rule
#
# @param objectID the rule objectID
# @param rule the rule
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def save_rule(objectID, rule, forward_to_replicas = false, request_options = {})
raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == ''
client.put("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", rule.to_json, :write, request_options)
end
#
# Save a rule and wait the end of indexing
#
# @param objectID the rule objectID
# @param rule the rule
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def save_rule!(objectID, rule, forward_to_replicas = false, request_options = {})
res = save_rule(objectID, rule, forward_to_replicas, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
return res
end
#
# Clear all rules
#
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def clear_rules(forward_to_replicas = false, request_options = {})
client.post("#{Protocol.clear_rules_uri(name)}?forwardToReplicas=#{forward_to_replicas}", {}, :write, request_options)
end
#
# Clear all rules and wait the end of indexing
#
# @param forward_to_replicas should we forward the delete to replica indices
# @param request_options contains extra parameters to send with your query
#
def clear_rules!(forward_to_replicas = false, request_options = {})
res = clear_rules(forward_to_replicas, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
return res
end
#
# Add/Update an array of rules
#
# @param rules the array of rules to add/update
# @param forward_to_replicas should we forward the delete to replica indices
# @param clear_existing_rules should we clear the existing rules before adding the new ones
# @param request_options contains extra parameters to send with your query
#
def batch_rules(rules, forward_to_replicas = false, clear_existing_rules = false, request_options = {})
client.post("#{Protocol.batch_rules_uri(name)}?forwardToReplicas=#{forward_to_replicas}&clearExistingRules=#{clear_existing_rules}", rules.to_json, :batch, request_options)
end
#
# Add/Update an array of rules and wait the end of indexing
#
# @param rules the array of rules to add/update
# @param forward_to_replicas should we forward the delete to replica indices
# @param clear_existing_rules should we clear the existing rules before adding the new ones
# @param request_options contains extra parameters to send with your query
#
def batch_rules!(rules, forward_to_replicas = false, clear_existing_rules = false, request_options = {})
res = batch_rules(rules, forward_to_replicas, clear_existing_rules, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
return res
end
#
# Replace rules in the index by the given array of rules
#
# @param rules the array of rules to add
# @param request_options contains extra parameters to send with your query
#
def replace_all_rules(rules, request_options = {})
forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false
batch_rules(rules, forward_to_replicas, true, request_options)
end
#
# Replace rules in the index by the given array of rules and wait the end of indexing
#
# @param rules the array of rules to add
# @param request_options contains extra parameters to send with your query
#
def replace_all_rules!(rules, request_options = {})
res = replace_all_rules(rules, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end
#
# Export the full list of rules
# Accepts an optional block to which it will pass each rule
# Also returns an array with all the rules
#
# @param hits_per_page Amount of rules to retrieve on each internal request - Optional - Default: 100
# @param request_options contains extra parameters to send with your query - Optional
#
def export_rules(hits_per_page = 100, request_options = {}, &_block)
res = []
page = 0
loop do
curr = search_rules('', { :hits_per_page => hits_per_page, :page => page }, request_options)['hits']
curr.each do |rule|
res << rule
yield rule if block_given?
end
break if curr.size < hits_per_page
page += 1
end
res
end
# Deprecated
alias_method :get_user_key, :get_api_key
alias_method :list_user_keys, :list_api_keys
alias_method :add_user_key, :add_api_key
alias_method :update_user_key, :update_api_key
alias_method :delete_user_key, :delete_api_key
private
def check_array(object)
raise ArgumentError.new('argument must be an array of objects') if !object.is_a?(Array)
end
def check_object(object, in_array = false)
case object
when Array
raise ArgumentError.new(in_array ? 'argument must be an array of objects' : 'argument must not be an array')
when String, Integer, Float, TrueClass, FalseClass, NilClass
raise ArgumentError.new("argument must be an #{'array of' if in_array} object, got: #{object.inspect}")
else
# ok
end
end
def get_objectID(object, objectID = nil)
check_object(object)
objectID ||= object[:objectID] || object['objectID']
raise ArgumentError.new("Missing 'objectID'") if objectID.nil?
return objectID
end
def build_batch(action, objects, with_object_id = false)
check_array(objects)
{
:requests => objects.map { |object|
check_object(object, true)
h = { :action => action, :body => object }
h[:objectID] = get_objectID(object).to_s if with_object_id
h
}
}
end
def sanitized_delete_by_query_params(params)
params ||= {}
params.delete(:hitsPerPage)
params.delete('hitsPerPage')
params.delete(:attributesToRetrieve)
params.delete('attributesToRetrieve')
params
end
end
|
chicks/sugarcrm | lib/sugarcrm/connection/api/set_note_attachment.rb | SugarCRM.Connection.set_note_attachment | ruby | def set_note_attachment(id, filename, file, opts={})
options = {
:module_id => '',
:module_name => ''
}.merge! opts
login! unless logged_in?
json = <<-EOF
{
"session": "#{@sugar_session_id}",
"note": {
"id": "#{id}",
"filename": "#{filename}",
"file": "#{b64_encode(file)}",
"related_module_id": "#{options[:module_id]}",
"related_module_name": "#{options[:module_name]}"
}
}
EOF
json.gsub!(/^\s{6}/,'')
send!(:set_note_attachment, json)
end | Creates or updates an attachment on a note | train | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection/api/set_note_attachment.rb#L3-L24 | module SugarCRM; class Connection
# Creates or updates an attachment on a note
end; end
|
Thermatix/ruta | lib/ruta/route.rb | Ruta.Route.paramaterize | ruby | def paramaterize params
segments = @url.split('/')
segments.map { |item| item[0] == ':' ? params.shift : item }.join('/')
end | @param [String] pattern of url to match against
@param [Symbol] context_ref to context route is mounted to
@param [{Symbol => String,Number,Boolean}] flags attached to route
take in params and return a paramaterized route
@param [Array<String,Number,Boolean>] params a list of params to replace named params in a route
@return [String] url containing named params replaced | train | https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/route.rb#L63-L66 | class Route
DOM = ::Kernel.method(:DOM)
NAMED = /:(\w+)/
SPLAT = /\\\*(\w+)/
OPTIONAL = /\\\((.*?)\\\)/
# @!attribute [r] regexp
# @return [Symbol] the regexp used to match against a route
# @!attribute [r] named
# @return [Symbol] list of all named paramters
# @!attribute [r] type
# @return [Symbol] the type of the route's handler
# @!attribute [r] handlers
# @return [Symbol] a list of the handlers this route is suposed to execute
# @!attribute [r] url
# @return [Symbol] the raw url to match against
# @!attribute [r] flags
# @return [Symbol] any flags this route possesses
attr_reader :regexp, :named, :type, :handlers, :url,:flags
# @param [String] pattern of url to match against
# @param [Symbol] context_ref to context route is mounted to
# @param [{Symbol => String,Number,Boolean}] flags attached to route
def initialize(pattern, context_ref,flags)
if flags[:to]
@type = :handlers
@handlers = [flags.delete(:to)].flatten
elsif flags[:context]
@type = :context
@handlers = flags.delete :context
else
@type = :ref_only
end
@context_ref = context_ref
@flags = flags
@url = pattern
@named = []
pattern = Regexp.escape pattern
pattern = pattern.gsub OPTIONAL, "(?:$1)?"
pattern.gsub(NAMED) { |m| @named << m[1..-1] }
pattern.gsub(SPLAT) { |m| @named << m[2..-1] }
pattern = pattern.gsub NAMED, "([^\\/]*)"
pattern = pattern.gsub SPLAT, "(.*?)"
@regexp = Regexp.new "^#{pattern}$"
end
#take in params and return a paramaterized route
#
# @param [Array<String,Number,Boolean>] params a list of params to replace named params in a route
# @return [String] url containing named params replaced
# get route hash and paramaterize url if needed
#
# @param [Array<String,Number,Boolean>] params to replace named params in the returned url
# @return [Symbol => Number,String,Route] hash specificly formatted:
# {
# url: of the route with named params replaced,
# title: the name of page if the url has one,
# params: a list of all the params used in the route,
# route: the #Route object
# }
def get params=nil
path = if params
paramaterize params.dup
else
@url
end
{
path: path,
title: self.flags.fetch(:title){nil},
params: params_hash(params),
route: self
}
end
# match this route against a given path
#
# @param [String,Regex] path to match against
# @return [Hash,false] (see #get) or false if there is no match
def match(path)
if match = @regexp.match(path)
params = {}
@named.each_with_index { |name, i| params[name] = match[i + 1] } if @type == :handlers
{
path: path,
title: self.flags.fetch(:title){nil},
params: params,
route: self
}
else
false
end
end
# execute's route's associated handlers
#
# @param [Symbol => String] params from the route with there respective keys
# @param [String] path containing params placed into there respective named positions
def execute_handler params={},path=nil
case @type
when :handlers
@handlers.each do |handler_ident|
handler = @context_ref.handlers.fetch(handler_ident) {raise "handler #{handler_ident} doesn't exist in context #{@context_ref.ref}"}
component = handler.(params,path||@url,&:call)
Context.current_context = @context_ref.ref
if component.class == Proc
component.call
else
Context.renderer.call(component,handler_ident)
end
Context.current_context = :no_context
end
when :context
Context.wipe
Context.render handlers
History.push(@context_ref.ref,"",[],@context_ref.ref)
end
end
def params_hash(params)
Hash[@named.zip(params)]
end
end
|
bitbucket-rest-api/bitbucket | lib/bitbucket_rest_api/repos/default_reviewers.rb | BitBucket.Repos::DefaultReviewers.get | ruby | def get(user_name, repo_name, reviewer_username, params={})
update_and_validate_user_repo_params(user_name, repo_name)
normalize! params
get_request("/2.0/repositories/#{user_name}/#{repo_name}/default-reviewers/#{reviewer_username}", params)
end | Get a default reviewer's info
= Examples
bitbucket = BitBucket.new
bitbucket.repos.default_reviewers.get 'user-name', 'repo-name', 'reviewer-username' | train | https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/repos/default_reviewers.rb#L27-L32 | class Repos::DefaultReviewers < API
# List default reviewers
#
# = Examples
# bitbucket = BitBucket.new
# bitbucket.repos.default_reviewers.list 'user-name', 'repo-name'
# bitbucket.repos.default_reviewers.list 'user-name', 'repo-name' { |reviewer| ... }
#
def list(user_name, repo_name, params={})
update_and_validate_user_repo_params(user_name, repo_name)
normalize! params
response = get_request("/2.0/repositories/#{user_name}/#{repo_name}/default-reviewers", params)
return response unless block_given?
response.each { |el| yield el }
end
alias :all :list
# Get a default reviewer's info
#
# = Examples
# bitbucket = BitBucket.new
# bitbucket.repos.default_reviewers.get 'user-name', 'repo-name', 'reviewer-username'
#
# Add a user to the default-reviewers list for the repo
#
# = Examples
# bitbucket = BitBucket.new
# bitbucket.repos.default_reviewers.add 'user-name', 'repo-name', 'reviewer-username'
#
def add(user_name, repo_name, reviewer_username, params={})
update_and_validate_user_repo_params(user_name, repo_name)
normalize! params
put_request("/2.0/repositories/#{user_name}/#{repo_name}/default-reviewers/#{reviewer_username}", params)
end
# Remove a user from the default-reviewers list for the repo
#
# = Examples
# bitbucket = BitBucket.new
# bitbucket.repos.default_reviewers.remove 'user-name', 'repo-name', 'reviewer-username'
#
def remove(user_name, repo_name, reviewer_username, params={})
update_and_validate_user_repo_params(user_name, repo_name)
normalize! params
delete_request("/2.0/repositories/#{user_name}/#{repo_name}/default-reviewers/#{reviewer_username}", params)
end
end
|
minhnghivn/idata | lib/idata/detector.rb | Idata.Detector.find_valid | ruby | def find_valid
selected = @candidates.select { |delim, count|
begin
CSV.parse(@sample, col_sep: delim)
true
rescue Exception => ex
false
end
}.keys
return selected.first if selected.count == 1
return DEFAULT_DELIMITER if selected.include?(DEFAULT_DELIMITER)
end | just work | train | https://github.com/minhnghivn/idata/blob/266bff364e8c98dd12eb4256dc7a3ee10a142fb3/lib/idata/detector.rb#L38-L50 | class Detector
DEFAULT_DELIMITER = ","
COMMON_DELIMITERS = [DEFAULT_DELIMITER, "|", "\t", ";"]
SAMPLE_SIZE = 100
def initialize(file)
@file = file
@sample = `head -n #{SAMPLE_SIZE} #{@file}`.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
@sample_lines = @sample.split(/[\r\n]+/)
@candidates = COMMON_DELIMITERS.map { |delim|
[delim, @sample.scan(delim).count]
}.to_h.select{|k,v| v > 0}
end
def find
return DEFAULT_DELIMITER if @candidates.empty? # for example, file with only one header
return find_same_occurence || find_valid || find_max_occurence || DEFAULT_DELIMITER
end
# just work
# high confident level
def find_same_occurence
selected = @candidates.select { |delim, count|
begin
CSV.parse(@sample, col_sep: delim).select{|e| !e.empty? }.map{|e| e.count}.uniq.count == 1
rescue Exception => ex
false
end
}.keys
return selected.first if selected.count == 1
return DEFAULT_DELIMITER if selected.include?(DEFAULT_DELIMITER)
end
# most occurence
def find_max_occurence
selected = @candidates.select{|k,v| v == @candidates.sort_by(&:last).last }.keys
return selected.first if selected.count == 1
return DEFAULT_DELIMITER if selected.include?(DEFAULT_DELIMITER)
end
end
|
Falkor/falkorlib | lib/falkorlib/common.rb | FalkorLib.Common.write_from_erb_template | ruby | def write_from_erb_template(erbfile, outfile, config = {},
options = {
:no_interaction => false
})
erbfiles = (erbfile.is_a?(Array)) ? erbfile : [ erbfile ]
content = ""
erbfiles.each do |f|
erb = (options[:srcdir].nil?) ? f : File.join(options[:srcdir], f)
unless File.exist?(erb)
warning "Unable to find the template ERBfile '#{erb}'"
really_continue? unless options[:no_interaction]
next
end
content += ERB.new(File.read(erb.to_s), nil, '<>').result(binding)
end
# error "Unable to find the template file #{erbfile}" unless File.exists? (erbfile )
# template = File.read("#{erbfile}")
# output = ERB.new(template, nil, '<>')
# content = output.result(binding)
show_diff_and_write(content, outfile, options)
end | ERB generation of the file `outfile` using the source template file `erbfile`
Supported options:
:no_interaction [boolean]: do not interact
:srcdir [string]: source dir for all considered ERB files | train | https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L364-L384 | module Common
module_function
##################################
### Default printing functions ###
##################################
# Print a text in bold
def bold(str)
(COLOR == true) ? Term::ANSIColor.bold(str) : str
end
# Print a text in green
def green(str)
(COLOR == true) ? Term::ANSIColor.green(str) : str
end
# Print a text in red
def red(str)
(COLOR == true) ? Term::ANSIColor.red(str) : str
end
# Print a text in cyan
def cyan(str)
(COLOR == true) ? Term::ANSIColor.cyan(str) : str
end
# Print an info message
def info(str)
puts green("[INFO] " + str)
end
# Print an warning message
def warning(str)
puts cyan("/!\\ WARNING: " + str)
end
alias_method :warn, :warning
## Print an error message and abort
def error(str)
#abort red("*** ERROR *** " + str)
$stderr.puts red("*** ERROR *** " + str)
exit 1
end
## simple helper text to mention a non-implemented feature
def not_implemented
error("NOT YET IMPLEMENTED")
end
##############################
### Interaction functions ###
##############################
## Ask a question
def ask(question, default_answer = '')
return default_answer if FalkorLib.config[:no_interaction]
print "#{question} "
print "[Default: #{default_answer}]" unless default_answer == ''
print ": "
STDOUT.flush
answer = STDIN.gets.chomp
(answer.empty?) ? default_answer : answer
end
## Ask whether or not to really continue
def really_continue?(default_answer = 'Yes')
return if FalkorLib.config[:no_interaction]
pattern = (default_answer =~ /yes/i) ? '(Y|n)' : '(y|N)'
answer = ask( cyan("=> Do you really want to continue #{pattern}?"), default_answer)
exit 0 if answer =~ /n.*/i
end
############################
### Execution functions ###
############################
## Check for the presence of a given command
def command?(name)
`which #{name}`
$?.success?
end
## Execute a given command, return exit code and print nicely stdout and stderr
def nice_execute(cmd)
puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}")
stdout, stderr, exit_status = Open3.capture3( cmd )
unless stdout.empty?
stdout.each_line do |line|
print "** [out] #{line}"
$stdout.flush
end
end
unless stderr.empty?
stderr.each_line do |line|
$stderr.print red("** [err] #{line}")
$stderr.flush
end
end
exit_status
end
# Simpler version that use the system call
def execute(cmd)
puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}")
system(cmd)
$?.exitstatus
end
## Execute in a given directory
def execute_in_dir(path, cmd)
exit_status = 0
Dir.chdir(path) do
exit_status = run %( #{cmd} )
end
exit_status
end # execute_in_dir
## Execute a given command - exit if status != 0
def exec_or_exit(cmd)
status = execute(cmd)
if (status.to_i.nonzero?)
error("The command '#{cmd}' failed with exit status #{status.to_i}")
end
status
end
## "Nice" way to present run commands
## Ex: run %{ hostname -f }
def run(cmds)
exit_status = 0
puts bold("[Running]\n#{cmds.gsub(/^\s*/, ' ')}")
$stdout.flush
#puts cmds.split(/\n */).inspect
cmds.split(/\n */).each do |cmd|
next if cmd.empty?
system(cmd.to_s) unless FalkorLib.config.debug
exit_status = $?.exitstatus
end
exit_status
end
## List items from a glob pattern to ask for a unique choice
# Supported options:
# :only_files [boolean]: list only files in the glob
# :only_dirs [boolean]: list only directories in the glob
# :pattern_include [array of strings]: pattern(s) to include for listing
# :pattern_exclude [array of strings]: pattern(s) to exclude for listing
# :text [string]: text to put
def list_items(glob_pattern, options = {})
list = { 0 => 'Exit' }
index = 1
raw_list = { 0 => 'Exit' }
Dir[glob_pattern.to_s].each do |elem|
#puts "=> element '#{elem}' - dir = #{File.directory?(elem)}; file = #{File.file?(elem)}"
next if (!options[:only_files].nil?) && options[:only_files] && File.directory?(elem)
next if (!options[:only_dirs].nil?) && options[:only_dirs] && File.file?(elem)
entry = File.basename(elem)
# unless options[:pattern_include].nil?
# select_entry = false
# options[:pattern_include].each do |pattern|
# #puts "considering pattern '#{pattern}' on entry '#{entry}'"
# select_entry |= entry =~ /#{pattern}/
# end
# next unless select_entry
# end
unless options[:pattern_exclude].nil?
select_entry = false
options[:pattern_exclude].each do |pattern|
#puts "considering pattern '#{pattern}' on entry '#{entry}'"
select_entry |= entry =~ /#{pattern}/
end
next if select_entry
end
#puts "selected entry = '#{entry}'"
list[index] = entry
raw_list[index] = elem
index += 1
end
text = (options[:text].nil?) ? "select the index" : options[:text]
default_idx = (options[:default].nil?) ? 0 : options[:default]
raise SystemExit, 'Empty list' if index == 1
#ap list
#ap raw_list
# puts list.to_yaml
# answer = ask("=> #{text}", "#{default_idx}")
# raise SystemExit.new('exiting selection') if answer == '0'
# raise RangeError.new('Undefined index') if Integer(answer) >= list.length
# raw_list[Integer(answer)]
select_from(list, text, default_idx, raw_list)
end
## Display a indexed list to select an i
def select_from(list, text = 'Select the index', default_idx = 0, raw_list = list)
error "list and raw_list differs in size" if list.size != raw_list.size
l = list
raw_l = raw_list
if list.is_a?(Array)
l = raw_l = { 0 => 'Exit' }
list.each_with_index do |e, idx|
l[idx + 1] = e
raw_l[idx + 1] = raw_list[idx]
end
end
puts l.to_yaml
answer = ask("=> #{text}", default_idx.to_s)
raise SystemExit, 'exiting selection' if answer == '0'
raise RangeError, 'Undefined index' if Integer(answer) >= l.length
raw_l[Integer(answer)]
end # select_from
## Display a indexed list to select multiple indexes
def select_multiple_from(list, text = 'Select the index', default_idx = 1, raw_list = list)
error "list and raw_list differs in size" if list.size != raw_list.size
l = list
raw_l = raw_list
if list.is_a?(Array)
l = raw_l = { 0 => 'Exit', 1 => 'End of selection' }
list.each_with_index do |e, idx|
l[idx + 2] = e
raw_l[idx + 2] = raw_list[idx]
end
end
puts l.to_yaml
choices = Array.new
answer = 0
begin
choices.push(raw_l[Integer(answer)]) if Integer(answer) > 1
answer = ask("=> #{text}", default_idx.to_s)
raise SystemExit, 'exiting selection' if answer == '0'
raise RangeError, 'Undefined index' if Integer(answer) >= l.length
end while Integer(answer) != 1
choices
end # select_multiple_from
###############################
### YAML File loading/store ###
###############################
# Return the yaml content as a Hash object
def load_config(file)
unless File.exist?(file)
raise FalkorLib::Error, "Unable to find the YAML file '#{file}'"
end
loaded = YAML.load_file(file)
unless loaded.is_a?(Hash)
raise FalkorLib::Error, "Corrupted or invalid YAML file '#{file}'"
end
loaded
end
# Store the Hash object as a Yaml file
# Supported options:
# :header [string]: additional info to place in the header of the (stored) file
# :no_interaction [boolean]: do not interact
def store_config(filepath, hash, options = {})
content = "# " + File.basename(filepath) + "\n"
content += "# /!\\ DO NOT EDIT THIS FILE: it has been automatically generated\n"
if options[:header]
options[:header].split("\n").each { |line| content += "# #{line}" }
end
content += hash.to_yaml
show_diff_and_write(content, filepath, options)
# File.open( filepath, 'w') do |f|
# f.print "# ", File.basename(filepath), "\n"
# f.puts "# /!\\ DO NOT EDIT THIS FILE: it has been automatically generated"
# if options[:header]
# options[:header].split("\n").each do |line|
# f.puts "# #{line}"
# end
# end
# f.puts hash.to_yaml
# end
end
#################################
### [ERB] template generation ###
#################################
# Bootstrap the destination directory `rootdir` using the template
# directory `templatedir`. the hash table `config` hosts the elements to
# feed ERB files which **should** have the extension .erb.
# The initialization is performed as follows:
# * a rsync process is initiated to duplicate the directory structure
# and the symlinks, and exclude .erb files
# * each erb files (thus with extension .erb) is interpreted, the
# corresponding file is generated without the .erb extension
# Supported options:
# :erb_exclude [array of strings]: pattern(s) to exclude from erb file
# interpretation and thus to copy 'as is'
# :no_interaction [boolean]: do not interact
def init_from_template(templatedir, rootdir, config = {},
options = {
:erb_exclude => [],
:no_interaction => false
})
error "Unable to find the template directory" unless File.directory?(templatedir)
warning "about to initialize/update the directory #{rootdir}"
really_continue? unless options[:no_interaction]
run %( mkdir -p #{rootdir} ) unless File.directory?( rootdir )
run %( rsync --exclude '*.erb' --exclude '.texinfo*' -avzu #{templatedir}/ #{rootdir}/ )
Dir["#{templatedir}/**/*.erb"].each do |erbfile|
relative_outdir = Pathname.new( File.realpath( File.dirname(erbfile) )).relative_path_from Pathname.new(templatedir)
filename = File.basename(erbfile, '.erb')
outdir = File.realpath( File.join(rootdir, relative_outdir.to_s) )
outfile = File.join(outdir, filename)
unless options[:erb_exclude].nil?
exclude_entry = false
options[:erb_exclude].each do |pattern|
exclude_entry |= erbfile =~ /#{pattern}/
end
if exclude_entry
info "copying non-interpreted ERB file"
# copy this file since it has been probably excluded from teh rsync process
run %( cp #{erbfile} #{outdir}/ )
next
end
end
# Let's go
info "updating '#{relative_outdir}/#{filename}'"
puts " using ERB template '#{erbfile}'"
write_from_erb_template(erbfile, outfile, config, options)
end
end
###
# ERB generation of the file `outfile` using the source template file `erbfile`
# Supported options:
# :no_interaction [boolean]: do not interact
# :srcdir [string]: source dir for all considered ERB files
## Show the difference between a `content` string and an destination file (using Diff algorithm).
# Obviosuly, if the outfile does not exists, no difference is proposed.
# Supported options:
# :no_interaction [boolean]: do not interact
# :json_pretty_format [boolean]: write a json content, in pretty format
# :no_commit [boolean]: do not (offer to) commit the changes
# return 0 if nothing happened, 1 if a write has been done
def show_diff_and_write(content, outfile, options = {
:no_interaction => false,
:json_pretty_format => false,
:no_commit => false
})
if File.exist?( outfile )
ref = File.read( outfile )
if options[:json_pretty_format]
ref = JSON.pretty_generate(JSON.parse( IO.read( outfile ) ))
end
if ref == content
warn "Nothing to update"
return 0
end
warn "the file '#{outfile}' already exists and will be overwritten."
warn "Expected difference: \n------"
Diffy::Diff.default_format = :color
puts Diffy::Diff.new(ref, content, :context => 1)
else
watch = (options[:no_interaction]) ? 'no' : ask( cyan(" ==> Do you want to see the generated file before commiting the writing (y|N)"), 'No')
puts content if watch =~ /y.*/i
end
proceed = (options[:no_interaction]) ? 'yes' : ask( cyan(" ==> proceed with the writing (Y|n)"), 'Yes')
return 0 if proceed =~ /n.*/i
info("=> writing #{outfile}")
File.open(outfile.to_s, "w+") do |f|
f.write content
end
if FalkorLib::Git.init?(File.dirname(outfile)) && !options[:no_commit]
do_commit = (options[:no_interaction]) ? 'yes' : ask( cyan(" ==> commit the changes (Y|n)"), 'Yes')
FalkorLib::Git.add(outfile, "update content of '#{File.basename(outfile)}'") if do_commit =~ /y.*/i
end
1
end
## Blind copy of a source file `src` into its destination directory `dstdir`
# Supported options:
# :no_interaction [boolean]: do not interact
# :srcdir [string]: source directory, make the `src` file relative to that directory
# :outfile [string]: alter the outfile name (File.basename(src) by default)
# :no_commit [boolean]: do not (offer to) commit the changes
def write_from_template(src, dstdir, options = {
:no_interaction => false,
:no_commit => false,
:srcdir => '',
:outfile => ''
})
srcfile = (options[:srcdir].nil?) ? src : File.join(options[:srcdir], src)
error "Unable to find the source file #{srcfile}" unless File.exist?( srcfile )
error "The destination directory '#{dstdir}' do not exist" unless File.directory?( dstdir )
dstfile = (options[:outfile].nil?) ? File.basename(srcfile) : options[:outfile]
outfile = File.join(dstdir, dstfile)
content = File.read( srcfile )
show_diff_and_write(content, outfile, options)
end # copy_from_template
### RVM init
def init_rvm(rootdir = Dir.pwd, gemset = '')
rvm_files = {
:version => File.join(rootdir, '.ruby-version'),
:gemset => File.join(rootdir, '.ruby-gemset')
}
unless File.exist?( (rvm_files[:version]).to_s)
v = select_from(FalkorLib.config[:rvm][:rubies],
"Select RVM ruby to configure for this directory",
3)
File.open( rvm_files[:version], 'w') do |f|
f.puts v
end
end
unless File.exist?( (rvm_files[:gemset]).to_s)
g = (gemset.empty?) ? ask("Enter RVM gemset name for this directory", File.basename(rootdir)) : gemset
File.open( rvm_files[:gemset], 'w') do |f|
f.puts g
end
end
end
###### normalize_path ######
# Normalize a path and return the absolute path foreseen
# Ex: '.' return Dir.pwd
# Supported options:
# * :relative [boolean] return relative path to the root dir
##
def normalized_path(dir = Dir.pwd, options = {})
rootdir = (FalkorLib::Git.init?(dir)) ? FalkorLib::Git.rootdir(dir) : dir
path = dir
path = Dir.pwd if dir == '.'
path = File.join(Dir.pwd, dir) unless (dir =~ /^\// || (dir == '.'))
if (options[:relative] || options[:relative_to])
root = (options[:relative_to]) ? options[:relative_to] : rootdir
relative_path_to_root = Pathname.new( File.realpath(path) ).relative_path_from Pathname.new(root)
path = relative_path_to_root.to_s
end
path
end # normalize_path
end
|
barkerest/incline | app/controllers/incline/access_groups_controller.rb | Incline.AccessGroupsController.access_group_params | ruby | def access_group_params(mode = :all)
list = []
list += [ :name ] if mode == :before_create || mode == :all
list += [ { group_ids: [], user_ids: [] } ] if mode == :after_create || mode == :all
params.require(:access_group).permit(list)
end | Only allow a trusted parameter "white list" through. | train | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/controllers/incline/access_groups_controller.rb#L119-L125 | class AccessGroupsController < ApplicationController
before_action :set_access_group, only: [ :show, :edit, :update, :destroy ]
before_action :set_dt_request, only: [ :index, :locate ]
require_admin true
layout :layout_to_use
##
# GET /incline/access_groups
def index
end
##
# GET /incline/access_groups/1
def show
end
##
# GET /incline/access_groups/new
def new
@access_group = Incline::AccessGroup.new
end
##
# GET /incline/access_groups/1/edit
def edit
end
##
# POST /incline/access_groups
def create
@access_group = Incline::AccessGroup.create(access_group_params :before_create)
if @access_group
if @access_group.update(access_group_params :after_create)
handle_update_success notice: 'Access group was successfully created.'
else
handle_update_failure :new
end
else
handle_update_failure :new
end
end
##
# PATCH/PUT /incline/access_groups/1
def update
if @access_group.update(access_group_params)
handle_update_success notice: 'Access group was successfully updated.'
else
handle_update_failure :edit
end
end
##
# DELETE /incline/access_groups/1
def destroy
@access_group.destroy
handle_update_success notice: 'Access group was successfully destroyed.'
end
# POST /incline/access_groups/1/locate
def locate
render json: { record: @dt_request.record_location }
end
# GET/POST /incline/access_groups/api?action=...
def api
process_api_action
end
private
def layout_to_use
inline_request? ? false : nil
end
def handle_update_failure(action)
if json_request?
# add a model-level error and render the json response.
@access_group.errors.add(:base, 'failed to save')
render 'show', formats: [ :json ]
else
# render the appropriate action.
render action
end
end
def handle_update_success(*messages)
if inline_request?
# inline and json requests expect json on success.
render 'show', formats: [ :json ]
else
# otherwise, we redirect.
# The default behavior in rails is to redirect to the item that was updated.
# The default behavior in incline is to redirect to the item collection.
# To reinstate the default rails behavior, uncomment the line below.
# redirect_to @<%= singular_table_name %>, *messages unless @<%= singular_table_name %>.destroyed?
redirect_to access_groups_url, *messages
end
end
def set_dt_request
@dt_request = Incline::DataTablesRequest.new(params) do
Incline::AccessGroup.all
end
end
# Use callbacks to share common setup or constraints between actions.
def set_access_group
@access_group = Incline::AccessGroup.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
end
|
amatsuda/rfd | lib/rfd/commands.rb | Rfd.Commands.ctrl_a | ruby | def ctrl_a
mark = marked_items.size != (items.size - 2) # exclude . and ..
items.each {|i| i.toggle_mark unless i.marked? == mark}
draw_items
draw_marked_items
move_cursor current_row
end | Mark or unmark "a"ll files and directories. | train | https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd/commands.rb#L190-L196 | module Commands
# Change permission ("A"ttributes) of selected files and directories.
def a
process_command_line preset_command: 'chmod'
end
# "c"opy selected files and directories.
def c
process_command_line preset_command: 'cp'
end
# Soft "d"elete (actually mv to the trash folder on OSX) selected files and directories.
def d
if selected_items.any?
if ask %Q[Are you sure want to trash #{selected_items.one? ? selected_items.first.name : "these #{selected_items.size} files"}? (y/n)]
trash
end
end
end
# Open current file or directory with the "e"ditor
def e
edit
end
# "f"ind the first file or directory of which name starts with the given String.
def f
c = get_char and (@last_command = -> { find c }).call
end
# Move the cursor to the top of the list.
def g
move_cursor 0
end
# Move the cursor to the left pane.
def h
(y = current_row - maxy) >= 0 and move_cursor y
end
# Move the cursor down.
def j
move_cursor (current_row + times) % items.size
end
# Move the cursor up.
def k
move_cursor (current_row - times) % items.size
end
# Move the cursor to the right pane.
def l
(y = current_row + maxy) < items.size and move_cursor y
end
# "m"ove selected files and directories.
def m
process_command_line preset_command: 'mv'
end
# Redo the latest f or F.
def n
@last_command.call if @last_command
end
# "o"pen selected files and directories with the OS "open" command.
def o
if selected_items.any?
system "open #{selected_items.map {|i| %Q["#{i.path}"]}.join(' ')}"
elsif %w(. ..).include? current_item.name
system %Q[open "#{current_item.path}"]
end
end
# Paste yanked files / directories into the directory on which the cursor is, or into the current directory.
def p
paste
end
# "q"uit the app.
def q
raise StopIteration if ask 'Are you sure want to exit? (y/n)'
end
# "q"uit the app!
def q!
raise StopIteration
end
# "r"ename selected files and directories.
def r
process_command_line preset_command: 'rename'
end
# "s"ort displayed files and directories in the given order.
def s
process_command_line preset_command: 'sort'
end
# Create a new file, or update its timestamp if the file already exists ("t"ouch).
def t
process_command_line preset_command: 'touch'
end
# "u"narchive .zip and .tar.gz files within selected files and directories into current_directory.
def u
unarchive
end
# "o"pen selected files and directories with the viewer.
def v
view
end
# Change o"w"ner of selected files and directories.
def w
process_command_line preset_command: 'chown'
end
# "y"ank selected file / directory names.
def y
yank
end
# Archive selected files and directories into a "z"ip file.
def z
process_command_line preset_command: 'zip'
end
# "C"opy paths of selected files and directory to the "C"lipboard.
def C
clipboard
end
# Hard "d"elete selected files and directories.
def D
if selected_items.any?
if ask %Q[Are you sure want to delete #{selected_items.one? ? selected_items.first.name : "these #{selected_items.size} files"}? (y/n)]
delete
end
end
end
# "f"ind the last file or directory of which name starts with the given String.
def F
c = get_char and (@last_command = -> { find_reverse c }).call
end
# Move the cursor to the top.
def H
move_cursor current_page * max_items
end
# Move the cursor to the bottom of the list.
def G
move_cursor items.size - 1
end
# Ma"K"e a directory.
def K
process_command_line preset_command: 'mkdir'
end
# Move the cursor to the bottom.
def L
move_cursor current_page * max_items + displayed_items.size - 1
end
# Move the cursor to the "M"iddle.
def M
move_cursor current_page * max_items + displayed_items.size / 2
end
# "O"pen terminal here.
def O
dir = current_item.directory? ? current_item.path : current_dir.path
system %Q[osascript -e 'tell app "Terminal"
do script "cd #{dir}"
end tell'] if osx?
end
# "S"ymlink the current file or directory
def S
process_command_line preset_command: 'symlink'
end
# Mark or unmark "a"ll files and directories.
# "b"ack to the previous page.
def ctrl_b
ctrl_p
end
# "f"orward to the next page.
def ctrl_f
ctrl_n
end
# Refresh the screen.
def ctrl_l
ls
end
# Forward to the "n"ext page.
def ctrl_n
move_cursor (current_page + 1) % total_pages * max_items if total_pages > 1
end
# Back to the "p"revious page.
def ctrl_p
move_cursor (current_page - 1) % total_pages * max_items if total_pages > 1
end
# Split the main "w"indow into given number of columns.
def ctrl_w
if @times
spawn_panes @times.to_i
ls
end
end
# Number of times to repeat the next command.
(?0..?9).each do |n|
define_method(n) do
@times ||= ''
@times += n
end
end
# Return to the previous directory (popd).
def -
popd
end
# Search files and directories from the current directory.
def /
process_command_line preset_command: 'grep'
end
# Change current directory (cd).
define_method(:'@') do
process_command_line preset_command: 'cd'
end
# Execute a shell command in an external shell.
define_method(:!) do
process_shell_command
end
# Execute a command in the controller context.
define_method(:':') do
process_command_line
end
# cd into a directory, or view a file.
def enter
if current_item.name == '.' # do nothing
elsif current_item.name == '..'
cd '..'
elsif in_zip?
v
elsif current_item.directory? || current_item.zip?
cd current_item
else
v
end
end
# Toggle mark, and move down.
def space
toggle_mark
draw_marked_items
j
end
# cd to the upper hierarchy.
def del
if current_dir.path != '/'
dir_was = times == 1 ? current_dir.name : File.basename(current_dir.join(['..'] * (times - 1)))
cd File.expand_path(current_dir.join(['..'] * times))
find dir_was
end
end
# Move cursor position by mouse click.
def click(y: nil, x: nil)
move_cursor_by_click y: y, x: x
end
# Move cursor position and enter
def double_click(y: nil, x: nil)
if move_cursor_by_click y: y, x: x
enter
end
end
end
|
jeremytregunna/ruby-trello | lib/trello/client.rb | Trello.Client.find | ruby | def find(path, id, params = {})
response = get("/#{path.to_s.pluralize}/#{id}", params)
trello_class = class_from_path(path)
trello_class.parse response do |data|
data.client = self
end
end | Finds given resource by id
Examples:
client.find(:board, "board1234")
client.find(:member, "user1234") | train | https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/client.rb#L43-L49 | class Client
extend Forwardable
include Authorization
def_delegators :configuration, :credentials, *Configuration.configurable_attributes
def initialize(attrs = {})
self.configuration.attributes = attrs
end
def get(path, params = {})
uri = Addressable::URI.parse("https://api.trello.com/#{API_VERSION}#{path}")
uri.query_values = params unless params.empty?
invoke_verb(:get, uri)
end
def post(path, body = {})
uri = Addressable::URI.parse("https://api.trello.com/#{API_VERSION}#{path}")
invoke_verb(:post, uri, body)
end
def put(path, body = {})
uri = Addressable::URI.parse("https://api.trello.com/#{API_VERSION}#{path}")
invoke_verb(:put, uri, body)
end
def delete(path)
uri = Addressable::URI.parse("https://api.trello.com/#{API_VERSION}#{path}")
invoke_verb(:delete, uri)
end
# Finds given resource by id
#
# Examples:
# client.find(:board, "board1234")
# client.find(:member, "user1234")
#
# Finds given resource by path with params
def find_many(trello_class, path, params = {})
response = get(path, params)
trello_class.parse_many response do |data|
data.client = self
end
end
# Creates resource with given options (attributes)
#
# Examples:
# client.create(:member, options)
# client.create(:board, options)
#
def create(path, options)
trello_class = class_from_path(path)
trello_class.save options do |data|
data.client = self
end
end
def configure
yield configuration if block_given?
end
def configuration
@configuration ||= Configuration.new
end
def auth_policy
@auth_policy ||= auth_policy_class.new(credentials)
end
private
def invoke_verb(name, uri, body = nil)
request = Request.new name, uri, {}, body
response = TInternet.execute auth_policy.authorize(request)
return '' unless response
if response.code.to_i == 401 && response.body =~ /expired token/
Trello.logger.error("[401 #{name.to_s.upcase} #{uri}]: Your access token has expired.")
raise InvalidAccessToken, response.body
end
unless [200, 201].include? response.code
Trello.logger.error("[#{response.code} #{name.to_s.upcase} #{uri}]: #{response.body}")
raise Error.new(response.body, response.code)
end
response.body
end
def auth_policy_class
if configuration.oauth?
OAuthPolicy
elsif configuration.basic?
BasicAuthPolicy
else
AuthPolicy
end
end
def class_from_path(path_or_class)
return path_or_class if path_or_class.is_a?(Class)
Trello.const_get(path_or_class.to_s.singularize.camelize)
end
end
|
OSHPark/ruby-api-client | lib/oshpark/client.rb | Oshpark.Client.add_order_item | ruby | def add_order_item id, project_id, quantity
post_request "orders/#{id}/add_item", {order: {project_id: project_id, quantity: quantity}}
end | Add a Project to an Order
@param id
@param project_id
@param quantity | train | https://github.com/OSHPark/ruby-api-client/blob/629c633c6c2189e2634b4b8721e6f0711209703b/lib/oshpark/client.rb#L117-L119 | class Client
attr_accessor :token, :connection
# Create an new Client object.
#
# @param connection:
# pass in a subclass of connection which implements the `request` method
# with whichever HTTP client library you prefer. Default is Net::HTTP.
def initialize args = {}
url = args.fetch(:url, "https://oshpark.com/api/v1")
connection = args.fetch(:connection, Connection)
self.connection = if connection.respond_to? :new
connection.new url
else
connection
end
refresh_token
end
# Authenticate to the API using a email and password.
#
# @param email
# @param credentials
# A hash with either the `with_password` or `with_api_secret` key.
def authenticate email, credentials={}
if password = credentials[:with_password]
refresh_token email: email, password: password
elsif secret = credentials[:with_api_secret]
api_key = OpenSSL::Digest::SHA256.new("#{email}:#{secret}:#{token.token}").to_s
refresh_token email: email, api_key: api_key
else
raise ArgumentError, "Must provide either `with_password` or `with_api_secret` arguments."
end
end
# Abandon a previous authentication.
def abandon
self.token = nil
refresh_token
end
# Retrieve a list of projects for the current user.
def projects
get_request 'projects'
end
# Retrieve a particular project from the current user's collection by ID.
#
# @param id
def project id
get_request "projects/#{id}"
end
# Approve a particular project from the current user's collection by ID.
# We strongly suggest that you allow the user to view the rendered images
# in Project#top_image, Project#bottom_image and Project#layers[]#image
#
# @param id
def approve_project id
get_request "projects/#{id}/approve"
end
# Update a project's data.
#
# @param id
# @param attrs
# A hash of attributes to update.
def update_project id, attrs
put_request "projects/#{id}", project: attrs
end
# Destroy a particular project from the current user's collection by ID.
#
# @param id
def destroy_project id
delete_request "projects/#{id}"
true
end
# Request a price estimate
#
# @param width In thousands of an Inch
# @param height In thousands of an Inch
# @param layers
# @param quantity Optional Defaults to the minimum quantity
def pricing width, height, pcb_layers, quantity = nil
post_request "pricing", {width_in_mils: width, height_in_mils: height, pcb_layers: pcb_layers, quantity: quantity}
end
# List all the current user's orders, and their status.
def orders
get_request 'orders'
end
# Retrieve a specific order by ID.
#
# @param id
def order id
get_request "orders/#{id}"
end
# Create a new Order
def create_order
post_request "orders"
end
# Add a Project to an Order
#
# @param id
# @param project_id
# @param quantity
# Set the delivery address for an Order
#
# @param id
# @param address
# An Address object or a Hash with at least the required keys: :name :address_line_1 :address_line_2 :city :country
def set_order_address id, address
post_request "orders/#{id}/set_address", {order: {address: address.to_h}}
end
def shipping_rates address_params
post_request "shipping_rates", {address: address_params}
end
# Set the delivery address for an Order
#
# @param id
# @param shipping_rate
# A ShippingRate object or a Hash with the following keys: :carrier_name :service_name
def set_order_shipping_rate id, shipping_rate
post_request "orders/#{id}/set_shipping_rate", {order:{shipping_rate: shipping_rate.to_h}}
end
# Checkout a specific order by ID.
#
# @param id
def checkout_order id
post_request "orders/#{id}/checkout"
end
# Cancel a specific order by ID.
# This can only be done when the order is in the 'RECEIVED' and
# 'AWAITING PANEL' states.
#
# @param id
def cancel_order id
delete_request "orders/#{id}"
true
end
# List all currently open and recently closed panels, including some
# interesting information about them.
def panels
get_request "panels"
end
# Retrieve a specific panel by ID.
#
# @param id
def panel id
get_request "panels/#{id}"
end
# Retrieve a specific upload by ID
#
# @param id
def upload id
get_request "uploads/#{id}"
end
# Create an upload by passing in an IO
#
# @param io
# An IO object.
def create_upload io
post_request "uploads", {file: io}
end
# Retrieve a specific import by ID
#
# @param id
def import id
get_request "imports/#{id}"
end
# Create an import by passing in a URL
#
# @param io
# A URL
def create_import url
post_request "imports", {url: url}
end
# Do we have a currently valid API token?
def has_token?
!!@token
end
# Are we successfully authenticated to the API?
def authenticated?
@token && !!@token.user
end
private
def connection
@connection
end
def refresh_token params={}
json = post_request 'sessions', params
self.token = Token.from_json json['api_session_token']
# Hey @hmaddocks - how are we going to set a timer to make the token refresh?
end
def post_request endpoint, params={}
connection.request :post, endpoint, params, token
end
def put_request endpoint, params={}
connection.request :put, endpoint, params, token
end
def get_request endpoint, params={}
connection.request :get, endpoint, params, token
end
def delete_request endpoint, params={}
connection.request :delete, endpoint, params, token
end
end
|
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtPubkey.version | ruby | def version
return ExtPubkey.version_from_purpose(number) if depth == 1
ver ? ver : Bitcoin.chain_params.extended_pubkey_version
end | get version bytes using serialization format | train | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L273-L276 | class ExtPubkey
attr_accessor :ver
attr_accessor :depth
attr_accessor :number
attr_accessor :chain_code
attr_accessor :pubkey # hex format
attr_accessor :parent_fingerprint
# serialize extended pubkey
def to_payload
version.htb << [depth].pack('C') <<
parent_fingerprint.htb << [number].pack('N') << chain_code << pub.htb
end
def pub
pubkey
end
def hash160
Bitcoin.hash160(pub)
end
# get address
def addr
case version
when Bitcoin.chain_params.bip49_pubkey_p2wpkh_p2sh_version
key.to_nested_p2wpkh
when Bitcoin.chain_params.bip84_pubkey_p2wpkh_version
key.to_p2wpkh
else
key.to_p2pkh
end
end
# get key object
# @return [Bitcoin::Key]
def key
Bitcoin::Key.new(pubkey: pubkey, key_type: key_type)
end
# get key identifier
def identifier
Bitcoin.hash160(pub)
end
# get fingerprint
def fingerprint
identifier.slice(0..7)
end
# Base58 encoded extended pubkey
def to_base58
h = to_payload.bth
hex = h + Bitcoin.calc_checksum(h)
Base58.encode(hex)
end
# whether hardened key.
def hardened?
number >= HARDENED_THRESHOLD
end
# derive child key
def derive(number)
new_key = ExtPubkey.new
new_key.depth = depth + 1
new_key.number = number
new_key.parent_fingerprint = fingerprint
raise 'hardened key is not support' if number > (HARDENED_THRESHOLD - 1)
data = pub.htb << [number].pack('N')
l = Bitcoin.hmac_sha512(chain_code, data)
left = l[0..31].bth.to_i(16)
raise 'invalid key' if left >= CURVE_ORDER
p1 = Bitcoin::Secp256k1::GROUP.generator.multiply_by_scalar(left)
p2 = Bitcoin::Key.new(pubkey: pubkey, key_type: key_type).to_point
new_key.pubkey = ECDSA::Format::PointOctetString.encode(p1 + p2, compression: true).bth
new_key.chain_code = l[32..-1]
new_key.ver = version
new_key
end
# get version bytes using serialization format
# get key type defined by BIP-178 using version.
def key_type
v = version
case v
when Bitcoin.chain_params.bip49_pubkey_p2wpkh_p2sh_version
Bitcoin::Key::TYPES[:pw2pkh_p2sh]
when Bitcoin.chain_params.bip84_pubkey_p2wpkh_version
Bitcoin::Key::TYPES[:p2wpkh]
when Bitcoin.chain_params.extended_pubkey_version
Bitcoin::Key::TYPES[:compressed]
end
end
def self.parse_from_payload(payload)
buf = StringIO.new(payload)
ext_pubkey = ExtPubkey.new
ext_pubkey.ver = buf.read(4).bth # version
raise 'An unsupported version byte was specified.' unless ExtPubkey.support_version?(ext_pubkey.ver)
ext_pubkey.depth = buf.read(1).unpack('C').first
ext_pubkey.parent_fingerprint = buf.read(4).bth
ext_pubkey.number = buf.read(4).unpack('N').first
ext_pubkey.chain_code = buf.read(32)
ext_pubkey.pubkey = buf.read(33).bth
ext_pubkey
end
# import pub key from Base58 private key address
def self.from_base58(address)
ExtPubkey.parse_from_payload(Base58.decode(address).htb)
end
# get version bytes from purpose' value.
def self.version_from_purpose(purpose)
v = purpose - HARDENED_THRESHOLD
case v
when 49
Bitcoin.chain_params.bip49_pubkey_p2wpkh_p2sh_version
when 84
Bitcoin.chain_params.bip84_pubkey_p2wpkh_version
else
Bitcoin.chain_params.extended_pubkey_version
end
end
# check whether +version+ is supported version bytes.
def self.support_version?(version)
p = Bitcoin.chain_params
[p.bip49_pubkey_p2wpkh_p2sh_version, p.bip84_pubkey_p2wpkh_version, p.extended_pubkey_version].include?(version)
end
end
|
nbulaj/proxy_fetcher | lib/proxy_fetcher/configuration.rb | ProxyFetcher.Configuration.setup_custom_class | ruby | def setup_custom_class(klass, required_methods: [])
unless klass.respond_to?(*required_methods)
raise ProxyFetcher::Exceptions::WrongCustomClass.new(klass, required_methods)
end
klass
end | Checks if custom class has some required class methods | train | https://github.com/nbulaj/proxy_fetcher/blob/da2e067acd930886d894490e229ba094f7f5ea53/lib/proxy_fetcher/configuration.rb#L175-L181 | class Configuration
# @!attribute client_timeout
# @return [Integer] HTTP request timeout (connect / open) for [ProxyFetcher::Client]
attr_accessor :client_timeout
# @!attribute provider_proxies_load_timeout
# @return [Integer] HTTP request timeout (connect / open) for loading of proxies list by provider
attr_accessor :provider_proxies_load_timeout
# @!attribute proxy_validation_timeout
# @return [Integer] HTTP request timeout (connect / open) for proxy validation with [ProxyFetcher::ProxyValidator]
attr_accessor :proxy_validation_timeout
# to save compatibility
alias timeout client_timeout
alias timeout= client_timeout=
# @!attribute pool_size
# @return [Integer] proxy validator pool size (max number of threads)
attr_accessor :pool_size
# @!attribute user_agent
# @return [String] User-Agent string
attr_accessor :user_agent
# @!attribute [r] logger
# @return [Object] Logger object
attr_accessor :logger
# @!attribute [r] adapter
# @return [Object] HTML parser adapter
attr_accessor :adapter
# @!attribute [r] adapter_class
# @return [Object] HTML adapter class
attr_reader :adapter_class
# @!attribute [r] http_client
# @return [Object] HTTP client class
attr_reader :http_client
# @!attribute [r] proxy_validator
# @return [Object] proxy validator class
attr_reader :proxy_validator
# @!attribute [r] providers
# @return [Array<String>, Array<Symbol>] proxy providers list to be used
attr_reader :providers
# User-Agent string that will be used by the ProxyFetcher HTTP client (to
# send requests via proxy) and to fetch proxy lists from the sources.
#
# Default is Google Chrome 60, but can be changed in <code>ProxyFetcher.config</code>.
#
DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 ' \
'(KHTML, like Gecko) Chrome/60.0.3112 Safari/537.36'.freeze
# HTML parser adapter name.
#
# Default is Nokogiri, but can be changed in <code>ProxyFetcher.config</code>.
#
DEFAULT_ADAPTER = :nokogiri
class << self
# Registry for handling proxy providers.
#
# @return [ProxyFetcher::ProvidersRegistry]
# providers registry
#
def providers_registry
@providers_registry ||= ProvidersRegistry.new
end
# Register new proxy provider. Requires provider name and class
# that will process proxy list.
#
# @param name [String, Symbol]
# name of the provider
#
# @param klass [Class]
# Class that will fetch and process proxy list
#
def register_provider(name, klass)
providers_registry.register(name, klass)
end
# Returns registered providers names.
#
# @return [Array<String>, Array<Symbol>]
# registered providers names
#
def registered_providers
providers_registry.providers.keys
end
end
# Initialize ProxyFetcher configuration with default options.
#
# @return [ProxyFetcher::Configuration]
# ProxyFetcher gem configuration object
#
def initialize
reset!
end
# Sets default configuration options
def reset!
@logger = Logger.new(STDOUT)
@user_agent = DEFAULT_USER_AGENT
@pool_size = 10
@client_timeout = 3
@provider_proxies_load_timeout = 30
@proxy_validation_timeout = 3
@http_client = HTTPClient
@proxy_validator = ProxyValidator
self.providers = self.class.registered_providers
end
def adapter=(value)
remove_instance_variable(:@adapter_class) if defined?(@adapter_class)
@adapter = value
end
def adapter_class
return @adapter_class if defined?(@adapter_class)
@adapter_class = ProxyFetcher::Document::Adapters.lookup(adapter)
@adapter_class.setup!
@adapter_class
end
# Setups collection of providers that will be used to fetch proxies.
#
# @param value [String, Symbol, Array<String>, Array<Symbol>]
# provider names
#
def providers=(value)
@providers = Array(value)
end
alias provider providers
alias provider= providers=
# Setups HTTP client class that will be used to fetch proxy lists.
# Validates class for the required methods to be defined.
#
# @param klass [Class]
# HTTP client class
#
def http_client=(klass)
@http_client = setup_custom_class(klass, required_methods: :fetch)
end
# Setups class that will be used to validate proxy lists.
# Validates class for the required methods to be defined.
#
# @param klass [Class]
# Proxy validator class
#
def proxy_validator=(klass)
@proxy_validator = setup_custom_class(klass, required_methods: :connectable?)
end
private
# Checks if custom class has some required class methods
end
|
TelAPI/telapi-ruby | lib/telapi/participant.rb | Telapi.Participant.undeaf | ruby | def undeaf
response = Network.post(['Conferences', self.conference_sid, 'Participant', self.call_sid], { :Deaf => false })
Participant.new(response)
end | Undeaf a participant of a conference call, returning a Telapi::Participant object
See http://www.telapi.com/docs/api/rest/conferences/deaf-or-mute/ | train | https://github.com/TelAPI/telapi-ruby/blob/880fd4539c97a5d2eebc881adc843afff341bca5/lib/telapi/participant.rb#L27-L30 | class Participant < Resource
class << self
# Convenient alternative to Conference::participants
def list(conference_sid, optional_params = {})
Conference.participants(conference_sid, optional_params)
end
# Convenient alternative to Conference::participant
def get(conference_sid, call_sid)
Conference.participant(conference_sid, call_sid)
end
end
# Deaf a participant of a conference call, returning a Telapi::Participant object
# See http://www.telapi.com/docs/api/rest/conferences/deaf-or-mute/
def deaf
response = Network.post(['Conferences', self.conference_sid, 'Participant', self.call_sid], { :Deaf => true })
Participant.new(response)
end
# Undeaf a participant of a conference call, returning a Telapi::Participant object
# See http://www.telapi.com/docs/api/rest/conferences/deaf-or-mute/
# Mute a participant of a conference call, returning a Telapi::Participant object
# See http://www.telapi.com/docs/api/rest/conferences/deaf-or-mute/
def mute
response = Network.post(['Conferences', self.conference_sid, 'Participant', self.call_sid], { :Muted => true })
Participant.new(response)
end
# Unmute a participant of a conference call, returning a Telapi::Participant object
# See http://www.telapi.com/docs/api/rest/conferences/deaf-or-mute/
def unmute
response = Network.post(['Conferences', self.conference_sid, 'Participant', self.call_sid], { :Muted => false })
Participant.new(response)
end
# Hangup a participant of a conference call, returning a Telapi::Participant object
# See http://www.telapi.com/docs/api/rest/conferences/hangup-participant/
def hangup
response = Network.delete(['Conferences', self.conference_sid, 'Participant', self.call_sid])
Participant.new(response)
end
# Play pre-recorded sound from a file to conference members, returning a Telapi::Participant object
# See http://www.telapi.com/docs/api/rest/conferences/play-audio/
#
# Required params:
# +sound_url+:: URL containing an audio file
def play_audio(sound_url = 'http://www.telapi.com/audio.mp3')
response = Network.post(['Conferences', self.conference_sid, 'Participant', self.call_sid], { :AudioUrl => sound_url })
Participant.new(response)
end
end
|
thumblemonks/riot | lib/riot/assertion_macros/equivalent_to.rb | Riot.EquivalentToMacro.evaluate | ruby | def evaluate(actual, expected)
if expected === actual
pass new_message.is_equivalent_to(expected)
else
fail expected_message(actual).to_be_equivalent_to(expected)
end
end | (see Riot::AssertionMacro#evaluate)
@param [Object] expected the object value to compare actual to | train | https://github.com/thumblemonks/riot/blob/e99a8965f2d28730fc863c647ca40b3bffb9e562/lib/riot/assertion_macros/equivalent_to.rb#L21-L27 | class EquivalentToMacro < AssertionMacro
register :equivalent_to
# (see Riot::AssertionMacro#evaluate)
# @param [Object] expected the object value to compare actual to
# (see Riot::AssertionMacro#devaluate)
# @param [Object] expected the object value to compare actual to
def devaluate(actual, expected)
if expected === actual
fail expected_message(actual).not_to_be_equivalent_to(expected)
else
pass new_message.is_equivalent_to(expected)
end
end
end
|
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.run_scope | ruby | def run_scope(scope, machine, klass, states)
values = states.flatten.map { |state| machine.states.fetch(state).value }
scope.call(klass, values)
end | Generates the results for the given scope based on one or more states to
filter by | train | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2132-L2135 | class Machine
include EvalHelpers
include MatcherHelpers
class << self
# Attempts to find or create a state machine for the given class. For
# example,
#
# StateMachines::Machine.find_or_create(Vehicle)
# StateMachines::Machine.find_or_create(Vehicle, :initial => :parked)
# StateMachines::Machine.find_or_create(Vehicle, :status)
# StateMachines::Machine.find_or_create(Vehicle, :status, :initial => :parked)
#
# If a machine of the given name already exists in one of the class's
# superclasses, then a copy of that machine will be created and stored
# in the new owner class (the original will remain unchanged).
def find_or_create(owner_class, *args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
name = args.first || :state
# Find an existing machine
machine = owner_class.respond_to?(:state_machines) &&
(args.first && owner_class.state_machines[name] || !args.first &&
owner_class.state_machines.values.first) || nil
if machine
# Only create a new copy if changes are being made to the machine in
# a subclass
if machine.owner_class != owner_class && (options.any? || block_given?)
machine = machine.clone
machine.initial_state = options[:initial] if options.include?(:initial)
machine.owner_class = owner_class
end
# Evaluate DSL
machine.instance_eval(&block) if block_given?
else
# No existing machine: create a new one
machine = new(owner_class, name, options, &block)
end
machine
end
def draw(*)
fail NotImplementedError
end
# Default messages to use for validation errors in ORM integrations
attr_accessor :default_messages
attr_accessor :ignore_method_conflicts
end
@default_messages = {
:invalid => 'is invalid',
:invalid_event => 'cannot transition when %s',
:invalid_transition => 'cannot transition via "%1$s"'
}
# Whether to ignore any conflicts that are detected for helper methods that
# get generated for a machine's owner class. Default is false.
@ignore_method_conflicts = false
# The class that the machine is defined in
attr_reader :owner_class
# The name of the machine, used for scoping methods generated for the
# machine as a whole (not states or events)
attr_reader :name
# The events that trigger transitions. These are sorted, by default, in
# the order in which they were defined.
attr_reader :events
# A list of all of the states known to this state machine. This will pull
# states from the following sources:
# * Initial state
# * State behaviors
# * Event transitions (:to, :from, and :except_from options)
# * Transition callbacks (:to, :from, :except_to, and :except_from options)
# * Unreferenced states (using +other_states+ helper)
#
# These are sorted, by default, in the order in which they were referenced.
attr_reader :states
# The callbacks to invoke before/after a transition is performed
#
# Maps :before => callbacks and :after => callbacks
attr_reader :callbacks
# The action to invoke when an object transitions
attr_reader :action
# An identifier that forces all methods (including state predicates and
# event methods) to be generated with the value prefixed or suffixed,
# depending on the context.
attr_reader :namespace
# Whether the machine will use transactions when firing events
attr_reader :use_transactions
# Creates a new state machine for the given attribute
def initialize(owner_class, *args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
options.assert_valid_keys(:attribute, :initial, :initialize, :action, :plural, :namespace, :integration, :messages, :use_transactions)
# Find an integration that matches this machine's owner class
if options.include?(:integration)
@integration = options[:integration] && StateMachines::Integrations.find_by_name(options[:integration])
else
@integration = StateMachines::Integrations.match(owner_class)
end
if @integration
extend @integration
options = (@integration.defaults || {}).merge(options)
end
# Add machine-wide defaults
options = {:use_transactions => true, :initialize => true}.merge(options)
# Set machine configuration
@name = args.first || :state
@attribute = options[:attribute] || @name
@events = EventCollection.new(self)
@states = StateCollection.new(self)
@callbacks = {:before => [], :after => [], :failure => []}
@namespace = options[:namespace]
@messages = options[:messages] || {}
@action = options[:action]
@use_transactions = options[:use_transactions]
@initialize_state = options[:initialize]
@action_hook_defined = false
self.owner_class = owner_class
# Merge with sibling machine configurations
add_sibling_machine_configs
# Define class integration
define_helpers
define_scopes(options[:plural])
after_initialize
# Evaluate DSL
instance_eval(&block) if block_given?
self.initial_state = options[:initial] unless sibling_machines.any?
end
# Creates a copy of this machine in addition to copies of each associated
# event/states/callback, so that the modifications to those collections do
# not affect the original machine.
def initialize_copy(orig) #:nodoc:
super
@events = @events.dup
@events.machine = self
@states = @states.dup
@states.machine = self
@callbacks = {:before => @callbacks[:before].dup, :after => @callbacks[:after].dup, :failure => @callbacks[:failure].dup}
end
# Sets the class which is the owner of this state machine. Any methods
# generated by states, events, or other parts of the machine will be defined
# on the given owner class.
def owner_class=(klass)
@owner_class = klass
# Create modules for extending the class with state/event-specific methods
@helper_modules = helper_modules = {:instance => HelperModule.new(self, :instance), :class => HelperModule.new(self, :class)}
owner_class.class_eval do
extend helper_modules[:class]
include helper_modules[:instance]
end
# Add class-/instance-level methods to the owner class for state initialization
unless owner_class < StateMachines::InstanceMethods
owner_class.class_eval do
extend StateMachines::ClassMethods
include StateMachines::InstanceMethods
end
define_state_initializer if @initialize_state
end
# Record this machine as matched to the name in the current owner class.
# This will override any machines mapped to the same name in any superclasses.
owner_class.state_machines[name] = self
end
# Sets the initial state of the machine. This can be either the static name
# of a state or a lambda block which determines the initial state at
# creation time.
def initial_state=(new_initial_state)
@initial_state = new_initial_state
add_states([@initial_state]) unless dynamic_initial_state?
# Update all states to reflect the new initial state
states.each { |state| state.initial = (state.name == @initial_state) }
# Output a warning if there are conflicting initial states for the machine's
# attribute
initial_state = states.detect { |state| state.initial }
if !owner_class_attribute_default.nil? && (dynamic_initial_state? || !owner_class_attribute_default_matches?(initial_state))
warn(
"Both #{owner_class.name} and its #{name.inspect} machine have defined "\
"a different default for \"#{attribute}\". Use only one or the other for "\
"defining defaults to avoid unexpected behaviors."
)
end
end
# Gets the initial state of the machine for the given object. If a dynamic
# initial state was configured for this machine, then the object will be
# passed into the lambda block to help determine the actual state.
#
# == Examples
#
# With a static initial state:
#
# class Vehicle
# state_machine :initial => :parked do
# ...
# end
# end
#
# vehicle = Vehicle.new
# Vehicle.state_machine.initial_state(vehicle) # => #<StateMachines::State name=:parked value="parked" initial=true>
#
# With a dynamic initial state:
#
# class Vehicle
# attr_accessor :force_idle
#
# state_machine :initial => lambda {|vehicle| vehicle.force_idle ? :idling : :parked} do
# ...
# end
# end
#
# vehicle = Vehicle.new
#
# vehicle.force_idle = true
# Vehicle.state_machine.initial_state(vehicle) # => #<StateMachines::State name=:idling value="idling" initial=false>
#
# vehicle.force_idle = false
# Vehicle.state_machine.initial_state(vehicle) # => #<StateMachines::State name=:parked value="parked" initial=false>
def initial_state(object)
states.fetch(dynamic_initial_state? ? evaluate_method(object, @initial_state) : @initial_state) if instance_variable_defined?('@initial_state')
end
# Whether a dynamic initial state is being used in the machine
def dynamic_initial_state?
instance_variable_defined?('@initial_state') && @initial_state.is_a?(Proc)
end
# Initializes the state on the given object. Initial values are only set if
# the machine's attribute hasn't been previously initialized.
#
# Configuration options:
# * <tt>:force</tt> - Whether to initialize the state regardless of its
# current value
# * <tt>:to</tt> - A hash to set the initial value in instead of writing
# directly to the object
def initialize_state(object, options = {})
state = initial_state(object)
if state && (options[:force] || initialize_state?(object))
value = state.value
if hash = options[:to]
hash[attribute.to_s] = value
else
write(object, :state, value)
end
end
end
# Gets the actual name of the attribute on the machine's owner class that
# stores data with the given name.
def attribute(name = :state)
name == :state ? @attribute : :"#{self.name}_#{name}"
end
# Defines a new helper method in an instance or class scope with the given
# name. If the method is already defined in the scope, then this will not
# override it.
#
# If passing in a block, there are two side effects to be aware of
# 1. The method cannot be chained, meaning that the block cannot call +super+
# 2. If the method is already defined in an ancestor, then it will not get
# overridden and a warning will be output.
#
# Example:
#
# # Instance helper
# machine.define_helper(:instance, :state_name) do |machine, object|
# machine.states.match(object).name
# end
#
# # Class helper
# machine.define_helper(:class, :state_machine_name) do |machine, klass|
# "State"
# end
#
# You can also define helpers using string evaluation like so:
#
# # Instance helper
# machine.define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
# def state_name
# self.class.state_machine(:state).states.match(self).name
# end
# end_eval
#
# # Class helper
# machine.define_helper :class, <<-end_eval, __FILE__, __LINE__ + 1
# def state_machine_name
# "State"
# end
# end_eval
def define_helper(scope, method, *args, &block)
helper_module = @helper_modules.fetch(scope)
if block_given?
if !self.class.ignore_method_conflicts && conflicting_ancestor = owner_class_ancestor_has_method?(scope, method)
ancestor_name = conflicting_ancestor.name && !conflicting_ancestor.name.empty? ? conflicting_ancestor.name : conflicting_ancestor.to_s
warn "#{scope == :class ? 'Class' : 'Instance'} method \"#{method}\" is already defined in #{ancestor_name}, use generic helper instead or set StateMachines::Machine.ignore_method_conflicts = true."
else
name = self.name
helper_module.class_eval do
define_method(method) do |*block_args|
block.call((scope == :instance ? self.class : self).state_machine(name), self, *block_args)
end
end
end
else
helper_module.class_eval(method, *args)
end
end
# Customizes the definition of one or more states in the machine.
#
# Configuration options:
# * <tt>:value</tt> - The actual value to store when an object transitions
# to the state. Default is the name (stringified).
# * <tt>:cache</tt> - If a dynamic value (via a lambda block) is being used,
# then setting this to true will cache the evaluated result
# * <tt>:if</tt> - Determines whether an object's value matches the state
# (e.g. :value => lambda {Time.now}, :if => lambda {|state| !state.nil?}).
# By default, the configured value is matched.
# * <tt>:human_name</tt> - The human-readable version of this state's name.
# By default, this is either defined by the integration or stringifies the
# name and converts underscores to spaces.
#
# == Customizing the stored value
#
# Whenever a state is automatically discovered in the state machine, its
# default value is assumed to be the stringified version of the name. For
# example,
#
# class Vehicle
# state_machine :initial => :parked do
# event :ignite do
# transition :parked => :idling
# end
# end
# end
#
# In the above state machine, there are two states automatically discovered:
# :parked and :idling. These states, by default, will store their stringified
# equivalents when an object moves into that state (e.g. "parked" / "idling").
#
# For legacy systems or when tying state machines into existing frameworks,
# it's oftentimes necessary to need to store a different value for a state
# than the default. In order to continue taking advantage of an expressive
# state machine and helper methods, every defined state can be re-configured
# with a custom stored value. For example,
#
# class Vehicle
# state_machine :initial => :parked do
# event :ignite do
# transition :parked => :idling
# end
#
# state :idling, :value => 'IDLING'
# state :parked, :value => 'PARKED
# end
# end
#
# This is also useful if being used in association with a database and,
# instead of storing the state name in a column, you want to store the
# state's foreign key:
#
# class VehicleState < ActiveRecord::Base
# end
#
# class Vehicle < ActiveRecord::Base
# state_machine :attribute => :state_id, :initial => :parked do
# event :ignite do
# transition :parked => :idling
# end
#
# states.each do |state|
# self.state(state.name, :value => lambda { VehicleState.find_by_name(state.name.to_s).id }, :cache => true)
# end
# end
# end
#
# In the above example, each known state is configured to store it's
# associated database id in the +state_id+ attribute. Also, notice that a
# lambda block is used to define the state's value. This is required in
# situations (like testing) where the model is loaded without any existing
# data (i.e. no VehicleState records available).
#
# One caveat to the above example is to keep performance in mind. To avoid
# constant db hits for looking up the VehicleState ids, the value is cached
# by specifying the <tt>:cache</tt> option. Alternatively, a custom
# caching strategy can be used like so:
#
# class VehicleState < ActiveRecord::Base
# cattr_accessor :cache_store
# self.cache_store = ActiveSupport::Cache::MemoryStore.new
#
# def self.find_by_name(name)
# cache_store.fetch(name) { find(:first, :conditions => {:name => name}) }
# end
# end
#
# === Dynamic values
#
# In addition to customizing states with other value types, lambda blocks
# can also be specified to allow for a state's value to be determined
# dynamically at runtime. For example,
#
# class Vehicle
# state_machine :purchased_at, :initial => :available do
# event :purchase do
# transition all => :purchased
# end
#
# event :restock do
# transition all => :available
# end
#
# state :available, :value => nil
# state :purchased, :if => lambda {|value| !value.nil?}, :value => lambda {Time.now}
# end
# end
#
# In the above definition, the <tt>:purchased</tt> state is customized with
# both a dynamic value *and* a value matcher.
#
# When an object transitions to the purchased state, the value's lambda
# block will be called. This will get the current time and store it in the
# object's +purchased_at+ attribute.
#
# *Note* that the custom matcher is very important here. Since there's no
# way for the state machine to figure out an object's state when it's set to
# a runtime value, it must be explicitly defined. If the <tt>:if</tt> option
# were not configured for the state, then an ArgumentError exception would
# be raised at runtime, indicating that the state machine could not figure
# out what the current state of the object was.
#
# == Behaviors
#
# Behaviors define a series of methods to mixin with objects when the current
# state matches the given one(s). This allows instance methods to behave
# a specific way depending on what the value of the object's state is.
#
# For example,
#
# class Vehicle
# attr_accessor :driver
# attr_accessor :passenger
#
# state_machine :initial => :parked do
# event :ignite do
# transition :parked => :idling
# end
#
# state :parked do
# def speed
# 0
# end
#
# def rotate_driver
# driver = self.driver
# self.driver = passenger
# self.passenger = driver
# true
# end
# end
#
# state :idling, :first_gear do
# def speed
# 20
# end
#
# def rotate_driver
# self.state = 'parked'
# rotate_driver
# end
# end
#
# other_states :backing_up
# end
# end
#
# In the above example, there are two dynamic behaviors defined for the
# class:
# * +speed+
# * +rotate_driver+
#
# Each of these behaviors are instance methods on the Vehicle class. However,
# which method actually gets invoked is based on the current state of the
# object. Using the above class as the example:
#
# vehicle = Vehicle.new
# vehicle.driver = 'John'
# vehicle.passenger = 'Jane'
#
# # Behaviors in the "parked" state
# vehicle.state # => "parked"
# vehicle.speed # => 0
# vehicle.rotate_driver # => true
# vehicle.driver # => "Jane"
# vehicle.passenger # => "John"
#
# vehicle.ignite # => true
#
# # Behaviors in the "idling" state
# vehicle.state # => "idling"
# vehicle.speed # => 20
# vehicle.rotate_driver # => true
# vehicle.driver # => "John"
# vehicle.passenger # => "Jane"
#
# As can be seen, both the +speed+ and +rotate_driver+ instance method
# implementations changed how they behave based on what the current state
# of the vehicle was.
#
# === Invalid behaviors
#
# If a specific behavior has not been defined for a state, then a
# NoMethodError exception will be raised, indicating that that method would
# not normally exist for an object with that state.
#
# Using the example from before:
#
# vehicle = Vehicle.new
# vehicle.state = 'backing_up'
# vehicle.speed # => NoMethodError: undefined method 'speed' for #<Vehicle:0xb7d296ac> in state "backing_up"
#
# === Using matchers
#
# The +all+ / +any+ matchers can be used to easily define behaviors for a
# group of states. Note, however, that you cannot use these matchers to
# set configurations for states. Behaviors using these matchers can be
# defined at any point in the state machine and will always get applied to
# the proper states.
#
# For example:
#
# state_machine :initial => :parked do
# ...
#
# state all - [:parked, :idling, :stalled] do
# validates_presence_of :speed
#
# def speed
# gear * 10
# end
# end
# end
#
# == State-aware class methods
#
# In addition to defining scopes for instance methods that are state-aware,
# the same can be done for certain types of class methods.
#
# Some libraries have support for class-level methods that only run certain
# behaviors based on a conditions hash passed in. For example:
#
# class Vehicle < ActiveRecord::Base
# state_machine do
# ...
# state :first_gear, :second_gear, :third_gear do
# validates_presence_of :speed
# validates_inclusion_of :speed, :in => 0..25, :if => :in_school_zone?
# end
# end
# end
#
# In the above ActiveRecord model, two validations have been defined which
# will *only* run when the Vehicle object is in one of the three states:
# +first_gear+, +second_gear+, or +third_gear. Notice, also, that if/unless
# conditions can continue to be used.
#
# This functionality is not library-specific and can work for any class-level
# method that is defined like so:
#
# def validates_presence_of(attribute, options = {})
# ...
# end
#
# The minimum requirement is that the last argument in the method be an
# options hash which contains at least <tt>:if</tt> condition support.
def state(*names, &block)
options = names.last.is_a?(Hash) ? names.pop : {}
options.assert_valid_keys(:value, :cache, :if, :human_name)
# Store the context so that it can be used for / matched against any state
# that gets added
@states.context(names, &block) if block_given?
if names.first.is_a?(Matcher)
# Add any states referenced in the matcher. When matchers are used,
# states are not allowed to be configured.
raise ArgumentError, "Cannot configure states when using matchers (using #{options.inspect})" if options.any?
states = add_states(names.first.values)
else
states = add_states(names)
# Update the configuration for the state(s)
states.each do |state|
if options.include?(:value)
state.value = options[:value]
self.states.update(state)
end
state.human_name = options[:human_name] if options.include?(:human_name)
state.cache = options[:cache] if options.include?(:cache)
state.matcher = options[:if] if options.include?(:if)
end
end
states.length == 1 ? states.first : states
end
alias_method :other_states, :state
# Gets the current value stored in the given object's attribute.
#
# For example,
#
# class Vehicle
# state_machine :initial => :parked do
# ...
# end
# end
#
# vehicle = Vehicle.new # => #<Vehicle:0xb7d94ab0 @state="parked">
# Vehicle.state_machine.read(vehicle, :state) # => "parked" # Equivalent to vehicle.state
# Vehicle.state_machine.read(vehicle, :event) # => nil # Equivalent to vehicle.state_event
def read(object, attribute, ivar = false)
attribute = self.attribute(attribute)
if ivar
object.instance_variable_defined?("@#{attribute}") ? object.instance_variable_get("@#{attribute}") : nil
else
object.send(attribute)
end
end
# Sets a new value in the given object's attribute.
#
# For example,
#
# class Vehicle
# state_machine :initial => :parked do
# ...
# end
# end
#
# vehicle = Vehicle.new # => #<Vehicle:0xb7d94ab0 @state="parked">
# Vehicle.state_machine.write(vehicle, :state, 'idling') # => Equivalent to vehicle.state = 'idling'
# Vehicle.state_machine.write(vehicle, :event, 'park') # => Equivalent to vehicle.state_event = 'park'
# vehicle.state # => "idling"
# vehicle.event # => "park"
def write(object, attribute, value, ivar = false)
attribute = self.attribute(attribute)
ivar ? object.instance_variable_set("@#{attribute}", value) : object.send("#{attribute}=", value)
end
# Defines one or more events for the machine and the transitions that can
# be performed when those events are run.
#
# This method is also aliased as +on+ for improved compatibility with
# using a domain-specific language.
#
# Configuration options:
# * <tt>:human_name</tt> - The human-readable version of this event's name.
# By default, this is either defined by the integration or stringifies the
# name and converts underscores to spaces.
#
# == Instance methods
#
# The following instance methods are generated when a new event is defined
# (the "park" event is used as an example):
# * <tt>park(..., run_action = true)</tt> - Fires the "park" event,
# transitioning from the current state to the next valid state. If the
# last argument is a boolean, it will control whether the machine's action
# gets run.
# * <tt>park!(..., run_action = true)</tt> - Fires the "park" event,
# transitioning from the current state to the next valid state. If the
# transition fails, then a StateMachines::InvalidTransition error will be
# raised. If the last argument is a boolean, it will control whether the
# machine's action gets run.
# * <tt>can_park?(requirements = {})</tt> - Checks whether the "park" event
# can be fired given the current state of the object. This will *not* run
# validations or callbacks in ORM integrations. It will only determine if
# the state machine defines a valid transition for the event. To check
# whether an event can fire *and* passes validations, use event attributes
# (e.g. state_event) as described in the "Events" documentation of each
# ORM integration.
# * <tt>park_transition(requirements = {})</tt> - Gets the next transition
# that would be performed if the "park" event were to be fired now on the
# object or nil if no transitions can be performed. Like <tt>can_park?</tt>
# this will also *not* run validations or callbacks. It will only
# determine if the state machine defines a valid transition for the event.
#
# With a namespace of "car", the above names map to the following methods:
# * <tt>can_park_car?</tt>
# * <tt>park_car_transition</tt>
# * <tt>park_car</tt>
# * <tt>park_car!</tt>
#
# The <tt>can_park?</tt> and <tt>park_transition</tt> helpers both take an
# optional set of requirements for determining what transitions are available
# for the current object. These requirements include:
# * <tt>:from</tt> - One or more states to transition from. If none are
# specified, then this will be the object's current state.
# * <tt>:to</tt> - One or more states to transition to. If none are
# specified, then this will match any to state.
# * <tt>:guard</tt> - Whether to guard transitions with the if/unless
# conditionals defined for each one. Default is true.
#
# == Defining transitions
#
# +event+ requires a block which allows you to define the possible
# transitions that can happen as a result of that event. For example,
#
# event :park, :stop do
# transition :idling => :parked
# end
#
# event :first_gear do
# transition :parked => :first_gear, :if => :seatbelt_on?
# transition :parked => same # Allow to loopback if seatbelt is off
# end
#
# See StateMachines::Event#transition for more information on
# the possible options that can be passed in.
#
# *Note* that this block is executed within the context of the actual event
# object. As a result, you will not be able to reference any class methods
# on the model without referencing the class itself. For example,
#
# class Vehicle
# def self.safe_states
# [:parked, :idling, :stalled]
# end
#
# state_machine do
# event :park do
# transition Vehicle.safe_states => :parked
# end
# end
# end
#
# == Overriding the event method
#
# By default, this will define an instance method (with the same name as the
# event) that will fire the next possible transition for that. Although the
# +before_transition+, +after_transition+, and +around_transition+ hooks
# allow you to define behavior that gets executed as a result of the event's
# transition, you can also override the event method in order to have a
# little more fine-grained control.
#
# For example:
#
# class Vehicle
# state_machine do
# event :park do
# ...
# end
# end
#
# def park(*)
# take_deep_breath # Executes before the transition (and before_transition hooks) even if no transition is possible
# if result = super # Runs the transition and all before/after/around hooks
# applaud # Executes after the transition (and after_transition hooks)
# end
# result
# end
# end
#
# There are a few important things to note here. First, the method
# signature is defined with an unlimited argument list in order to allow
# callers to continue passing arguments that are expected by state_machine.
# For example, it will still allow calls to +park+ with a single parameter
# for skipping the configured action.
#
# Second, the overridden event method must call +super+ in order to run the
# logic for running the next possible transition. In order to remain
# consistent with other events, the result of +super+ is returned.
#
# Third, any behavior defined in this method will *not* get executed if
# you're taking advantage of attribute-based event transitions. For example:
#
# vehicle = Vehicle.new
# vehicle.state_event = 'park'
# vehicle.save
#
# In this case, the +park+ event will run the before/after/around transition
# hooks and transition the state, but the behavior defined in the overriden
# +park+ method will *not* be executed.
#
# == Defining additional arguments
#
# Additional arguments can be passed into events and accessed by transition
# hooks like so:
#
# class Vehicle
# state_machine do
# after_transition :on => :park do |vehicle, transition|
# kind = *transition.args # :parallel
# ...
# end
# after_transition :on => :park, :do => :take_deep_breath
#
# event :park do
# ...
# end
#
# def take_deep_breath(transition)
# kind = *transition.args # :parallel
# ...
# end
# end
# end
#
# vehicle = Vehicle.new
# vehicle.park(:parallel)
#
# *Remember* that if the last argument is a boolean, it will be used as the
# +run_action+ parameter to the event action. Using the +park+ action
# example from above, you can might call it like so:
#
# vehicle.park # => Uses default args and runs machine action
# vehicle.park(:parallel) # => Specifies the +kind+ argument and runs the machine action
# vehicle.park(:parallel, false) # => Specifies the +kind+ argument and *skips* the machine action
#
# If you decide to override the +park+ event method *and* define additional
# arguments, you can do so as shown below:
#
# class Vehicle
# state_machine do
# event :park do
# ...
# end
# end
#
# def park(kind = :parallel, *args)
# take_deep_breath if kind == :parallel
# super
# end
# end
#
# Note that +super+ is called instead of <tt>super(*args)</tt>. This allow
# the entire arguments list to be accessed by transition callbacks through
# StateMachines::Transition#args.
#
# === Using matchers
#
# The +all+ / +any+ matchers can be used to easily execute blocks for a
# group of events. Note, however, that you cannot use these matchers to
# set configurations for events. Blocks using these matchers can be
# defined at any point in the state machine and will always get applied to
# the proper events.
#
# For example:
#
# state_machine :initial => :parked do
# ...
#
# event all - [:crash] do
# transition :stalled => :parked
# end
# end
#
# == Example
#
# class Vehicle
# state_machine do
# # The park, stop, and halt events will all share the given transitions
# event :park, :stop, :halt do
# transition [:idling, :backing_up] => :parked
# end
#
# event :stop do
# transition :first_gear => :idling
# end
#
# event :ignite do
# transition :parked => :idling
# transition :idling => same # Allow ignite while still idling
# end
# end
# end
def event(*names, &block)
options = names.last.is_a?(Hash) ? names.pop : {}
options.assert_valid_keys(:human_name)
# Store the context so that it can be used for / matched against any event
# that gets added
@events.context(names, &block) if block_given?
if names.first.is_a?(Matcher)
# Add any events referenced in the matcher. When matchers are used,
# events are not allowed to be configured.
raise ArgumentError, "Cannot configure events when using matchers (using #{options.inspect})" if options.any?
events = add_events(names.first.values)
else
events = add_events(names)
# Update the configuration for the event(s)
events.each do |event|
event.human_name = options[:human_name] if options.include?(:human_name)
# Add any states that may have been referenced within the event
add_states(event.known_states)
end
end
events.length == 1 ? events.first : events
end
alias_method :on, :event
# Creates a new transition that determines what to change the current state
# to when an event fires.
#
# == Defining transitions
#
# The options for a new transition uses the Hash syntax to map beginning
# states to ending states. For example,
#
# transition :parked => :idling, :idling => :first_gear, :on => :ignite
#
# In this case, when the +ignite+ event is fired, this transition will cause
# the state to be +idling+ if it's current state is +parked+ or +first_gear+
# if it's current state is +idling+.
#
# To help define these implicit transitions, a set of helpers are available
# for slightly more complex matching:
# * <tt>all</tt> - Matches every state in the machine
# * <tt>all - [:parked, :idling, ...]</tt> - Matches every state except those specified
# * <tt>any</tt> - An alias for +all+ (matches every state in the machine)
# * <tt>same</tt> - Matches the same state being transitioned from
#
# See StateMachines::MatcherHelpers for more information.
#
# Examples:
#
# transition all => nil, :on => :ignite # Transitions to nil regardless of the current state
# transition all => :idling, :on => :ignite # Transitions to :idling regardless of the current state
# transition all - [:idling, :first_gear] => :idling, :on => :ignite # Transitions every state but :idling and :first_gear to :idling
# transition nil => :idling, :on => :ignite # Transitions to :idling from the nil state
# transition :parked => :idling, :on => :ignite # Transitions to :idling if :parked
# transition [:parked, :stalled] => :idling, :on => :ignite # Transitions to :idling if :parked or :stalled
#
# transition :parked => same, :on => :park # Loops :parked back to :parked
# transition [:parked, :stalled] => same, :on => [:park, :stall] # Loops either :parked or :stalled back to the same state on the park and stall events
# transition all - :parked => same, :on => :noop # Loops every state but :parked back to the same state
#
# # Transitions to :idling if :parked, :first_gear if :idling, or :second_gear if :first_gear
# transition :parked => :idling, :idling => :first_gear, :first_gear => :second_gear, :on => :shift_up
#
# == Verbose transitions
#
# Transitions can also be defined use an explicit set of configuration
# options:
# * <tt>:from</tt> - A state or array of states that can be transitioned from.
# If not specified, then the transition can occur for *any* state.
# * <tt>:to</tt> - The state that's being transitioned to. If not specified,
# then the transition will simply loop back (i.e. the state will not change).
# * <tt>:except_from</tt> - A state or array of states that *cannot* be
# transitioned from.
#
# These options must be used when defining transitions within the context
# of a state.
#
# Examples:
#
# transition :to => nil, :on => :park
# transition :to => :idling, :on => :ignite
# transition :except_from => [:idling, :first_gear], :to => :idling, :on => :ignite
# transition :from => nil, :to => :idling, :on => :ignite
# transition :from => [:parked, :stalled], :to => :idling, :on => :ignite
#
# == Conditions
#
# In addition to the state requirements for each transition, a condition
# can also be defined to help determine whether that transition is
# available. These options will work on both the normal and verbose syntax.
#
# Configuration options:
# * <tt>:if</tt> - A method, proc or string to call to determine if the
# transition should occur (e.g. :if => :moving?, or :if => lambda {|vehicle| vehicle.speed > 60}).
# The condition should return or evaluate to true or false.
# * <tt>:unless</tt> - A method, proc or string to call to determine if the
# transition should not occur (e.g. :unless => :stopped?, or :unless => lambda {|vehicle| vehicle.speed <= 60}).
# The condition should return or evaluate to true or false.
#
# Examples:
#
# transition :parked => :idling, :on => :ignite, :if => :moving?
# transition :parked => :idling, :on => :ignite, :unless => :stopped?
# transition :idling => :first_gear, :first_gear => :second_gear, :on => :shift_up, :if => :seatbelt_on?
#
# transition :from => :parked, :to => :idling, :on => ignite, :if => :moving?
# transition :from => :parked, :to => :idling, :on => ignite, :unless => :stopped?
#
# == Order of operations
#
# Transitions are evaluated in the order in which they're defined. As a
# result, if more than one transition applies to a given object, then the
# first transition that matches will be performed.
def transition(options)
raise ArgumentError, 'Must specify :on event' unless options[:on]
branches = []
options = options.dup
event(*Array(options.delete(:on))) { branches << transition(options) }
branches.length == 1 ? branches.first : branches
end
# Creates a callback that will be invoked *before* a transition is
# performed so long as the given requirements match the transition.
#
# == The callback
#
# Callbacks must be defined as either an argument, in the :do option, or
# as a block. For example,
#
# class Vehicle
# state_machine do
# before_transition :set_alarm
# before_transition :set_alarm, all => :parked
# before_transition all => :parked, :do => :set_alarm
# before_transition all => :parked do |vehicle, transition|
# vehicle.set_alarm
# end
# ...
# end
# end
#
# Notice that the first three callbacks are the same in terms of how the
# methods to invoke are defined. However, using the <tt>:do</tt> can
# provide for a more fluid DSL.
#
# In addition, multiple callbacks can be defined like so:
#
# class Vehicle
# state_machine do
# before_transition :set_alarm, :lock_doors, all => :parked
# before_transition all => :parked, :do => [:set_alarm, :lock_doors]
# before_transition :set_alarm do |vehicle, transition|
# vehicle.lock_doors
# end
# end
# end
#
# Notice that the different ways of configuring methods can be mixed.
#
# == State requirements
#
# Callbacks can require that the machine be transitioning from and to
# specific states. These requirements use a Hash syntax to map beginning
# states to ending states. For example,
#
# before_transition :parked => :idling, :idling => :first_gear, :do => :set_alarm
#
# In this case, the +set_alarm+ callback will only be called if the machine
# is transitioning from +parked+ to +idling+ or from +idling+ to +parked+.
#
# To help define state requirements, a set of helpers are available for
# slightly more complex matching:
# * <tt>all</tt> - Matches every state/event in the machine
# * <tt>all - [:parked, :idling, ...]</tt> - Matches every state/event except those specified
# * <tt>any</tt> - An alias for +all+ (matches every state/event in the machine)
# * <tt>same</tt> - Matches the same state being transitioned from
#
# See StateMachines::MatcherHelpers for more information.
#
# Examples:
#
# before_transition :parked => [:idling, :first_gear], :do => ... # Matches from parked to idling or first_gear
# before_transition all - [:parked, :idling] => :idling, :do => ... # Matches from every state except parked and idling to idling
# before_transition all => :parked, :do => ... # Matches all states to parked
# before_transition any => same, :do => ... # Matches every loopback
#
# == Event requirements
#
# In addition to state requirements, an event requirement can be defined so
# that the callback is only invoked on specific events using the +on+
# option. This can also use the same matcher helpers as the state
# requirements.
#
# Examples:
#
# before_transition :on => :ignite, :do => ... # Matches only on ignite
# before_transition :on => all - :ignite, :do => ... # Matches on every event except ignite
# before_transition :parked => :idling, :on => :ignite, :do => ... # Matches from parked to idling on ignite
#
# == Verbose Requirements
#
# Requirements can also be defined using verbose options rather than the
# implicit Hash syntax and helper methods described above.
#
# Configuration options:
# * <tt>:from</tt> - One or more states being transitioned from. If none
# are specified, then all states will match.
# * <tt>:to</tt> - One or more states being transitioned to. If none are
# specified, then all states will match.
# * <tt>:on</tt> - One or more events that fired the transition. If none
# are specified, then all events will match.
# * <tt>:except_from</tt> - One or more states *not* being transitioned from
# * <tt>:except_to</tt> - One more states *not* being transitioned to
# * <tt>:except_on</tt> - One or more events that *did not* fire the transition
#
# Examples:
#
# before_transition :from => :ignite, :to => :idling, :on => :park, :do => ...
# before_transition :except_from => :ignite, :except_to => :idling, :except_on => :park, :do => ...
#
# == Conditions
#
# In addition to the state/event requirements, a condition can also be
# defined to help determine whether the callback should be invoked.
#
# Configuration options:
# * <tt>:if</tt> - A method, proc or string to call to determine if the
# callback should occur (e.g. :if => :allow_callbacks, or
# :if => lambda {|user| user.signup_step > 2}). The method, proc or string
# should return or evaluate to a true or false value.
# * <tt>:unless</tt> - A method, proc or string to call to determine if the
# callback should not occur (e.g. :unless => :skip_callbacks, or
# :unless => lambda {|user| user.signup_step <= 2}). The method, proc or
# string should return or evaluate to a true or false value.
#
# Examples:
#
# before_transition :parked => :idling, :if => :moving?, :do => ...
# before_transition :on => :ignite, :unless => :seatbelt_on?, :do => ...
#
# == Accessing the transition
#
# In addition to passing the object being transitioned, the actual
# transition describing the context (e.g. event, from, to) can be accessed
# as well. This additional argument is only passed if the callback allows
# for it.
#
# For example,
#
# class Vehicle
# # Only specifies one parameter (the object being transitioned)
# before_transition all => :parked do |vehicle|
# vehicle.set_alarm
# end
#
# # Specifies 2 parameters (object being transitioned and actual transition)
# before_transition all => :parked do |vehicle, transition|
# vehicle.set_alarm(transition)
# end
# end
#
# *Note* that the object in the callback will only be passed in as an
# argument if callbacks are configured to *not* be bound to the object
# involved. This is the default and may change on a per-integration basis.
#
# See StateMachines::Transition for more information about the
# attributes available on the transition.
#
# == Usage with delegates
#
# As noted above, state_machine uses the callback method's argument list
# arity to determine whether to include the transition in the method call.
# If you're using delegates, such as those defined in ActiveSupport or
# Forwardable, the actual arity of the delegated method gets masked. This
# means that callbacks which reference delegates will always get passed the
# transition as an argument. For example:
#
# class Vehicle
# extend Forwardable
# delegate :refresh => :dashboard
#
# state_machine do
# before_transition :refresh
# ...
# end
#
# def dashboard
# @dashboard ||= Dashboard.new
# end
# end
#
# class Dashboard
# def refresh(transition)
# # ...
# end
# end
#
# In the above example, <tt>Dashboard#refresh</tt> *must* defined a
# +transition+ argument. Otherwise, an +ArgumentError+ exception will get
# raised. The only way around this is to avoid the use of delegates and
# manually define the delegate method so that the correct arity is used.
#
# == Examples
#
# Below is an example of a class with one state machine and various types
# of +before+ transitions defined for it:
#
# class Vehicle
# state_machine do
# # Before all transitions
# before_transition :update_dashboard
#
# # Before specific transition:
# before_transition [:first_gear, :idling] => :parked, :on => :park, :do => :take_off_seatbelt
#
# # With conditional callback:
# before_transition all => :parked, :do => :take_off_seatbelt, :if => :seatbelt_on?
#
# # Using helpers:
# before_transition all - :stalled => same, :on => any - :crash, :do => :update_dashboard
# ...
# end
# end
#
# As can be seen, any number of transitions can be created using various
# combinations of configuration options.
def before_transition(*args, &block)
options = (args.last.is_a?(Hash) ? args.pop : {})
options[:do] = args if args.any?
add_callback(:before, options, &block)
end
# Creates a callback that will be invoked *after* a transition is
# performed so long as the given requirements match the transition.
#
# See +before_transition+ for a description of the possible configurations
# for defining callbacks.
def after_transition(*args, &block)
options = (args.last.is_a?(Hash) ? args.pop : {})
options[:do] = args if args.any?
add_callback(:after, options, &block)
end
# Creates a callback that will be invoked *around* a transition so long as
# the given requirements match the transition.
#
# == The callback
#
# Around callbacks wrap transitions, executing code both before and after.
# These callbacks are defined in the exact same manner as before / after
# callbacks with the exception that the transition must be yielded to in
# order to finish running it.
#
# If defining +around+ callbacks using blocks, you must yield within the
# transition by directly calling the block (since yielding is not allowed
# within blocks).
#
# For example,
#
# class Vehicle
# state_machine do
# around_transition do |block|
# Benchmark.measure { block.call }
# end
#
# around_transition do |vehicle, block|
# logger.info "vehicle was #{state}..."
# block.call
# logger.info "...and is now #{state}"
# end
#
# around_transition do |vehicle, transition, block|
# logger.info "before #{transition.event}: #{vehicle.state}"
# block.call
# logger.info "after #{transition.event}: #{vehicle.state}"
# end
# end
# end
#
# Notice that referencing the block is similar to doing so within an
# actual method definition in that it is always the last argument.
#
# On the other hand, if you're defining +around+ callbacks using method
# references, you can yield like normal:
#
# class Vehicle
# state_machine do
# around_transition :benchmark
# ...
# end
#
# def benchmark
# Benchmark.measure { yield }
# end
# end
#
# See +before_transition+ for a description of the possible configurations
# for defining callbacks.
def around_transition(*args, &block)
options = (args.last.is_a?(Hash) ? args.pop : {})
options[:do] = args if args.any?
add_callback(:around, options, &block)
end
# Creates a callback that will be invoked *after* a transition failures to
# be performed so long as the given requirements match the transition.
#
# See +before_transition+ for a description of the possible configurations
# for defining callbacks. *Note* however that you cannot define the state
# requirements in these callbacks. You may only define event requirements.
#
# = The callback
#
# Failure callbacks get invoked whenever an event fails to execute. This
# can happen when no transition is available, a +before+ callback halts
# execution, or the action associated with this machine fails to succeed.
# In any of these cases, any failure callback that matches the attempted
# transition will be run.
#
# For example,
#
# class Vehicle
# state_machine do
# after_failure do |vehicle, transition|
# logger.error "vehicle #{vehicle} failed to transition on #{transition.event}"
# end
#
# after_failure :on => :ignite, :do => :log_ignition_failure
#
# ...
# end
# end
def after_failure(*args, &block)
options = (args.last.is_a?(Hash) ? args.pop : {})
options[:do] = args if args.any?
options.assert_valid_keys(:on, :do, :if, :unless)
add_callback(:failure, options, &block)
end
# Generates a list of the possible transition sequences that can be run on
# the given object. These paths can reveal all of the possible states and
# events that can be encountered in the object's state machine based on the
# object's current state.
#
# Configuration options:
# * +from+ - The initial state to start all paths from. By default, this
# is the object's current state.
# * +to+ - The target state to end all paths on. By default, paths will
# end when they loop back to the first transition on the path.
# * +deep+ - Whether to allow the target state to be crossed more than once
# in a path. By default, paths will immediately stop when the target
# state (if specified) is reached. If this is enabled, then paths can
# continue even after reaching the target state; they will stop when
# reaching the target state a second time.
#
# *Note* that the object is never modified when the list of paths is
# generated.
#
# == Examples
#
# class Vehicle
# state_machine :initial => :parked do
# event :ignite do
# transition :parked => :idling
# end
#
# event :shift_up do
# transition :idling => :first_gear, :first_gear => :second_gear
# end
#
# event :shift_down do
# transition :second_gear => :first_gear, :first_gear => :idling
# end
# end
# end
#
# vehicle = Vehicle.new # => #<Vehicle:0xb7c27024 @state="parked">
# vehicle.state # => "parked"
#
# vehicle.state_paths
# # => [
# # [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>,
# # #<StateMachines::Transition attribute=:state event=:shift_up from="idling" from_name=:idling to="first_gear" to_name=:first_gear>,
# # #<StateMachines::Transition attribute=:state event=:shift_up from="first_gear" from_name=:first_gear to="second_gear" to_name=:second_gear>,
# # #<StateMachines::Transition attribute=:state event=:shift_down from="second_gear" from_name=:second_gear to="first_gear" to_name=:first_gear>,
# # #<StateMachines::Transition attribute=:state event=:shift_down from="first_gear" from_name=:first_gear to="idling" to_name=:idling>],
# #
# # [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>,
# # #<StateMachines::Transition attribute=:state event=:shift_up from="idling" from_name=:idling to="first_gear" to_name=:first_gear>,
# # #<StateMachines::Transition attribute=:state event=:shift_down from="first_gear" from_name=:first_gear to="idling" to_name=:idling>]
# # ]
#
# vehicle.state_paths(:from => :parked, :to => :second_gear)
# # => [
# # [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>,
# # #<StateMachines::Transition attribute=:state event=:shift_up from="idling" from_name=:idling to="first_gear" to_name=:first_gear>,
# # #<StateMachines::Transition attribute=:state event=:shift_up from="first_gear" from_name=:first_gear to="second_gear" to_name=:second_gear>]
# # ]
#
# In addition to getting the possible paths that can be accessed, you can
# also get summary information about the states / events that can be
# accessed at some point along one of the paths. For example:
#
# # Get the list of states that can be accessed from the current state
# vehicle.state_paths.to_states # => [:idling, :first_gear, :second_gear]
#
# # Get the list of events that can be accessed from the current state
# vehicle.state_paths.events # => [:ignite, :shift_up, :shift_down]
def paths_for(object, requirements = {})
PathCollection.new(object, self, requirements)
end
# Marks the given object as invalid with the given message.
#
# By default, this is a no-op.
def invalidate(_object, _attribute, _message, _values = [])
end
# Gets a description of the errors for the given object. This is used to
# provide more detailed information when an InvalidTransition exception is
# raised.
def errors_for(_object)
''
end
# Resets any errors previously added when invalidating the given object.
#
# By default, this is a no-op.
def reset(_object)
end
# Generates the message to use when invalidating the given object after
# failing to transition on a specific event
def generate_message(name, values = [])
message = (@messages[name] || self.class.default_messages[name])
# Check whether there are actually any values to interpolate to avoid
# any warnings
if message.scan(/%./).any? { |match| match != '%%' }
message % values.map { |value| value.last }
else
message
end
end
# Runs a transaction, rolling back any changes if the yielded block fails.
#
# This is only applicable to integrations that involve databases. By
# default, this will not run any transactions since the changes aren't
# taking place within the context of a database.
def within_transaction(object)
if use_transactions
transaction(object) { yield }
else
yield
end
end
def draw(*)
fail NotImplementedError
end
# Determines whether an action hook was defined for firing attribute-based
# event transitions when the configured action gets called.
def action_hook?(self_only = false)
@action_hook_defined || !self_only && owner_class.state_machines.any? { |name, machine| machine.action == action && machine != self && machine.action_hook?(true) }
end
protected
# Runs additional initialization hooks. By default, this is a no-op.
def after_initialize
end
# Looks up other machines that have been defined in the owner class and
# are targeting the same attribute as this machine. When accessing
# sibling machines, they will be automatically copied for the current
# class if they haven't been already. This ensures that any configuration
# changes made to the sibling machines only affect this class and not any
# base class that may have originally defined the machine.
def sibling_machines
owner_class.state_machines.inject([]) do |machines, (name, machine)|
if machine.attribute == attribute && machine != self
machines << (owner_class.state_machine(name) {})
end
machines
end
end
# Determines if the machine's attribute needs to be initialized. This
# will only be true if the machine's attribute is blank.
def initialize_state?(object)
value = read(object, :state)
(value.nil? || value.respond_to?(:empty?) && value.empty?) && !states[value, :value]
end
# Adds helper methods for interacting with the state machine, including
# for states, events, and transitions
def define_helpers
define_state_accessor
define_state_predicate
define_event_helpers
define_path_helpers
define_action_helpers if define_action_helpers?
define_name_helpers
end
# Defines the initial values for state machine attributes. Static values
# are set prior to the original initialize method and dynamic values are
# set *after* the initialize method in case it is dependent on it.
def define_state_initializer
define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
def initialize(*)
self.class.state_machines.initialize_states(self) { super }
end
end_eval
end
# Adds reader/writer methods for accessing the state attribute
def define_state_accessor
attribute = self.attribute
@helper_modules[:instance].class_eval { attr_reader attribute } unless owner_class_ancestor_has_method?(:instance, attribute)
@helper_modules[:instance].class_eval { attr_writer attribute } unless owner_class_ancestor_has_method?(:instance, "#{attribute}=")
end
# Adds predicate method to the owner class for determining the name of the
# current state
def define_state_predicate
call_super = !!owner_class_ancestor_has_method?(:instance, "#{name}?")
define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
def #{name}?(*args)
args.empty? && (#{call_super} || defined?(super)) ? super : self.class.state_machine(#{name.inspect}).states.matches?(self, *args)
end
end_eval
end
# Adds helper methods for getting information about this state machine's
# events
def define_event_helpers
# Gets the events that are allowed to fire on the current object
define_helper(:instance, attribute(:events)) do |machine, object, *args|
machine.events.valid_for(object, *args).map { |event| event.name }
end
# Gets the next possible transitions that can be run on the current
# object
define_helper(:instance, attribute(:transitions)) do |machine, object, *args|
machine.events.transitions_for(object, *args)
end
# Fire an arbitrary event for this machine
define_helper(:instance, "fire_#{attribute(:event)}") do |machine, object, event, *args|
machine.events.fetch(event).fire(object, *args)
end
# Add helpers for tracking the event / transition to invoke when the
# action is called
if action
event_attribute = attribute(:event)
define_helper(:instance, event_attribute) do |machine, object|
# Interpret non-blank events as present
event = machine.read(object, :event, true)
event && !(event.respond_to?(:empty?) && event.empty?) ? event.to_sym : nil
end
# A roundabout way of writing the attribute is used here so that
# integrations can hook into this modification
define_helper(:instance, "#{event_attribute}=") do |machine, object, value|
machine.write(object, :event, value, true)
end
event_transition_attribute = attribute(:event_transition)
define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
protected; attr_accessor #{event_transition_attribute.inspect}
end_eval
end
end
# Adds helper methods for getting information about this state machine's
# available transition paths
def define_path_helpers
# Gets the paths of transitions available to the current object
define_helper(:instance, attribute(:paths)) do |machine, object, *args|
machine.paths_for(object, *args)
end
end
# Determines whether action helpers should be defined for this machine.
# This is only true if there is an action configured and no other machines
# have process this same configuration already.
def define_action_helpers?
action && !owner_class.state_machines.any? { |name, machine| machine.action == action && machine != self }
end
# Adds helper methods for automatically firing events when an action
# is invoked
def define_action_helpers
if action_hook
@action_hook_defined = true
define_action_hook
end
end
# Hooks directly into actions by defining the same method in an included
# module. As a result, when the action gets invoked, any state events
# defined for the object will get run. Method visibility is preserved.
def define_action_hook
action_hook = self.action_hook
action = self.action
private_action_hook = owner_class.private_method_defined?(action_hook)
# Only define helper if it hasn't
define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
def #{action_hook}(*)
self.class.state_machines.transitions(self, #{action.inspect}).perform { super }
end
private #{action_hook.inspect} if #{private_action_hook}
end_eval
end
# The method to hook into for triggering transitions when invoked. By
# default, this is the action configured for the machine.
#
# Since the default hook technique relies on module inheritance, the
# action must be defined in an ancestor of the owner classs in order for
# it to be the action hook.
def action_hook
action && owner_class_ancestor_has_method?(:instance, action) ? action : nil
end
# Determines whether there's already a helper method defined within the
# given scope. This is true only if one of the owner's ancestors defines
# the method and is further along in the ancestor chain than this
# machine's helper module.
def owner_class_ancestor_has_method?(scope, method)
return false unless owner_class_has_method?(scope, method)
superclasses = owner_class.ancestors.select { |ancestor| ancestor.is_a?(Class) }[1..-1]
if scope == :class
current = owner_class.singleton_class
superclass = superclasses.first
else
current = owner_class
superclass = owner_class.superclass
end
# Generate the list of modules that *only* occur in the owner class, but
# were included *prior* to the helper modules, in addition to the
# superclasses
ancestors = current.ancestors - superclass.ancestors + superclasses
ancestors = ancestors[ancestors.index(@helper_modules[scope])..-1].reverse
# Search for for the first ancestor that defined this method
ancestors.detect do |ancestor|
ancestor = ancestor.singleton_class if scope == :class && ancestor.is_a?(Class)
ancestor.method_defined?(method) || ancestor.private_method_defined?(method)
end
end
def owner_class_has_method?(scope, method)
target = scope == :class ? owner_class.singleton_class : owner_class
target.method_defined?(method) || target.private_method_defined?(method)
end
# Adds helper methods for accessing naming information about states and
# events on the owner class
def define_name_helpers
# Gets the humanized version of a state
define_helper(:class, "human_#{attribute(:name)}") do |machine, klass, state|
machine.states.fetch(state).human_name(klass)
end
# Gets the humanized version of an event
define_helper(:class, "human_#{attribute(:event_name)}") do |machine, klass, event|
machine.events.fetch(event).human_name(klass)
end
# Gets the state name for the current value
define_helper(:instance, attribute(:name)) do |machine, object|
machine.states.match!(object).name
end
# Gets the human state name for the current value
define_helper(:instance, "human_#{attribute(:name)}") do |machine, object|
machine.states.match!(object).human_name(object.class)
end
end
# Defines the with/without scope helpers for this attribute. Both the
# singular and plural versions of the attribute are defined for each
# scope helper. A custom plural can be specified if it cannot be
# automatically determined by either calling +pluralize+ on the attribute
# name or adding an "s" to the end of the name.
def define_scopes(custom_plural = nil)
plural = custom_plural || pluralize(name)
[:with, :without].each do |kind|
[name, plural].map { |s| s.to_s }.uniq.each do |suffix|
method = "#{kind}_#{suffix}"
if scope = send("create_#{kind}_scope", method)
# Converts state names to their corresponding values so that they
# can be looked up properly
define_helper(:class, method) do |machine, klass, *states|
run_scope(scope, machine, klass, states)
end
end
end
end
end
# Generates the results for the given scope based on one or more states to
# filter by
# Pluralizes the given word using #pluralize (if available) or simply
# adding an "s" to the end of the word
def pluralize(word)
word = word.to_s
if word.respond_to?(:pluralize)
word.pluralize
else
"#{name}s"
end
end
# Creates a scope for finding objects *with* a particular value or values
# for the attribute.
#
# By default, this is a no-op.
def create_with_scope(name)
end
# Creates a scope for finding objects *without* a particular value or
# values for the attribute.
#
# By default, this is a no-op.
def create_without_scope(name)
end
# Always yields
def transaction(object)
yield
end
# Gets the initial attribute value defined by the owner class (outside of
# the machine's definition). By default, this is always nil.
def owner_class_attribute_default
nil
end
# Checks whether the given state matches the attribute default specified
# by the owner class
def owner_class_attribute_default_matches?(state)
state.matches?(owner_class_attribute_default)
end
# Updates this machine based on the configuration of other machines in the
# owner class that share the same target attribute.
def add_sibling_machine_configs
# Add existing states
sibling_machines.each do |machine|
machine.states.each { |state| states << state unless states[state.name] }
end
end
# Adds a new transition callback of the given type.
def add_callback(type, options, &block)
callbacks[type == :around ? :before : type] << callback = Callback.new(type, options, &block)
add_states(callback.known_states)
callback
end
# Tracks the given set of states in the list of all known states for
# this machine
def add_states(new_states)
new_states.map do |new_state|
# Check for other states that use a different class type for their name.
# This typically prevents string / symbol misuse.
if new_state && conflict = states.detect { |state| state.name && state.name.class != new_state.class }
raise ArgumentError, "#{new_state.inspect} state defined as #{new_state.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all states must be consistent"
end
unless state = states[new_state]
states << state = State.new(self, new_state)
# Copy states over to sibling machines
sibling_machines.each { |machine| machine.states << state }
end
state
end
end
# Tracks the given set of events in the list of all known events for
# this machine
def add_events(new_events)
new_events.map do |new_event|
# Check for other states that use a different class type for their name.
# This typically prevents string / symbol misuse.
if conflict = events.detect { |event| event.name.class != new_event.class }
raise ArgumentError, "#{new_event.inspect} event defined as #{new_event.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all events must be consistent"
end
unless event = events[new_event]
events << event = Event.new(self, new_event)
end
event
end
end
end
|
cul/cul-ldap | lib/cul/ldap.rb | Cul.LDAP.search | ruby | def search(args = {})
super(args).tap do |result|
if result.is_a?(Array)
result.map!{ |e| Cul::LDAP::Entry.new(e) }
end
end
end | Wrapper around Net::LDAP#search, converts Net::LDAP::Entry objects to
Cul::LDAP::Entry objects. | train | https://github.com/cul/cul-ldap/blob/07c35bbf1c2fdc73719e32c39397c3971c0878bc/lib/cul/ldap.rb#L48-L54 | class LDAP < Net::LDAP
CONFIG_FILENAME = 'cul_ldap.yml'
CONFIG_DEFAULTS = {
host: 'ldap.columbia.edu',
port: '636',
encryption: {
method: :simple_tls,
tls_options: OpenSSL::SSL::SSLContext::DEFAULT_PARAMS
}
}.freeze
def initialize(options = {})
super(build_config(options)) # All keys have to be symbols.
end
# LDAP lookup based on UNI. If record could not be found returns nil.
#
# @param [String] uni
# @return [Cul::LDAP::Entry] containing all the ldap information available for the uni given
# @return [nil] if record for uni could not be found, or more than one record was found
def find_by_uni(uni)
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("uid", uni))
(entries.count == 1) ? entries.first : nil
end
# LDAP lookup based on name.
#
# @param [String] name
# @return [Cul::LDAP::Entry] containing the entry matching this name, if it is unique
# @return [nil] if record could not be found or if there is more than one match
def find_by_name(name)
if name.include?(',')
name = name.split(',').map(&:strip).reverse.join(" ")
end
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("cn", name))
(entries.count == 1) ? entries.first : nil
end
# Wrapper around Net::LDAP#search, converts Net::LDAP::Entry objects to
# Cul::LDAP::Entry objects.
private
def build_config(options)
config = CONFIG_DEFAULTS.merge(options)
credentials = config.fetch(:auth, nil)
credentials = nil if !credentials.nil? && credentials.empty?
# If rails app fetch credentials using rails code, otherwise read from
# cul_ldap.yml if credentials are nil.
if credentials.nil?
credentials = rails_credentials || credentials_from_file
credentials = nil if !credentials.nil? && credentials.empty?
end
unless credentials.nil?
credentials = credentials.map { |k, v| [k.to_sym, v] }.to_h
credentials[:method] = :simple unless credentials.key?(:method)
end
config[:auth] = credentials
config
end
def credentials_from_file
(File.exist?(CONFIG_FILENAME)) ? YAML.load_file(CONFIG_FILENAME) : nil
end
def rails_credentials
if defined?(Rails.application.config_for) && File.exist?(File.join(Rails.root, 'config', CONFIG_FILENAME))
raise "Missing cul-ldap credentials in config/#{CONFIG_FILENAME}" if Rails.application.config_for(:cul_ldap).empty?
Rails.application.config_for(:cul_ldap)
else
nil
end
end
end
|
oleganza/btcruby | lib/btcruby/extensions.rb | BTC.StringExtensions.to_wif | ruby | def to_wif(network: nil, public_key_compressed: nil)
BTC::WIF.new(private_key: self, network: network, public_key_compressed: public_key_compressed).to_s
end | Converts binary string as a private key to a WIF Base58 format. | train | https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/extensions.rb#L5-L7 | module StringExtensions
# Converts binary string as a private key to a WIF Base58 format.
# Decodes string in WIF format into a binary private key (32 bytes)
def from_wif
addr = BTC::WIF.new(string: self)
addr ? addr.private_key : nil
end
# Converts binary data into hex string
def to_hex
BTC.to_hex(self)
end
# Converts hex string into a binary data
def from_hex
BTC.from_hex(self)
end
# Various hash functions
def hash256
BTC.hash256(self)
end
def hash160
BTC.hash160(self)
end
def sha1
BTC.sha1(self)
end
def ripemd160
BTC.ripemd160(self)
end
def sha256
BTC.sha256(self)
end
def sha512
BTC.sha512(self)
end
end
|
hoanganhhanoi/dhcp_parser | lib/dhcp_parser.rb | DHCPParser.Conf.pools | ruby | def pools
pool = []
index = 0
while index < @datas.count
index += 1
data = DHCPParser::Conf.get_pool(@datas["net#{index}"])
i = 0
tmp_hash = {}
while i < data["hosts"].count
i += 1
tmp_hash["#{i}"] = data["hosts"]["host#{i}"]
end
pool << tmp_hash
end
return pool
end | Get pool | train | https://github.com/hoanganhhanoi/dhcp_parser/blob/baa59aab7b519117c162d323104fb6e56d7fd4fc/lib/dhcp_parser.rb#L298-L313 | class Conf
attr_accessor :datas
# Function constructor of DHCP
def initialize(path)
@datas = DHCPParser::Conf.read_file(path)
@array_net = []
end
# Read file config return Net. Net is hash
def self.read_file(path)
str = ""
count = 0
counter = 0
object = Hash.new
begin
if path.nil? || path.empty?
path = "#{Gem.default_path[1]}/gems/dhcp_parser-#{DhcpParser::VERSION}/examples/default_dhcp.conf"
# path = "../examples/default_dhcp.conf"
end
file = File.new("#{path}", "r")
while (line = file.gets)
if !line.eql?("\n") && !line.eql?("")
element = line.strip.split
if !element.include?("#")
# Set new net
if counter == 0
count += 1
checkoption = false
checkhost = false
checkpool = true
checksub = true
object["net#{count}"] = { "subnet" => "",
"option" => "",
"pool" => ""
}
end
# Filter subnet
last = line.strip.slice(-1,1)
checkoption = true if !checksub
checkhost = true if !checkpool
checkpool = true if
if last.eql?("{")
counter -= 1
if counter == -1
object["net#{count}"]["subnet"] = line.gsub("\{\n","")
checksub = false
end
if counter == -2
checkpool = false
end
elsif last.eql?("}")
counter += 1
end
# Get data
if counter == -1 && checkoption
object["net#{count}"]["option"] = object["net#{count}"]["option"] + "#{line}"
elsif checkhost
object["net#{count}"]["pool"] = object["net#{count}"]["pool"] + "#{line}"
end
end
end
end
file.close
rescue => err
puts "Exception: #{err}"
err
end
return object
end
# Get subnet and netmask
def self.get_sub_mask(subnet)
if subnet.nil?
return false
else
array = subnet["subnet"].split
address = { "#{array[0]}" => array[1],
"#{array[2]}" => array[3] }
end
end
def self.get_subnet(subnet)
if subnet.nil?
return false
else
array = subnet["subnet"].split
address = array[1]
end
end
def self.get_netmask(subnet)
if subnet.nil?
return false
else
array = subnet["subnet"].split
address = array[3]
end
end
def self.get_authoritative(subnet)
if subnet.nil?
return false
else
authori = DHCPParser::Conf.get_list_option(subnet)
if !authori["authoritative"].nil?
return true
else
return false
end
end
end
# Get all config option of subnet
def self.get_list_option(subnet, condition = false)
if subnet.nil?
return false
else
option = {}
differ = {}
i = 0
line_number = subnet["option"].lines.count
if !condition
while i < line_number do
if !subnet["option"].lines[i].strip.eql?("")
substring = subnet["option"].lines[i].gsub("\;","")
array = substring.split
if array.include?("option")
option["#{array[1]}"] = "#{array[2]}"
elsif array.include?("authoritative")
option["#{array[0]}"] = true
else
option["#{array[0]}"] = "#{array[1]}"
end
end
i += 1
end
# Delete trash element
option.delete("}")
return option
else
while i < line_number do
if !subnet["option"].lines[i].strip.eql?("")
substring = subnet["option"].lines[i].gsub("\;","")
array = substring.split
if array.include?("option")
option["#{array[1]}"] = "#{array[2]}"
elsif array.include?("authoritative")
differ["#{array[0]}"] = true
else
differ["#{array[0]}"] = "#{array[1]}"
end
end
i += 1
end
# Delete trash element
differ.delete("}")
return [option, differ]
end
end
end
# Get host. Host is Hash
def self.get_pool(subnet)
if subnet.nil?
return false
else
pool = { "hosts" => {} }
count = 0
counter = 0
check_first = true
checkhost = true
i = 0
line_number = subnet["pool"].lines.count
lines = subnet["pool"].lines
while i < line_number do
if !lines[i].eql?("\n")
line = lines[i].gsub("\n","")
# valid block
last = line.strip.slice(-1,1)
if last.eql?("{")
check_first = false
count += 1
counter -= 1
pool["hosts"]["host#{count}"] = {}
if counter == -1
item = line.split
pool["hosts"]["host#{count}"]["#{item[0]}"] = item [1]
checkhost = false
end
elsif last.eql?("}")
counter += 1
end
# Create new host
if counter == 0 && !line.eql?("}")
if check_first
substring = line.gsub("\;","")
item = substring.split
if item.include?("range")
pool["#{item[0]}"] = { "min" => item[1], "max" => item[2] }
else
pool["#{item[0]}"] = item[1]
end
end
end
# Get data
if !checkhost
substring = line.gsub("\;","")
item = substring.split
if item.include?("hardware")
pool["hosts"]["host#{count}"]["#{item[0]}_#{item[1]}"] = item[2]
else
pool["hosts"]["host#{count}"]["#{item[0]}"] = item[1]
end
end
end
i += 1
end
# Delete trash element
[*1..count].each do |i|
pool["hosts"]["host#{i}"].tap {|key|
key.delete("}")
}
end
return pool
end
end
# Get list subnet
def subnets
subnet = []
index = 0
while index < @datas.count
index += 1
subnet << DHCPParser::Conf.get_subnet(@datas["net#{index}"])
end
return subnet
end
# Get list netmask
def netmasks
netmask = []
index = 0
while index < @datas.count
index += 1
netmask << DHCPParser::Conf.get_netmask(@datas["net#{index}"])
end
return netmask
end
# Get list option
def options
option = []
index = 0
while index < @datas.count
index += 1
option << DHCPParser::Conf.get_list_option(@datas["net#{index}"])
end
return option
end
# Get value authoritative
def authoritative
authori = []
index = 0
while index < @datas.count
index += 1
authori << DHCPParser::Conf.get_authoritative(@datas["net#{index}"])
end
return authori
end
# Get pool
# Get range
def ranges
range = []
index = 0
while index < @datas.count
index += 1
data = DHCPParser::Conf.get_pool(@datas["net#{index}"])
range << "#{data["range"]["min"]} #{data["range"]["max"]}"
end
return range
end
# Get allow
def allow
allow = []
index = 0
while index < @datas.count
index += 1
data = DHCPParser::Conf.get_pool(@datas["net#{index}"])
if !data["allow"].nil?
allow << data["allow"]
end
end
return allow
end
# Get allow
def denny
denny = []
index = 0
while index < @datas.count
index += 1
data = DHCPParser::Conf.get_pool(@datas["net#{index}"])
if !data["denny"].nil?
denny << data["denny"]
end
end
return denny
end
# Return data in file
def data
@datas
end
# Set data in object
def net
i = 0
while i < @datas.count
i += 1
new_net = Net.new
new_net.subnet = DHCPParser::Conf.get_subnet(@datas["net#{i}"])
new_net.netmask = DHCPParser::Conf.get_netmask(@datas["net#{i}"])
list_option = DHCPParser::Conf.get_list_option(@datas["net#{i}"], true)
new_net.option = list_option[0]
new_net.differ = list_option[1]
pool = DHCPParser::Conf.get_pool(@datas["net#{i}"])
new_net.pool["range"] = pool["range"]
new_net.pool["allow"] = pool["allow"]
new_net.pool["denny"] = pool["denny"]
# set host
index = 0
while index < pool["hosts"].count
index += 1
host_name = pool["hosts"]["host#{index}"]["host"]
ethernet = pool["hosts"]["host#{index}"]["hardware_ethernet"]
address = pool["hosts"]["host#{index}"]["fixed-address"]
host = Host.new(host_name, ethernet, address)
new_net.pool["hosts"] << host
end
@array_net << new_net
end
return @array_net
end
# Write file
def write_file_conf(file_name, arr_net, condition)
if !arr_net.empty?
result = WriteConf.write_file_conf(file_name, arr_net, condition)
end
end
# Convert xml
def to_xml(arr_net)
xml = XMLConvert.to_xml(arr_net)
end
# Write file xml
def write_file_xml(file_name, xml_string)
result = XMLConvert.write_file_xml(file_name, xml_string)
end
end
|
senchalabs/jsduck | lib/jsduck/tag/type.rb | JsDuck::Tag.Type.parse_doc | ruby | def parse_doc(p, pos)
tag = p.standard_tag({:tagname => :type, :type => true, :optional => true})
tag[:type] = curlyless_type(p) unless tag[:type]
tag
end | matches @type {type} or @type type
The presence of @type implies that we are dealing with property.
ext-doc allows type name to be either inside curly braces or
without them at all. | train | https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/tag/type.rb#L19-L23 | class Type < Tag
def initialize
@pattern = "type"
@tagname = :type
# We don't really care about the position as we don't output any
# HTML. We just need to set this up to do the formatting.
@html_position = POS_DOC
end
# matches @type {type} or @type type
#
# The presence of @type implies that we are dealing with property.
# ext-doc allows type name to be either inside curly braces or
# without them at all.
def curlyless_type(p)
p.match(/\S+/)
end
def process_doc(h, tags, pos)
h[:type] = tags[0][:type] unless h[:type]
end
def format(m, formatter)
m[:html_type] = formatter.format_type(m[:type])
end
end
|
sds/haml-lint | lib/haml_lint/linter.rb | HamlLint.Linter.next_node | ruby | def next_node(node)
return unless node
siblings = node.parent ? node.parent.children : [node]
next_sibling = siblings[siblings.index(node) + 1] if siblings.count > 1
return next_sibling if next_sibling
next_node(node.parent)
end | Gets the next node following this node, ascending up the ancestor chain
recursively if this node has no siblings.
@param node [HamlLint::Tree::Node]
@return [HamlLint::Tree::Node,nil] | train | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter.rb#L153-L161 | class Linter
include HamlVisitor
# List of lints reported by this linter.
#
# @todo Remove once spec/support/shared_linter_context returns an array of
# lints for the subject instead of the linter itself.
attr_reader :lints
# Initializes a linter with the specified configuration.
#
# @param config [Hash] configuration for this linter
def initialize(config)
@config = config
@lints = []
end
# Runs the linter against the given Haml document.
#
# @param document [HamlLint::Document]
def run(document)
@document = document
@lints = []
visit(document.tree)
@lints
rescue Parser::SyntaxError => e
location = e.diagnostic.location
@lints <<
HamlLint::Lint.new(
HamlLint::Linter::Syntax.new(config),
document.file,
location.line,
e.to_s,
:error
)
end
# Returns the simple name for this linter.
#
# @return [String]
def name
self.class.name.to_s.split('::').last
end
private
attr_reader :config, :document
# Record a lint for reporting back to the user.
#
# @param node [#line] node to extract the line number from
# @param message [String] error/warning to display to the user
def record_lint(node, message)
@lints << HamlLint::Lint.new(self, @document.file, node.line, message,
config.fetch('severity', :warning).to_sym)
end
# Parse Ruby code into an abstract syntax tree.
#
# @return [AST::Node]
def parse_ruby(source)
@ruby_parser ||= HamlLint::RubyParser.new
@ruby_parser.parse(source)
end
# Remove the surrounding double quotes from a string, ignoring any
# leading/trailing whitespace.
#
# @param string [String]
# @return [String] stripped with leading/trailing double quotes removed.
def strip_surrounding_quotes(string)
string[/\A\s*"(.*)"\s*\z/, 1]
end
# Returns whether a string contains any interpolation.
#
# @param string [String]
# @return [true,false]
def contains_interpolation?(string)
return false unless string
Haml::Util.contains_interpolation?(string)
end
# Returns whether this tag node has inline script, e.g. is of the form
# %tag= ...
#
# @param tag_node [HamlLint::Tree::TagNode]
# @return [true,false]
def tag_has_inline_script?(tag_node)
tag_with_inline_content = tag_with_inline_text(tag_node)
return false unless inline_content = inline_node_content(tag_node)
return false unless index = tag_with_inline_content.rindex(inline_content)
index -= 1
index -= 1 while [' ', '"', "'"].include?(tag_with_inline_content[index])
tag_with_inline_content[index] == '='
end
# Returns whether the inline content for a node is a string.
#
# For example, the following node has a literal string:
#
# %tag= "A literal #{string}"
#
# whereas this one does not:
#
# %tag A literal #{string}
#
# @param node [HamlLint::Tree::Node]
# @return [true,false]
def inline_content_is_string?(node)
tag_with_inline_content = tag_with_inline_text(node)
inline_content = inline_node_content(node)
index = tag_with_inline_content.rindex(inline_content) - 1
%w[' "].include?(tag_with_inline_content[index])
end
# Get the inline content for this node.
#
# Inline content is the content that appears inline right after the
# tag/script. For example, in the code below...
#
# %tag Some inline content
#
# ..."Some inline content" would be the inline content.
#
# @param node [HamlLint::Tree::Node]
# @return [String]
def inline_node_content(node)
inline_content = node.script
if contains_interpolation?(inline_content)
strip_surrounding_quotes(inline_content)
else
inline_content
end
end
# Gets the next node following this node, ascending up the ancestor chain
# recursively if this node has no siblings.
#
# @param node [HamlLint::Tree::Node]
# @return [HamlLint::Tree::Node,nil]
# Returns the line of the "following node" (child of this node or sibling or
# the last line in the file).
#
# @param node [HamlLint::Tree::Node]
def following_node_line(node)
[
[node.children.first, next_node(node)].compact.map(&:line),
@document.source_lines.count + 1,
].flatten.min
end
# Extracts all text for a tag node and normalizes it, including additional
# lines following commas or multiline bar indicators ('|')
#
# @param tag_node [HamlLine::Tree::TagNode]
# @return [String] source code of original parse node
def tag_with_inline_text(tag_node)
# Normalize each of the lines to ignore the multiline bar (|) and
# excess whitespace
@document.source_lines[(tag_node.line - 1)...(following_node_line(tag_node) - 1)]
.map do |line|
line.strip.gsub(/\|\z/, '').rstrip
end.join(' ')
end
end
|
huacnlee/rucaptcha | lib/rucaptcha/controller_helpers.rb | RuCaptcha.ControllerHelpers.generate_rucaptcha | ruby | def generate_rucaptcha
res = RuCaptcha.generate()
session_val = {
code: res[0],
time: Time.now.to_i
}
RuCaptcha.cache.write(rucaptcha_sesion_key_key, session_val, expires_in: RuCaptcha.config.expires_in)
res[1]
end | Generate a new Captcha | train | https://github.com/huacnlee/rucaptcha/blob/b7074ed9fd84e9768e91b39555ea037ffd327032/lib/rucaptcha/controller_helpers.rb#L17-L25 | module ControllerHelpers
extend ActiveSupport::Concern
included do
helper_method :verify_rucaptcha?
end
# session key of rucaptcha
def rucaptcha_sesion_key_key
session_id = session.respond_to?(:id) ? session.id : session[:session_id]
warning_when_session_invalid if session_id.blank?
['rucaptcha-session', session_id].join(':')
end
# Generate a new Captcha
# Verify captcha code
#
# params:
# resource - [optional] a ActiveModel object, if given will add validation error message to object.
# :keep_session - if true, RuCaptcha will not delete the captcha code session.
# :captcha - if given, the value of it will be used to verify the captcha,
# if do not give or blank, the value of params[:_rucaptcha] will be used to verify the captcha
#
# exmaples:
#
# verify_rucaptcha?
# verify_rucaptcha?(user, keep_session: true)
# verify_rucaptcha?(nil, keep_session: true)
# verify_rucaptcha?(nil, captcha: params[:user][:captcha])
#
def verify_rucaptcha?(resource = nil, opts = {})
opts ||= {}
store_info = RuCaptcha.cache.read(rucaptcha_sesion_key_key)
# make sure move used key
RuCaptcha.cache.delete(rucaptcha_sesion_key_key) unless opts[:keep_session]
# Make sure session exist
if store_info.blank?
return add_rucaptcha_validation_error
end
# Make sure not expire
if (Time.now.to_i - store_info[:time]) > RuCaptcha.config.expires_in
return add_rucaptcha_validation_error
end
# Make sure parama have captcha
captcha = (opts[:captcha] || params[:_rucaptcha] || '').downcase.strip
if captcha.blank?
return add_rucaptcha_validation_error
end
if captcha != store_info[:code]
return add_rucaptcha_validation_error
end
true
end
private
def add_rucaptcha_validation_error
if defined?(resource) && resource && resource.respond_to?(:errors)
resource.errors.add(:base, t('rucaptcha.invalid'))
end
false
end
def warning_when_session_invalid
Rails.logger.warn "
WARNING! The session.id is blank, RuCaptcha can't work properly, please keep session available.
More details about this: https://github.com/huacnlee/rucaptcha/pull/66
"
end
end
|
mailgun/mailgun-ruby | lib/mailgun/messages/batch_message.rb | Mailgun.BatchMessage.add_recipient | ruby | def add_recipient(recipient_type, address, variables = nil)
# send the message when we have 1000, not before
send_message if @counters[:recipients][recipient_type] == Mailgun::Chains::MAX_RECIPIENTS
compiled_address = parse_address(address, variables)
set_multi_complex(recipient_type, compiled_address)
store_recipient_variables(recipient_type, address, variables) if recipient_type != :from
@counters[:recipients][recipient_type] += 1 if @counters[:recipients].key?(recipient_type)
end | Public: Creates a new BatchMessage object.
Adds a specific type of recipient to the batch message object.
@param [String] recipient_type The type of recipient. "to".
@param [String] address The email address of the recipient to add to the message object.
@param [Hash] variables A hash of the variables associated with the recipient. We recommend "first" and "last" at a minimum!
@return [void] | train | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/batch_message.rb#L46-L56 | class BatchMessage < MessageBuilder
attr_reader :message_ids, :domain, :recipient_variables
# Public: Creates a new BatchMessage object.
def initialize(client, domain)
@client = client
@recipient_variables = {}
@domain = domain
@message_ids = {}
@message = Hash.new { |hash, key| hash[key] = [] }
@counters = {
recipients: { to: 0, cc: 0, bcc: 0 },
attributes: { attachment: 0, campaign_id: 0, custom_option: 0, tag: 0 }
}
end
# Adds a specific type of recipient to the batch message object.
#
# @param [String] recipient_type The type of recipient. "to".
# @param [String] address The email address of the recipient to add to the message object.
# @param [Hash] variables A hash of the variables associated with the recipient. We recommend "first" and "last" at a minimum!
# @return [void]
# Always call this function after adding recipients. If less than 1000 are added,
# this function will ensure the batch is sent.
#
# @return [Hash] A hash of {'Message ID' => '# of Messages Sent'}
def finalize
send_message if any_recipients_left?
@message_ids
end
private
# This method determines if it's necessary to send another batch.
#
# @return [Boolean]
def any_recipients_left?
return true if @counters[:recipients][:to] > 0
return true if @counters[:recipients][:cc] > 0
return true if @counters[:recipients][:bcc] > 0
false
end
# This method initiates a batch send to the API. It formats the recipient
# variables, posts to the API, gathers the message IDs, then flushes that data
# to prepare for the next batch. This method implements the Mailgun Client, thus,
# an exception will be thrown if a communication error occurs.
#
# @return [Boolean]
def send_message
rkey = 'recipient-variables'
set_multi_simple rkey, JSON.generate(@recipient_variables)
@message[rkey] = @message[rkey].first if @message.key?(rkey)
response = @client.send_message(@domain, @message).to_h!
message_id = response['id'].gsub(/\>|\</, '')
@message_ids[message_id] = count_recipients
reset_message
end
# This method stores recipient variables for each recipient added, if
# variables exist.
def store_recipient_variables(recipient_type, address, variables)
variables = { id: @counters[:recipients][recipient_type] } unless variables
@recipient_variables[address] = variables
end
# This method stores recipient variables for each recipient added, if
# variables exist.
def count_recipients
count = 0
@counters[:recipients].each_value { |cnt| count += cnt }
count
end
# This method resets the message object to prepare for the next batch
# of recipients.
def reset_message
@message.delete('recipient-variables')
@message.delete(:to)
@message.delete(:cc)
@message.delete(:bcc)
@counters[:recipients][:to] = 0
@counters[:recipients][:cc] = 0
@counters[:recipients][:bcc] = 0
end
end
|
litaio/lita | lib/lita/configuration_builder.rb | Lita.ConfigurationBuilder.build_nested | ruby | def build_nested(object)
this = self
nested_object = Configuration.new
children.each { |child| child.build(nested_object) }
object.instance_exec { define_singleton_method(this.name) { nested_object } }
object
end | Finalize the root builder or any builder with children. | train | https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_builder.rb#L198-L206 | class ConfigurationBuilder
# An array of any nested configuration builders.
# @return [Array<ConfigurationBuilder>] The array of child configuration builders.
# @api private
attr_reader :children
# An array of valid types for the attribute.
# @return [Array<Object>] The array of valid types.
# @api private
attr_reader :types
# A block used to validate the attribute.
# @return [Proc] The validation block.
# @api private
attr_reader :validator
# The name of the configuration attribute.
# @return [String, Symbol] The attribute's name.
# @api private
attr_accessor :name
# The value of the configuration attribute.
# @return [Object] The attribute's value.
# @api private
attr_reader :value
# A boolean indicating whether or not the attribute must be set.
# @return [Boolean] Whether or not the attribute is required.
# @api private
attr_accessor :required
alias required? required
class << self
# Deeply freezes a configuration object so that it can no longer be modified.
# @param config [Configuration] The configuration object to freeze.
# @return [void]
# @api private
def freeze_config(config)
IceNine.deep_freeze!(config)
end
# Loads configuration from a user configuration file.
# @param config_path [String] The path to the configuration file.
# @return [void]
# @api private
def load_user_config(config_path = nil)
config_path ||= "lita_config.rb"
if File.exist?(config_path)
begin
load(config_path)
rescue ValidationError
abort
rescue Exception => e
Lita.logger.fatal I18n.t(
"lita.config.exception",
message: e.message,
backtrace: e.backtrace.join("\n")
)
abort
end
end
end
end
def initialize
@children = []
@name = :root
end
# Builds a {Configuration} object from the attributes defined on the builder.
# @param object [Configuration] The empty configuration object that will be extended to
# create the final form.
# @return [Configuration] The fully built configuration object.
# @api private
def build(object = Configuration.new)
container = if children.empty?
build_leaf(object)
else
build_nested(object)
end
container.public_send(name)
end
# Returns a boolean indicating whether or not the attribute has any child attributes.
# @return [Boolean] Whether or not the attribute has any child attributes.
# @api private
def children?
!children.empty?
end
# Merges two configuration builders by making one an attribute on the other.
# @param name [String, Symbol] The name of the new attribute.
# @param attribute [ConfigurationBuilder] The configuration builder that should be its
# value.
# @return [void]
# @api private
def combine(name, attribute)
attribute.name = name
children << attribute
end
# Declares a configuration attribute.
# @param name [String, Symbol] The attribute's name.
# @param types [Object, Array<Object>] Optional: One or more types that the attribute's value
# must be.
# @param type [Object, Array<Object>] Optional: One or more types that the attribute's value
# must be.
# @param required [Boolean] Whether or not this attribute must be set. If required, and Lita
# is run without it set, Lita will abort on start up with a message about it.
# @param default [Object] An optional default value for the attribute.
# @yield A block to be evaluated in the context of the new attribute. Used for
# defining nested configuration attributes and validators.
# @return [void]
def config(name, types: nil, type: nil, required: false, default: nil, &block)
attribute = self.class.new
attribute.name = name
attribute.types = types || type
attribute.required = required
attribute.value = default
attribute.instance_exec(&block) if block
children << attribute
end
# Sets the valid types for the configuration attribute.
# @param types [Object, Array<Object>] One or more valid types.
# @return [void]
# @api private
def types=(types)
@types = Array(types) if types
end
# Declares a block to be used to validate the value of an attribute whenever it's set.
# Validation blocks should return any object to indicate an error, or +nil+/+false+ if
# validation passed.
# @yield The code that performs validation.
# @return [void]
def validate(&block)
validator = block
unless value.nil?
error = validator.call(value)
raise ValidationError, error if error
end
@validator = block
end
# Sets the value of the attribute, raising an error if it is not among the valid types.
# @param value [Object] The new value of the attribute.
# @return [void]
# @raise [TypeError] If the new value is not among the declared valid types.
# @api private
def value=(value)
ensure_valid_default_value(value)
@value = value
end
private
# Finalize a nested object.
def build_leaf(object)
this = self
run_validator = method(:run_validator)
check_types = method(:check_types)
object.instance_exec do
define_singleton_method(this.name) { this.value }
define_singleton_method("#{this.name}=") do |value|
run_validator.call(value)
check_types.call(value)
this.value = value
end
end
object
end
# Finalize the root builder or any builder with children.
# Check's the value's type from inside the finalized object.
def check_types(value)
if types&.none? { |type| type === value }
Lita.logger.fatal(
I18n.t("lita.config.type_error", attribute: name, types: types.join(", "))
)
raise ValidationError
end
end
# Raise if value is non-nil and isn't one of the specified types.
def ensure_valid_default_value(value)
if !value.nil? && types && types.none? { |type| type === value }
raise TypeError, I18n.t("lita.config.type_error", attribute: name, types: types.join(", "))
end
end
# Runs the validator from inside the build configuration object.
def run_validator(value)
return unless validator
error = validator.call(value)
if error
Lita.logger.fatal(
I18n.t("lita.config.validation_error", attribute: name, message: error)
)
raise ValidationError
end
end
end
|
seamusabshere/weighted_average | lib/weighted_average/arel_select_manager_instance_methods.rb | WeightedAverage.ArelSelectManagerInstanceMethods.weighted_average_relation | ruby | def weighted_average_relation(data_column_names, options = {})
unless options[:safe] == true
return clone.weighted_average_relation(data_column_names, options.merge(:safe => true))
end
data_column_names = Array.wrap data_column_names
left = self.source.left
weighted_by_column = case options[:weighted_by]
when Arel::Attribute
options[:weighted_by]
when Symbol, String
left[options[:weighted_by]]
when NilClass
left[DEFAULT_WEIGHTED_BY_COLUMN_NAME]
else
raise ArgumentError, ":weighted_by => #{options[:weighted_by].inspect} must be a column on #{left.inspect}"
end
disaggregate_by_column = if options[:disaggregate_by]
left[options[:disaggregate_by]]
end
data_columns = data_column_names.map do |data_column_name|
left[data_column_name]
end
data_columns_added_together = data_columns.inject(nil) do |memo, data_column|
if memo
Arel::Nodes::Addition.new(memo, data_column)
else
data_column
end
end
if data_column_names.many?
data_columns_added_together = Arel::Nodes::Grouping.new(data_columns_added_together)
end
if disaggregate_by_column
self.projections = [Arel::Nodes::Division.new(Arel::Nodes::Sum.new(weighted_by_column * data_columns_added_together / disaggregate_by_column * 1.0), Arel::Nodes::Sum.new([weighted_by_column]))]
else
self.projections = [Arel::Nodes::Division.new(Arel::Nodes::Sum.new(weighted_by_column * data_columns_added_together * 1.0), Arel::Nodes::Sum.new([weighted_by_column]))]
end
data_columns_not_eq_nil = data_columns.inject(nil) do |memo, data_column|
if memo
memo.and(data_column.not_eq(nil))
else
data_column.not_eq(nil)
end
end
if disaggregate_by_column
where data_columns_not_eq_nil.and(weighted_by_column.gt(0)).and(disaggregate_by_column.gt(0))
else
where data_columns_not_eq_nil.and(weighted_by_column.gt(0))
end
end | In case you want to get the relation and/or the SQL of the calculation query before actually runnnig it.
@example Get the SQL
Arel::Table.new(:flight_segments).weighted_average_relation(:load_factor, :weighted_by => :passengers).to_sql
@return [Arel::SelectManager] A relation you can play around with. | train | https://github.com/seamusabshere/weighted_average/blob/42f3d62d321b062353510778d4c151bdf7411b90/lib/weighted_average/arel_select_manager_instance_methods.rb#L28-L86 | module ArelSelectManagerInstanceMethods
# Calculate the weighted average of column(s).
#
# @param [Symbol,Array<Symbol>] data_column_names One or more column names whose average should be calculated. Added together before being multiplied by the weighting if more than one.
# @param [Hash] options
#
# @option options [Symbol] :weighted_by The name of the weighting column if it's not :weighting (the default)
# @option options [Symbol] :disaggregate_by The name of a column to disaggregate by. Usually not necessary.
#
# @see WeightedAverage::ActiveRecordRelationInstanceMethods The ActiveRecord-specific version of this method, which knows about associations.
#
# @example Weighted average of load factor in flight stage data
# Arel::Table.new(:flight_segments).weighted_average(:load_factor, :weighted_by => :passengers)
#
# @return [Float,nil]
def weighted_average(data_column_names, options = {})
weighted_average = @engine.connection.select_value(weighted_average_relation(data_column_names, options).to_sql)
weighted_average.nil? ? nil : weighted_average.to_f
end
# In case you want to get the relation and/or the SQL of the calculation query before actually runnnig it.
#
# @example Get the SQL
# Arel::Table.new(:flight_segments).weighted_average_relation(:load_factor, :weighted_by => :passengers).to_sql
#
# @return [Arel::SelectManager] A relation you can play around with.
end
|
gollum/gollum | lib/gollum/helpers.rb | Precious.Helpers.extract_path | ruby | def extract_path(file_path)
return nil if file_path.nil?
last_slash = file_path.rindex("/")
if last_slash
file_path[0, last_slash]
end
end | Extract the path string that Gollum::Wiki expects | train | https://github.com/gollum/gollum/blob/f44367c31baac5c154888a9e09b2833fa62e1c61/lib/gollum/helpers.rb#L10-L16 | module Helpers
EMOJI_PATHNAME = Pathname.new(Gemojione.images_path).freeze
# Extract the path string that Gollum::Wiki expects
# Extract the 'page' name from the file_path
def extract_name(file_path)
if file_path[-1, 1] == "/"
return nil
end
# File.basename is too eager to please and will return the last
# component of the path even if it ends with a directory separator.
::File.basename(file_path)
end
def sanitize_empty_params(param)
[nil, ''].include?(param) ? nil : CGI.unescape(param)
end
# Ensure path begins with a single leading slash
def clean_path(path)
if path
(path[0] != '/' ? path.insert(0, '/') : path).gsub(/\/{2,}/, '/')
end
end
# Remove all slashes from the start of string.
# Remove all double slashes
def clean_url url
return url if url.nil?
url.gsub('%2F', '/').gsub(/^\/+/, '').gsub('//', '/')
end
def forbid(msg = "Forbidden. This wiki is set to no-edit mode.")
@message = msg
status 403
halt mustache :error
end
def not_found(msg = nil)
@message = msg || "The requested page does not exist."
status 404
return mustache :error
end
def emoji(name)
if emoji = Gemojione.index.find_by_name(name)
IO.read(EMOJI_PATHNAME.join("#{emoji['unicode']}.png"))
else
fail ArgumentError, "emoji `#{name}' not found"
end
end
end
|
winston/google_visualr | lib/google_visualr/base_chart.rb | GoogleVisualr.BaseChart.to_js | ruby | def to_js(element_id)
js = ""
js << "\n<script type='text/javascript'>"
js << load_js(element_id)
js << draw_js(element_id)
js << "\n</script>"
js
end | Generates JavaScript and renders the Google Chart in the final HTML output.
Parameters:
*div_id [Required] The ID of the DIV element that the Google Chart should be rendered in. | train | https://github.com/winston/google_visualr/blob/17b97114a345baadd011e7b442b9a6c91a2b7ab5/lib/google_visualr/base_chart.rb#L63-L70 | class BaseChart
include GoogleVisualr::ParamHelpers
DEFAULT_VERSION = "1.0".freeze
attr_accessor :data_table, :listeners, :version, :language, :material
def initialize(data_table, options={})
@data_table = data_table
@listeners = []
@version = options.delete(:version) || DEFAULT_VERSION
@language = options.delete(:language)
@material = options.delete(:material) || false
send(:options=, options)
end
def package_name
self.class.to_s.split("::").last.downcase
end
def class_name
self.class.to_s.split("::").last
end
def chart_class
if material
"charts"
else
"visualization"
end
end
def chart_name
if material
class_name.gsub!("Chart", "")
else
class_name
end
end
def chart_function_name(element_id)
"draw_#{element_id.gsub('-', '_')}"
end
def options
@options
end
def options=(options)
@options = stringify_keys!(options)
end
def add_listener(event, callback)
@listeners << { :event => event.to_s, :callback => callback }
end
# Generates JavaScript and renders the Google Chart in the final HTML output.
#
# Parameters:
# *div_id [Required] The ID of the DIV element that the Google Chart should be rendered in.
# Generates JavaScript for loading the appropriate Google Visualization package, with callback to render chart.
#
# Parameters:
# *div_id [Required] The ID of the DIV element that the Google Chart should be rendered in.
def load_js(element_id)
language_opt = ", language: '#{language}'" if language
"\n google.load('visualization', '#{version}', {packages: ['#{package_name}']#{language_opt}, callback: #{chart_function_name(element_id)}});"
end
# Generates JavaScript function for rendering the chart.
#
# Parameters:
# *div_id [Required] The ID of the DIV element that the Google Chart should be rendered in.
def draw_js(element_id)
js = ""
js << "\n function #{chart_function_name(element_id)}() {"
js << "\n #{@data_table.to_js}"
js << "\n var chart = new google.#{chart_class}.#{chart_name}(document.getElementById('#{element_id}'));"
@listeners.each do |listener|
js << "\n google.visualization.events.addListener(chart, '#{listener[:event]}', #{listener[:callback]});"
end
js << "\n chart.draw(data_table, #{js_parameters(@options)});"
js << "\n };"
js
end
end
|
zhimin/rwebspec | lib/rwebspec-common/core.rb | RWebSpec.Core.process_each_row_in_csv_file | ruby | def process_each_row_in_csv_file(csv_file, &block)
require 'faster_csv'
connect_to_testwise("CSV_START", csv_file) if $testwise_support
has_error = false
idx = 0
FasterCSV.foreach(csv_file, :headers => :first_row, :encoding => 'u') do |row|
connect_to_testwise("CSV_ON_ROW", idx.to_s) if $testwise_support
begin
yield row
connect_to_testwise("CSV_ROW_PASS", idx.to_s) if $testwise_support
rescue => e
connect_to_testwise("CSV_ROW_FAIL", idx.to_s) if $testwise_support
has_error = true
ensure
idx += 1
end
end
connect_to_testwise("CSV_END", "") if $testwise_support
raise "Test failed on data" if has_error
end | Data Driven Tests
Processing each row in a CSV file, must have heading rows
Usage:
process_each_row_in_csv_file(@csv_file) { |row|
goto_page("/")
enter_text("username", row[1])
enter_text("password", row[2])
click_button("Sign in")
page_text.should contain(row[3])
failsafe{ click_link("Sign off") }
} | train | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/core.rb#L488-L508 | module Core
# open a browser, and set base_url via hash, but does not acually
#
# example:
# open_browser :base_url => http://localhost:8080, :browser => :ie
#
# There are 3 ways to set base url
# 1. pass as first argument
# 2. If running using TestWise, used as confiured
# 3. Use default value set
#
#
# New Options:
# :browser => :ie | :firefox | :chrome | :safari
def open_browser(opts = {})
puts "[INFO] RWebSpec.Framework currently set to => #{RWebSpec.framework }"
=begin
if RWebSpec.framework =~ /watir/i
RWebSpec.load_watir
self.class.send(:include, RWebSpec::Driver)
load(File.dirname(__FILE__) + "/web_page.rb")
return open_browser_by_watir(opts)
end
if RWebSpec.framework =~ /selenium/i
RWebSpec.load_selenium
self.class.send(:include, RWebSpec::Driver)
load(File.dirname(__FILE__) + "/web_page.rb")
return open_browser_by_selenium(opts)
end
=end
puts "[INFO] No underlying framework is set, try to determine browser: #{opts.inspect}"
if opts.class == Hash
if opts[:browser]
if opts[:browser].to_s =~ /ie/i || opts[:browser].to_s =~ /internet\sexplorer/i
puts "[INFO] based on browser, set to Watir"
RWebSpec.framework = "Watir"
self.class.send(:include, RWebSpec::Driver)
# Reload abstract web page to load driver
load(File.dirname(__FILE__) + "/web_page.rb")
return open_browser_by_watir(opts)
end
puts "[INFO] based on browser, set to Selenium"
# not IE, using selenium
RWebSpec.framework = "Selenium"
self.class.send(:include, RWebSpec::Driver)
load(File.dirname(__FILE__) + "/web_page.rb")
return open_browser_by_selenium(opts)
end
end
puts "[INFO] browser type not specified, decide framework based on platform"
if RUBY_PLATFORM =~ /mingw/
# if it is Windows, set to Watir
RWebSpec.framework = "Watir"
self.class.send(:include, RWebSpec::Driver)
puts "[INFO] Extends of RWebSpec::Driver"
load(File.dirname(__FILE__) + "/web_page.rb")
return open_browser_by_watir(opts)
else
RWebSpec.framework = "Selenium"
self.class.send(:include, RWebSpec::Driver)
load(File.dirname(__FILE__) + "/web_page.rb")
# using extend somehow does not work for RSpec
# extend RWebSpec::Driver
return open_browser_by_selenium(opts)
end
end
def use_current_browser(how = :title, what = /.*/)
puts "[INFO] user current browser => #{RWebSpec.framework}"
if RWebSpec.framework =~ /watir/i
self.class.send(:include, RWebSpec::Driver)
use_current_watir_browser(how, what)
elsif RWebSpec.framework =~ /selenium/i
self.class.send(:include, RWebSpec::Driver)
use_current_selenium_browser(how, what)
else
# not specified, guess
if RUBY_PLATFORM =~ /mingw/i
RWebSpec.framework = "Watir"
self.class.send(:include, RWebSpec::Driver)
load(File.dirname(__FILE__) + "/web_page.rb")
use_current_watir_browser(how, what)
else
RWebSpec.framework = "Selenium"
self.class.send(:include, RWebSpec::Driver)
load(File.dirname(__FILE__) + "/web_page.rb")
use_current_selenium_browser(how, what)
end
end
end
# Try the operation up to specified timeout (in seconds), and sleep given interval (in seconds).
# Error will be ignored until timeout
# Example
# try_for { click_link('waiting')}
# try_for(10, 2) { click_button('Search' } # try to click the 'Search' button upto 10 seconds, try every 2 seconds
# try_for { click_button('Search' }
def try_for(timeout = $testwise_polling_timeout, polling_interval = $testwise_polling_interval || 1, &block)
start_time = Time.now
last_error = nil
until (duration = Time.now - start_time) > timeout
begin
yield
last_error = nil
return true
rescue RWebSpec::Assertion => e1
last_error = e1
rescue ArgumentError => ae
last_error = ae
rescue RSpec::Expectations::ExpectationNotMetError => ree
last_error = ree
rescue => e
last_error = e
end
sleep polling_interval
end
raise "Timeout after #{duration.to_i} seconds with error: #{last_error}." if last_error
raise "Timeout after #{duration.to_i} seconds."
end
# Deprecated
# alias try_upto try_for
# alias try_up_to try_for
# alias try_until try_for
=begin
def try(timeout = $testwise_polling_timeout, polling_interval = $testwise_polling_interval || 1, &block)
puts "Warning: method 'try' is deprecated (won't support in RWebSpec 3), use try_for instead."
try_for(timeout, polling_interval) {
yield
}
end
=end
=begin
# Try the operation up to specified times, and sleep given interval (in seconds)
# Error will be ignored until timeout
# Example
# repeat_try(3, 2) { click_button('Search' } # 3 times, 6 seconds in total
# repeat_try { click_button('Search' } # using default 5 tries, 2 second interval
def repeat_try(num_tries = $testwise_polling_timeout || 30, interval = $testwise_polling_interval || 1, & block)
num_tries ||= 1
(num_tries - 1).times do |num|
begin
yield
return
rescue => e
# puts "debug: #{num} failed: #{e}"
sleep interval
end
end
# last try, throw error if still fails
begin
yield
rescue => e
raise e.to_s + " after trying #{num_tries} times every #{interval} seconds"
end
yield
end
=end
##
# Convert :first to 1, :second to 2, and so on...
def symbol_to_sequence(symb)
value = {:zero => 0,
:first => 1,
:second => 2,
:third => 3,
:fourth => 4,
:fifth => 5,
:sixth => 6,
:seventh => 7,
:eighth => 8,
:ninth => 9,
:tenth => 10}[symb]
return value || symb.to_i
end
#= Convenient functions
#
# Using Ruby block syntax to create interesting domain specific language,
# may be appeal to someone.
# Example:
# on @page do |i|
# i.enter_text('btn1')
# i.click_button('btn1')
# end
def on(page, & block)
yield page
end
# fail the test if user can perform the operation
#
# Example:
# shall_not_allow { 1/0 }
def shall_not_allow(& block)
operation_performed_ok = false
begin
yield
operation_performed_ok = true
rescue
end
raise "Operation shall not be allowed" if operation_performed_ok
end
alias do_not_allow shall_not_allow
# Does not provide real function, other than make enhancing test syntax
#
# Example:
# allow { click_button('Register') }
def allow(& block)
yield
end
alias shall_allow allow
alias allowing allow
# try operation, ignore if errors occur
#
# Example:
# failsafe { click_link("Logout") } # try logout, but it still OK if not being able to (already logout))
def failsafe(& block)
begin
yield
rescue RWebSpec::Assertion => e1
rescue ArgumentError => ae
rescue RSpec::Expectations::ExpectationNotMetError => ree
rescue =>e
end
end
alias fail_safe failsafe
# default date format returned is 29/12/2007.
# if supplied parameter is not '%m/%d/%Y' -> 12/29/2007
# Otherwise, "2007-12-29", which is most approiate date format
#
# %a - The abbreviated weekday name (``Sun'')
# %A - The full weekday name (``Sunday'')
# %b - The abbreviated month name (``Jan'')
# %B - The full month name (``January'')
# %c - The preferred local date and time representation
# %d - Day of the month (01..31)
# %H - Hour of the day, 24-hour clock (00..23)
# %I - Hour of the day, 12-hour clock (01..12)
# %j - Day of the year (001..366)
# %m - Month of the year (01..12)
# %M - Minute of the hour (00..59)
# %p - Meridian indicator (``AM'' or ``PM'')
# %S - Second of the minute (00..60)
# %U - Week number of the current year,
# starting with the first Sunday as the first
# day of the first week (00..53)
# %W - Week number of the current year,
# starting with the first Monday as the first
# day of the first week (00..53)
# %w - Day of the week (Sunday is 0, 0..6)
# %x - Preferred representation for the date alone, no time
# %X - Preferred representation for the time alone, no date
# %y - Year without a century (00..99)
# %Y - Year with century
# %Z - Time zone name
# %% - Literal ``%'' character
def today(format = nil)
format_date(Time.now, date_format(format))
end
alias getToday_AU today
alias getToday_US today
alias getToday today
def days_before(days, format = nil)
return nil if !(days.instance_of?(Fixnum))
format_date(Time.now - days * 24 * 3600, date_format(format))
end
def yesterday(format = nil)
days_before(1, date_format(format))
end
def days_from_now(days, format = nil)
return nil if !(days.instance_of?(Fixnum))
format_date(Time.now + days * 24 * 3600, date_format(format))
end
alias days_after days_from_now
def tomorrow(format = nil)
days_from_now(1, date_format(format))
end
# return a random number >= min, but <= max
def random_number(min, max)
rand(max-min+1)+min
end
def random_boolean
return random_number(0, 1) == 1
end
def random_char(lowercase = true)
if lowercase
sprintf("%c", random_number(97, 122))
else
sprintf("%c", random_number(65, 90))
end
end
def random_digit()
sprintf("%c", random_number(48, 57))
end
def random_str(length, lowercase = true)
randomStr = ""
length.times {
randomStr += random_char(lowercase)
}
randomStr
end
# Return a random string in a rangeof pre-defined strings
def random_string_in(arr)
return nil if arr.empty?
index = random_number(0, arr.length-1)
arr[index]
end
alias random_string_in_collection random_string_in
WORDS = %w(alias consequatur aut perferendis sit voluptatem accusantium doloremque aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem ut enim ad minima veniam quis nostrum exercitationem ullam corporis nemo enim ipsam voluptatem quia voluptas sit suscipit laboriosam nisi ut aliquid ex ea commodi consequatur quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae et iusto odio dignissimos ducimus qui blanditiis praesentium laudantium totam rem voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident sed ut perspiciatis unde omnis iste natus error similique sunt in culpa qui officia deserunt mollitia animi id est laborum et dolorum fuga et harum quidem rerum facilis est et expedita distinctio nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo porro quisquam est qui minus id quod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam et aut consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur at vero eos et accusamus officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae itaque earum rerum hic tenetur a sapiente delectus ut aut reiciendis voluptatibus maiores doloribus asperiores repellat)
# Pick a random value out of a given range.
def value_in_range(range)
case range.first
when Integer then number_in_range(range)
when Time then time_in_range(range)
when Date then date_in_range(range)
else range.to_a.rand
end
end
# Generate a given number of words. If a range is passed, it will generate
# a random number of words within that range.
def words(total)
if total.class == Range
(1..interpret_value(total)).map { WORDS[random_number(total.min, total.max)] }.join(' ')
else
(1..interpret_value(total)).map { WORDS[random_number(0, total)] }.join(' ')
end
end
# Generate a given number of sentences. If a range is passed, it will generate
# a random number of sentences within that range.
def sentences(total)
(1..interpret_value(total)).map do
words(5..20).capitalize
end.join('. ')
end
# Generate a given number of paragraphs. If a range is passed, it will generate
# a random number of paragraphs within that range.
def paragraphs(total)
(1..interpret_value(total)).map do
sentences(3..8).capitalize
end.join("\n\n")
end
# If an array or range is passed, a random value will be selected to match.
# All other values are simply returned.
def interpret_value(value)
case value
when Array then value.rand
when Range then value_in_range(value)
else value
end
end
private
def time_in_range(range)
Time.at number_in_range(Range.new(range.first.to_i, range.last.to_i, rangee.exclude_end?))
end
def date_in_range(range)
Date.jd number_in_range(Range.new(range.first.jd, range.last.jd, range.exclude_end?))
end
def number_in_range(range)
if range.exclude_end?
rand(range.last - range.first) + range.first
else
rand((range.last+1) - range.first) + range.first
end
end
def format_date(date, date_format = '%d/%m/%Y')
date.strftime(date_format)
end
def date_format(format_argument)
if format_argument.nil? then
get_locale_date_format(default_locale)
elsif format_argument.class == Symbol then
get_locale_date_format(format_argument)
elsif format_argument.class == String then
format_argument
else
# invalid input, use default
get_locale_date_format(default_date_format)
end
end
def get_locale_date_format(locale)
case locale
when :us
"%m/%d/%Y"
when :au, :uk
"%d/%m/%Y"
else
"%Y-%m-%d"
end
end
def default_locale
return :au
end
def average_of(array)
array.inject(0.0) { |sum, e| sum + e } / array.length
end
# NOTE might cause issues
# why it is removed total
def sum_of(array)
array.inject(0.0) { |sum, e| sum + e }
end
## Data Driven Tests
#
# Processing each row in a CSV file, must have heading rows
#
# Usage:
#
# process_each_row_in_csv_file(@csv_file) { |row|
# goto_page("/")
# enter_text("username", row[1])
# enter_text("password", row[2])
# click_button("Sign in")
# page_text.should contain(row[3])
# failsafe{ click_link("Sign off") }
# }
#
end
|
markdownlint/markdownlint | lib/mdl/doc.rb | MarkdownLint.Doc.find_type_elements | ruby | def find_type_elements(type, nested=true, elements=@elements)
results = []
if type.class == Symbol
type = [type]
end
elements.each do |e|
results.push(e) if type.include?(e.type)
if nested and not e.children.empty?
results.concat(find_type_elements(type, nested, e.children))
end
end
results
end | Find all elements of a given type, returning a list of the element
objects themselves.
Instead of a single type, a list of types can be provided instead to
find all types.
If +nested+ is set to false, this returns only top level elements of a
given type. | train | https://github.com/markdownlint/markdownlint/blob/a9e80fcf3989d73b654b00bb2225a00be53983e8/lib/mdl/doc.rb#L86-L98 | class Doc
##
# A list of raw markdown source lines. Note that the list is 0-indexed,
# while line numbers in the parsed source are 1-indexed, so you need to
# subtract 1 from a line number to get the correct line. The element_line*
# methods take care of this for you.
attr_reader :lines
##
# A Kramdown::Document object containing the parsed markdown document.
attr_reader :parsed
##
# A list of top level Kramdown::Element objects from the parsed document.
attr_reader :elements
##
# The line number offset which is greater than zero when the
# markdown file contains YAML front matter that should be ignored.
attr_reader :offset
##
# Create a new document given a string containing the markdown source
def initialize(text, ignore_front_matter = false)
regex = /^---\n(.*?)---\n/m
if ignore_front_matter and regex.match(text)
@offset = regex.match(text).to_s.split("\n").length
text.sub!(regex,'')
else
@offset = 0
end
@lines = text.split("\n")
@parsed = Kramdown::Document.new(text, :input => 'MarkdownLint')
@elements = @parsed.root.children
add_levels(@elements)
end
##
# Alternate 'constructor' passing in a filename
def self.new_from_file(filename, ignore_front_matter = false)
if filename == "-"
self.new(STDIN.read, ignore_front_matter)
else
self.new(File.read(filename, encoding: 'UTF-8'), ignore_front_matter)
end
end
##
# Find all elements of a given type, returning their options hash. The
# options hash has most of the useful data about an element and often you
# can just use this in your rules.
#
# # Returns [ { :location => 1, :element_level => 2 }, ... ]
# elements = find_type(:li)
#
# If +nested+ is set to false, this returns only top level elements of a
# given type.
def find_type(type, nested=true)
find_type_elements(type, nested).map { |e| e.options }
end
##
# Find all elements of a given type, returning a list of the element
# objects themselves.
#
# Instead of a single type, a list of types can be provided instead to
# find all types.
#
# If +nested+ is set to false, this returns only top level elements of a
# given type.
##
# A variation on find_type_elements that allows you to skip drilling down
# into children of specific element types.
#
# Instead of a single type, a list of types can be provided instead to
# find all types.
#
# Unlike find_type_elements, this method will always search for nested
# elements, and skip the element types given to nested_except.
def find_type_elements_except(type, nested_except=[], elements=@elements)
results = []
if type.class == Symbol
type = [type]
end
if nested_except.class == Symbol
nested_except = [nested_except]
end
elements.each do |e|
results.push(e) if type.include?(e.type)
unless nested_except.include?(e.type) or e.children.empty?
results.concat(find_type_elements_except(type, nested_except, e.children))
end
end
results
end
##
# Returns the line number a given element is located on in the source
# file. You can pass in either an element object or an options hash here.
def element_linenumber(element)
element = element.options if element.is_a?(Kramdown::Element)
element[:location]
end
##
# Returns the actual source line for a given element. You can pass in an
# element object or an options hash here. This is useful if you need to
# examine the source line directly for your rule to make use of
# information that isn't present in the parsed document.
def element_line(element)
@lines[element_linenumber(element) - 1]
end
##
# Returns a list of line numbers for all elements passed in. You can pass
# in a list of element objects or a list of options hashes here.
def element_linenumbers(elements)
elements.map { |e| element_linenumber(e) }
end
##
# Returns the actual source lines for a list of elements. You can pass in
# a list of elements objects or a list of options hashes here.
def element_lines(elements)
elements.map { |e| element_line(e) }
end
##
# Returns the header 'style' - :atx (hashes at the beginning), :atx_closed
# (atx header style, but with hashes at the end of the line also), :setext
# (underlined). You can pass in the element object or an options hash
# here.
def header_style(header)
if header.type != :header
raise "header_style called with non-header element"
end
line = element_line(header)
if line.start_with?("#")
if line.strip.end_with?("#")
:atx_closed
else
:atx
end
else
:setext
end
end
##
# Returns the list style for a list: :asterisk, :plus, :dash, :ordered or
# :ordered_paren depending on which symbol is used to denote the list
# item. You can pass in either the element itself or an options hash here.
def list_style(item)
if item.type != :li
raise "list_style called with non-list element"
end
line = element_line(item).strip
if line.start_with?('*')
:asterisk
elsif line.start_with?('+')
:plus
elsif line.start_with?('-')
:dash
elsif line.match('[0-9]+\.')
:ordered
elsif line.match('[0-9]+\)')
:ordered_paren
else
:unknown
end
end
##
# Returns how much a given line is indented. Hard tabs are treated as an
# indent of 8 spaces. You need to pass in the raw string here.
def indent_for(line)
return line.match(/^\s*/)[0].gsub("\t", " " * 8).length
end
##
# Returns line numbers for lines that match the given regular expression
def matching_lines(re)
@lines.each_with_index.select{|text, linenum| re.match(text)}.map{
|i| i[1]+1}
end
##
# Returns line numbers for lines that match the given regular expression.
# Only considers text inside of 'text' elements (i.e. regular markdown
# text and not code/links or other elements).
def matching_text_element_lines(re, exclude_nested=[:a])
matches = []
find_type_elements_except(:text, exclude_nested).each do |e|
first_line = e.options[:location]
# We'll error out if kramdown doesn't have location information for
# the current element. It's better to just not match in these cases
# rather than crash.
next if first_line.nil?
lines = e.value.split("\n")
lines.each_with_index do |l, i|
matches << first_line + i if re.match(l)
end
end
matches
end
##
# Extracts the text from an element whose children consist of text
# elements and other things
def extract_text(element, prefix="", restore_whitespace = true)
quotes = {
:rdquo => '"',
:ldquo => '"',
:lsquo => "'",
:rsquo => "'"
}
# If anything goes amiss here, e.g. unknown type, then nil will be
# returned and we'll just not catch that part of the text, which seems
# like a sensible failure mode.
lines = element.children.map { |e|
if e.type == :text
e.value
elsif [:strong, :em, :p, :codespan].include?(e.type)
extract_text(e, prefix, restore_whitespace).join("\n")
elsif e.type == :smart_quote
quotes[e.value]
end
}.join.split("\n")
# Text blocks have whitespace stripped, so we need to add it back in at
# the beginning. Because this might be in something like a blockquote,
# we optionally strip off a prefix given to the function.
if restore_whitespace
lines[0] = element_line(element).sub(prefix, "")
end
lines
end
private
##
# Adds a 'level' option to all elements to show how nested they are
def add_levels(elements, level=1)
elements.each do |e|
e.options[:element_level] = level
add_levels(e.children, level+1)
end
end
end
|
schasse/mandrill_batch_mailer | lib/mandrill_batch_mailer/base_mailer.rb | MandrillBatchMailer.BaseMailer.mandrill_parameters | ruby | def mandrill_parameters
{
key: MandrillBatchMailer.api_key,
template_name: template_name,
template_content: [],
message: {
subject: subject,
from_email: from_email,
from_name: from_name,
to: to,
important: false,
track_opens: nil,
track_clicks: nil,
inline_css: true,
url_strip_qs: nil,
preserve_recipients: false,
view_content_link: nil,
tracking_domain: nil,
signing_domain: nil,
return_path_domain: nil,
merge: true,
global_merge_vars: global_merge_vars,
merge_vars: merge_vars,
tags: tags
},
async: true
}.deep_merge(_default)
end | rubocop:disable MethodLength | train | https://github.com/schasse/mandrill_batch_mailer/blob/6f8902b2ee3cc6e4758c57c1ef061e86db369972/lib/mandrill_batch_mailer/base_mailer.rb#L59-L86 | class BaseMailer
private
attr_accessor :caller_method_name
public
def initialize(method)
self.caller_method_name = method
end
def mail(to: nil)
@tos = tos_from(to)
send_template mandrill_parameters
end
# feel free to override
def from_email
MandrillBatchMailer.from_email
end
# feel free to override
def from_name
MandrillBatchMailer.from_name || ''
end
# feel free to override
def tags
["#{template_name}"]
end
class << self
# do it just as ActionMailer
def method_missing(method, *args)
mailer = new method
if mailer.respond_to? method
mailer.public_send(method, *args)
else
super method, *args
end
end
end
protected
def scope
"#{class_name.underscore.gsub('/', '.')}.#{caller_method_name}"
end
private
# rubocop:disable MethodLength
# rubocop:enable MethodLength
def _default
given_defaults = (respond_to?(:default, true) && default) || {}
if MandrillBatchMailer.intercept_recipients
given_defaults[:message].try(:delete, :to)
end
given_defaults
end
def template_name
"#{class_name.underscore}_#{caller_method_name}".split('/').last
.gsub '_', '-'
end
def subject
'*|subject|*'
end
def to
if MandrillBatchMailer.intercept_recipients
@tos.keys.size.times.map do |i|
{ email: MandrillBatchMailer
.interception_base_mail.sub('@', "+#{i}@") }
end
else
@tos.keys.map { |to_email| { email: to_email } }
end
end
def global_merge_vars
merge_vars_from(translations.merge(shared_translations))
end
def merge_vars
@tos.each_with_index.map do |to, i|
to_email, vars = to.to_a
if MandrillBatchMailer.intercept_recipients
intercepted_merge_vars(to_email, vars, i)
else
{ rcpt: to_email, vars: merge_vars_from(vars) }
end
end
end
def intercepted_merge_vars(to_email, vars, i)
subject = vars[:subject] || translations[:subject]
{
rcpt: MandrillBatchMailer.interception_base_mail.sub('@', "+#{i}@"),
vars: merge_vars_from(vars.merge(subject: "#{to_email} #{subject}"))
}
end
## HELPER METHODS ##
# @return [Hash]
# p.e. { 'some@mail.ch' => { a_variable: 'Hello' } }
def tos_from(to)
case to
when String
{ to => {} }
when Array
to.map { |single_to| [single_to, {}] }.to_h
when Hash
to
else
to.to_h
end
end
def translations
if I18n.methods.include? :fallbacks
fallback_translations scope
else
I18n.t scope
end
end
def fallback_translations(scope)
I18n.fallbacks[I18n.locale].map do |fallback_locale|
I18n.t scope, locale: fallback_locale
end.reduce do |orig_translations, fallback_translations|
if fallback_translations.is_a? Hash
fallback_translations.deep_merge orig_translations
else
orig_translations
end
end
end
def class_name
self.class.to_s
end
def shared_translations
shared_scope =
"#{class_name.deconstantize.underscore}.shared_translations"
if I18n.methods.include? :fallbacks
fallback_translations shared_scope
else
I18n.t shared_scope
end
end
def merge_vars_from(translations)
translations.map do |key, translation|
{ name: key, content: translation }
end
end
def send_template(params)
if MandrillBatchMailer.perform_deliveries
rest_client_send params
params
else
log_sending(params)
params
end
end
def log_sending(params)
params_inspect =
if defined? AwesomePrint
params.ai
else
params.inspect
end
MandrillBatchMailer.logger
.info "Sending Mandrill Mail: #{params_inspect}"
end
def rest_client_send(params)
RestClient::Request.execute(
method: :post,
url: MandrillBatchMailer::ENDPOINT,
payload: params.to_json,
read_timeout: MandrillBatchMailer.read_timeout,
open_timeout: MandrillBatchMailer.open_timeout)
end
end
|
sds/haml-lint | lib/haml_lint/linter/rubocop.rb | HamlLint.Linter::RuboCop.extract_lints_from_offenses | ruby | def extract_lints_from_offenses(offenses, source_map)
dummy_node = Struct.new(:line)
offenses.reject { |offense| Array(config['ignored_cops']).include?(offense.cop_name) }
.each do |offense|
record_lint(dummy_node.new(source_map[offense.line]), offense.message,
offense.severity.name)
end
end | Aggregates RuboCop offenses and converts them to {HamlLint::Lint}s
suitable for reporting.
@param offenses [Array<RuboCop::Cop::Offense>]
@param source_map [Hash] | train | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/rubocop.rb#L68-L76 | class Linter::RuboCop < Linter
include LinterRegistry
# Maps the ::RuboCop::Cop::Severity levels to our own levels.
SEVERITY_MAP = {
error: :error,
fatal: :error,
convention: :warning,
refactor: :warning,
warning: :warning,
}.freeze
def visit_root(_node)
extractor = HamlLint::RubyExtractor.new
extracted_source = extractor.extract(document)
return if extracted_source.source.empty?
find_lints(extracted_source.source, extracted_source.source_map)
end
private
# Executes RuboCop against the given Ruby code and records the offenses as
# lints.
#
# @param ruby [String] Ruby code
# @param source_map [Hash] map of Ruby code line numbers to original line
# numbers in the template
def find_lints(ruby, source_map)
rubocop = ::RuboCop::CLI.new
filename =
if document.file
"#{document.file}.rb"
else
'ruby_script.rb'
end
with_ruby_from_stdin(ruby) do
extract_lints_from_offenses(lint_file(rubocop, filename), source_map)
end
end
# Defined so we can stub the results in tests
#
# @param rubocop [RuboCop::CLI]
# @param file [String]
# @return [Array<RuboCop::Cop::Offense>]
def lint_file(rubocop, file)
rubocop.run(rubocop_flags << file)
OffenseCollector.offenses
end
# Aggregates RuboCop offenses and converts them to {HamlLint::Lint}s
# suitable for reporting.
#
# @param offenses [Array<RuboCop::Cop::Offense>]
# @param source_map [Hash]
# Record a lint for reporting back to the user.
#
# @param node [#line] node to extract the line number from
# @param message [String] error/warning to display to the user
# @param severity [Symbol] RuboCop severity level for the offense
def record_lint(node, message, severity)
@lints << HamlLint::Lint.new(self, @document.file, node.line, message,
SEVERITY_MAP.fetch(severity, :warning))
end
# Returns flags that will be passed to RuboCop CLI.
#
# @return [Array<String>]
def rubocop_flags
flags = %w[--format HamlLint::OffenseCollector]
flags += ['--config', ENV['HAML_LINT_RUBOCOP_CONF']] if ENV['HAML_LINT_RUBOCOP_CONF']
flags += ['--stdin']
flags
end
# Overrides the global stdin to allow RuboCop to read Ruby code from it.
#
# @param ruby [String] the Ruby code to write to the overridden stdin
# @param _block [Block] the block to perform with the overridden stdin
# @return [void]
def with_ruby_from_stdin(ruby, &_block)
original_stdin = $stdin
stdin = StringIO.new
stdin.write(ruby)
stdin.rewind
$stdin = stdin
yield
ensure
$stdin = original_stdin
end
end
|
oniram88/imdb-scan | lib/imdb/movie.rb | IMDB.Movie.genres | ruby | def genres
doc.xpath("//h4[contains(., 'Genre')]/..").search("a").map { |g|
g.content.strip unless g.content =~ /See more/
}.compact
rescue
nil
end | Genre List
@return [Array] | train | https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L115-L121 | class Movie < IMDB::Skeleton
attr_accessor :link, :imdb_id
def initialize(id_of)
# !!!DON'T FORGET DEFINE NEW METHODS IN SUPER!!!
super("Movie", { :imdb_id => String,
:poster => String,
:title => String,
:release_date => String,
:cast => Array,
:photos => Array,
:director => String,
:director_person => Person,
:genres => Array,
:rating => Float,
:movielength => Integer,
:short_description => String,
:writers => Array }, [:imdb_id])
@imdb_id = id_of
@link = "http://www.imdb.com/title/tt#{@imdb_id}"
end
# Get movie poster address
# @return [String]
def poster
src = doc.at("#img_primary img")["src"] rescue nil
unless src.nil?
if src.match(/\._V1/)
return src.match(/(.*)\._V1.*(.jpg)/)[1, 2].join
else
return src
end
end
src
end
# Get movie title
# @return [String]
def title
doc.at("//head/meta[@name='title']")["content"].split(/\(.*\)/)[0].strip! ||
doc.at("h1.header").children.first.text.strip
end
# Get movie cast listing
# @return [Cast[]]
def cast
doc.search("table.cast tr").map do |link|
#picture = link.children[0].search("img")[0]["src"] rescue nil
#name = link.children[1].content.strip rescue nil
id = link.children[1].search('a[@href^="/name/nm"]').first["href"].match(/\/name\/nm([0-9]+)/)[1] rescue nil
char = link.children[3].content.strip rescue nil
unless id.nil?
person = IMDB::Person.new(id)
IMDB::Cast.new(self, person, char)
end
end.compact
end
# Get movie photos
# @return [Array]
def photos
begin
doc.search('#main .media_index_thumb_list img').map { |i| i["src"] }
rescue
nil
end
end
# Get release date
# @return [String]
def release_date
if (node =doc.css('.infobar span.nobr meta[itemprop="datePublished"]')).length > 0
date = node.first['content']
if date.match /^\d{4}$/
"#{date}-01-01"
else
Date.parse(date).to_s
end
else
year = doc.at("h1.header .nobr").text[/\d{4}/]
"#{year}-01-01"
end
rescue
nil
end
# Get Director
# @return [String]
def director
self.director_person.name rescue nil
end
# Get Director Person class
# @return [Person]
def director_person
begin
link=doc.xpath("//h4[contains(., 'Director')]/..").at('a[@href^="/name/nm"]')
profile = link['href'].match(/\/name\/nm([0-9]+)/)[1] rescue nil
IMDB::Person.new(profile) unless profile.nil?
rescue
nil
end
end
# Genre List
# @return [Array]
# Writer List
# @return [Float]
def rating
@rating ||= doc.search(".star-box-giga-star").text.strip.to_f
rescue
nil
end
#Get the movielength of the movie in minutes
# @return [Integer]
def movielength
doc.at("//h4[text()='Runtime:']/..").inner_html[/\d+ min/].to_i rescue nil
end
# Writer List
# @return [Array]
def writers
doc.css("h4:contains('Writing')").first.next_element.css('a[@href^="/name/nm"]').map { |w|
profile = w['href'].match(/\/name\/nm([0-9]+)/)[1] rescue nil
IMDB::Person.new(profile) unless profile.nil?
}
end
# @return [String]
def short_description
doc.at("#overview-top p[itemprop=description]").try(:text).try(:strip)
end
private
def doc
if caller[0] =~ /`([^']*)'/ and ($1 == "cast" or $1 == "writers")
@doc_full ||= Nokogiri::HTML(open("#{@link}/fullcredits"))
elsif caller[0] =~ /`([^']*)'/ and ($1 == "photos")
@doc_photo ||= Nokogiri::HTML(open("#{@link}/mediaindex"))
else
@doc ||= Nokogiri::HTML(open("#{@link}"))
end
end
end # Movie
|
groupdocs-signature-cloud/groupdocs-signature-cloud-ruby | lib/groupdocs_signature_cloud/models/border_line_data.rb | GroupDocsSignatureCloud.BorderLineData.list_invalid_properties | ruby | def list_invalid_properties
invalid_properties = []
if @style.nil?
invalid_properties.push("invalid value for 'style', style cannot be nil.")
end
if @transparency.nil?
invalid_properties.push("invalid value for 'transparency', transparency cannot be nil.")
end
if @weight.nil?
invalid_properties.push("invalid value for 'weight', weight cannot be nil.")
end
return invalid_properties
end | Initializes the object
@param [Hash] attributes Model attributes in the form of hash
Show invalid properties with the reasons. Usually used together with valid?
@return Array for valid properies with the reasons | train | https://github.com/groupdocs-signature-cloud/groupdocs-signature-cloud-ruby/blob/d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0/lib/groupdocs_signature_cloud/models/border_line_data.rb#L120-L135 | class BorderLineData
# Gets or sets the signature border style.
attr_accessor :style
# Gets or sets the signature border transparency (value from 0.0 (opaque) through 1.0 (clear)).
attr_accessor :transparency
# Gets or sets the weight of the signature border.
attr_accessor :weight
# Gets or sets the border color of signature.
attr_accessor :color
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'style' => :'Style',
:'transparency' => :'Transparency',
:'weight' => :'Weight',
:'color' => :'Color'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'style' => :'String',
:'transparency' => :'Float',
:'weight' => :'Float',
:'color' => :'Color'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.key?(:'Style')
self.style = attributes[:'Style']
end
if attributes.key?(:'Transparency')
self.transparency = attributes[:'Transparency']
end
if attributes.key?(:'Weight')
self.weight = attributes[:'Weight']
end
if attributes.key?(:'Color')
self.color = attributes[:'Color']
end
if !((defined? options_type) == nil)
self.options_type = "BorderLineData"
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @style.nil?
style_validator = EnumAttributeValidator.new('String', ["Default", "Solid", "ShortDash", "ShortDot", "ShortDashDot", "ShortDashDotDot", "Dot", "Dash", "LongDash", "DashDot", "LongDashDot", "LongDashDotDot"])
return false unless style_validator.valid?(@style)
return false if @transparency.nil?
return false if @weight.nil?
return true
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] style Object to be assigned
def style=(style)
validator = EnumAttributeValidator.new('String', ["Default", "Solid", "ShortDash", "ShortDot", "ShortDashDot", "ShortDashDotDot", "Dot", "Dash", "LongDash", "DashDot", "LongDashDot", "LongDashDotDot"])
if style.to_i == 0
unless validator.valid?(style)
raise ArgumentError, "invalid value for 'style', must be one of #{validator.allowable_values}."
end
@style = style
else
@style = validator.allowable_values[style.to_i]
end
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(other)
return true if self.equal?(other)
self.class == other.class &&
style == other.style &&
transparency == other.transparency &&
weight == other.weight &&
color == other.color
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(other)
self == other
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[style, transparency, weight, color].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
attributeName = self.class.attribute_map[key]
attributeNameLowerStr = attributeName.to_s
attributeNameLowerStr[0] = attributeNameLowerStr[0].downcase
attributeNameLower = attributeNameLowerStr.to_sym
attributeNameLowerStr2 = attributeName.to_s
attributeNameLowerStr2[0] = attributeNameLowerStr[0].downcase
attributeNameLowerStr2[1] = attributeNameLowerStr[1].downcase
attributeNameLower2 = attributeNameLowerStr2.to_sym
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[attributeName].is_a?(Array)
self.send("#{key}=", attributes[attributeName].map { |v| _deserialize($1, v) })
end
if attributes[attributeNameLower].is_a?(Array)
self.send("#{key}=", attributes[attributeNameLower].map { |v| _deserialize($1, v) })
end
if attributes[attributeNameLower2].is_a?(Array)
self.send("#{key}=", attributes[attributeNameLower2].map { |v| _deserialize($1, v) })
end
elsif !attributes[attributeName].nil?
self.send("#{key}=", _deserialize(type, attributes[attributeName]))
elsif !attributes[attributeNameLower].nil?
self.send("#{key}=", _deserialize(type, attributes[attributeNameLower]))
elsif !attributes[attributeNameLower2].nil?
self.send("#{key}=", _deserialize(type, attributes[attributeNameLower2]))
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
Time.at(/\d/.match(value)[0].to_f).to_datetime
when :Date
Time.at(/\d/.match(value)[0].to_f).to_date
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else
# model
temp_model = GroupDocsSignatureCloud.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
|
giraffi/zcloudjp | lib/zcloudjp/machine.rb | Zcloudjp.Machine.start | ruby | def start(params={})
id = params.delete(:id) || self.id
response = Zcloudjp::Client.post("/machines/#{id}/start", self.request_options)
update_attributes(response.parsed_response)
end | POST /machines/:id/start.json | train | https://github.com/giraffi/zcloudjp/blob/0ee8dd49cf469fd182a48856fae63f606a959de5/lib/zcloudjp/machine.rb#L41-L45 | module Machine
# GET /machines.json
def index(params={})
self.request_options = self.request_options.merge(params[:query] || {})
response = Zcloudjp::Client.get("/machines", self.request_options)
response.parsed_response.map do |res|
update_attributes(res).clone
end
end
alias :list :index
# GET /machines/:id.json
def show(params={})
id = params.delete(:id) || self.id
response = Zcloudjp::Client.get("/machines/#{id}", self.request_options)
update_attributes(response.parsed_response)
end
alias :find_by :show
alias :reload :show
# POST /machines.json
def create(params={})
self.request_options = self.request_options.merge(body: params.to_json)
response = Zcloudjp::Client.post("/machines", self.request_options)
update_attributes(response.parsed_response)
end
# DELETE /machines/:id.json
def delete(params={})
id = params.delete(:id) || self.id
response = Zcloudjp::Client.delete("/machines/#{id}", self.request_options)
update_attributes(response.parsed_response)
end
alias :destroy :delete
# POST /machines/:id/start.json
# POST /machines/:id/stop.json
def stop(params={})
id = params.delete(:id) || self.id
response = Zcloudjp::Client.post("/machines/#{id}/stop", self.request_options)
update_attributes(response.parsed_response)
end
# Create a Metadata object related to the specified machine
def metadata
Metadata.new(self)
end
protected
def update_attributes(response)
response = response.first if response.is_a? Array
response.each do |key, value|
self.instance_variable_set(:"@#{key}", value)
self.send("#{key}=", value)
end
self
end
end
|
mongodb/mongoid | lib/mongoid/positional.rb | Mongoid.Positional.positionally | ruby | def positionally(selector, operations, processed = {})
if selector.size == 1 || selector.values.any? { |val| val.nil? }
return operations
end
keys = selector.keys.map{ |m| m.sub('._id','') } - ['_id']
keys = keys.sort_by { |s| s.length*-1 }
process_operations(keys, operations, processed)
end | Takes the provided selector and atomic operations and replaces the
indexes of the embedded documents with the positional operator when
needed.
@note The only time we can accurately know when to use the positional
operator is at the exact time we are going to persist something. So
we can tell by the selector that we are sending if it is actually
possible to use the positional operator at all. For example, if the
selector is: { "_id" => 1 }, then we could not use the positional
operator for updating embedded documents since there would never be a
match - we base whether we can based on the number of levels deep the
selector goes, and if the id values are not nil.
@example Process the operations.
positionally(
{ "_id" => 1, "addresses._id" => 2 },
{ "$set" => { "addresses.0.street" => "hobrecht" }}
)
@param [ Hash ] selector The selector.
@param [ Hash ] operations The update operations.
@param [ Hash ] processed The processed update operations.
@return [ Hash ] The new operations.
@since 3.1.0 | train | https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/positional.rb#L37-L44 | module Positional
# Takes the provided selector and atomic operations and replaces the
# indexes of the embedded documents with the positional operator when
# needed.
#
# @note The only time we can accurately know when to use the positional
# operator is at the exact time we are going to persist something. So
# we can tell by the selector that we are sending if it is actually
# possible to use the positional operator at all. For example, if the
# selector is: { "_id" => 1 }, then we could not use the positional
# operator for updating embedded documents since there would never be a
# match - we base whether we can based on the number of levels deep the
# selector goes, and if the id values are not nil.
#
# @example Process the operations.
# positionally(
# { "_id" => 1, "addresses._id" => 2 },
# { "$set" => { "addresses.0.street" => "hobrecht" }}
# )
#
# @param [ Hash ] selector The selector.
# @param [ Hash ] operations The update operations.
# @param [ Hash ] processed The processed update operations.
#
# @return [ Hash ] The new operations.
#
# @since 3.1.0
private
def process_operations(keys, operations, processed)
operations.each_pair do |operation, update|
processed[operation] = process_updates(keys, update)
end
processed
end
def process_updates(keys, update, updates = {})
update.each_pair do |position, value|
updates[replace_index(keys, position)] = value
end
updates
end
def replace_index(keys, position)
# replace index with $ only if that key is in the selector and it is only
# nested a single level deep.
matches = position.scan(/\.\d+\./)
if matches.size == 1
keys.each do |kk|
if position =~ /^#{kk}\.\d+\.(.*)/
return "#{kk}.$.#{$1}"
end
end
end
position
end
end
|
RobertAudi/TaskList | lib/task-list/parser.rb | TaskList.Parser.unglobify | ruby | def unglobify(glob)
chars = glob.split("")
chars = smoosh(chars)
curlies = 0
escaping = false
string = chars.map do |char|
if escaping
escaping = false
char
else
case char
when "**"
"([^/]+/)*"
when '*'
".*"
when "?"
"."
when "."
"\."
when "{"
curlies += 1
"("
when "}"
if curlies > 0
curlies -= 1
")"
else
char
end
when ","
if curlies > 0
"|"
else
char
end
when "\\"
escaping = true
"\\"
else
char
end
end
end
'(\A|\/)' + string.join + '\Z'
end | NOTE: This is actually a glob-to-regex method | train | https://github.com/RobertAudi/TaskList/blob/98ac82f449eec7a6958f88c19c9637845eae68f2/lib/task-list/parser.rb#L165-L213 | class Parser
attr_reader :files, :tasks, :search_path, :github
def initialize(arguments: [], options: {})
self.search_path = options[:search_path]
@github = options[:github] if options[:github]
@plain = options[:plain] if options[:plain]
@type = options[:type].upcase if options[:type]
@files = fuzzy_find_files queries: arguments
@tasks = {}
VALID_TASKS.each { |t| @tasks[t.to_sym] = [] }
end
def search_path=(value)
if value.nil? || value.empty?
@search_path = "."
else
@search_path = value
end
end
# Parse all the collected files to find tasks
# and populate the tasks hash
def parse!
unless @type.nil? || VALID_TASKS.include?(@type)
raise TaskList::Exceptions::InvalidTaskTypeError.new type: @type
end
@files.each { |f| parsef! file: f }
end
def print!
@tasks.each do |type, tasks|
unless tasks.empty?
puts "#{type}:\n#{'-' * (type.length + 1)}\n"
if self.github? || self.plain?
puts
end
tasks.each do |task|
if self.github?
if Pathname.new(self.search_path).absolute?
reference = "#{task[:file].sub(/#{Regexp.escape(self.git_repo_root)}\//, "")}#L#{task[:line_number]}"
else
search_path_components = File.expand_path(self.search_path).split(File::SEPARATOR)
search_path_components.pop
parent = File.join(*search_path_components)
file = task[:file].sub(/#{Regexp.escape(parent)}\//, "")
reference = "#{file}#L#{task[:line_number]}"
end
puts "- #{task[:task]} — [#{reference}](#{reference})"
else
puts task[:task]
if self.plain?
puts " line #{task[:line_number]} in #{task[:file]}"
else
puts " \e[30m\e[1mline #{task[:line_number]} in #{task[:file]}\e[0m"
end
end
end
puts
end
end
end
def git_repo_root
full_search_path = File.expand_path(self.search_path)
root_path = full_search_path.dup
repo_found = false
begin
if File.directory?(File.join(root_path, ".git"))
repo_found = true
break
end
directories = root_path.split(File::SEPARATOR)
directories.pop
root_path = File.join(*directories)
end until repo_found
unless repo_found
# FIXME: Show an error message instead of raising an exception
raise "No git repo found."
end
root_path
end
def github?
!!@github
end
def plain?
!!@plain
end
private
def fuzzy_find_files(queries: [])
patterns = regexify queries
paths = []
Find.find(File.expand_path(self.search_path)) do |path|
paths << path unless FileTest.directory?(path)
end
paths.map! { |p| p.gsub(/\A\.\//, "") }
EXCLUDED_DIRECTORIES.each do |d|
paths.delete_if { |p| p =~ /\A#{Regexp.escape(d)}/ }
end
EXCLUDED_EXTENSIONS.each do |e|
paths.delete_if { |p| File.file?(p) && File.extname(p) =~ /\A#{Regexp.escape(e)}/ }
end
EXCLUDED_GLOBS.each do |g|
paths.delete_if { |p| p =~ /#{unglobify(g)}/ }
end
if queries.empty?
paths
else
results = []
patterns.each do |pattern|
paths.each do |path|
matches = path.match(/#{pattern}/).to_a
results << path unless matches.empty?
end
end
results
end
end
def regexify(queries)
patterns = []
queries.each do |query|
if query.include?("/")
pattern = query.split("/").map { |p| p.split("").join(")[^\/]*?(").prepend("[^\/]*?(") + ")[^\/]*?" }.join("\/")
pattern << "\/" if query[-1] == "/"
else
pattern = query.split("").join(").*?(").prepend(".*?(") + ").*?"
end
patterns << pattern
end
patterns
end
# NOTE: This is actually a glob-to-regex method
def smoosh(chars)
out = []
until chars.empty?
char = chars.shift
if char == "*" && chars.first == "*"
chars.shift
chars.shift if chars.first == "/"
out.push("**")
else
out.push(char)
end
end
out
end
# Parse a file to find tasks
def parsef!(file: "")
types = @type ? [@type] : VALID_TASKS
File.open(file, "r") do |f|
line_number = 1
while line = f.gets
types.each do |type|
result = line.match(/#{Regexp.escape(type)}[\s,:-]+(\S.*)\Z/) rescue nil
unless result.nil?
task = {
file: file,
line_number: line_number,
task: result.to_a.last
}
@tasks[type.to_sym] << task
end
end
line_number += 1
end
end
end
end
|
mailgun/mailgun-ruby | lib/mailgun/messages/message_builder.rb | Mailgun.MessageBuilder.add_tag | ruby | def add_tag(tag)
if @counters[:attributes][:tag] >= Mailgun::Chains::MAX_TAGS
fail Mailgun::ParameterError, 'Too many tags added to message.', tag
end
set_multi_complex('o:tag', tag)
@counters[:attributes][:tag] += 1
end | Add tags to message. Limit of 3 per message.
@param [String] tag A defined campaign ID to add to the message.
@return [void] | train | https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/message_builder.rb#L187-L193 | class MessageBuilder
attr_reader :message, :counters
# Public: Creates a new MessageBuilder object.
def initialize
@message = Hash.new { |hash, key| hash[key] = [] }
@counters = {
recipients: { to: 0, cc: 0, bcc: 0 },
attributes: { attachment: 0, campaign_id: 0, custom_option: 0, tag: 0 }
}
end
# Adds a specific type of recipient to the message object.
#
# WARNING: Setting 'h:reply-to' with add_recipient() is deprecated! Use 'reply_to' instead.
#
# @param [String] recipient_type The type of recipient. "to", "cc", "bcc" or "h:reply-to".
# @param [String] address The email address of the recipient to add to the message object.
# @param [Hash] variables A hash of the variables associated with the recipient. We recommend "first" and "last" at a minimum!
# @return [void]
def add_recipient(recipient_type, address, variables = nil)
if recipient_type == "h:reply-to"
warn 'DEPRECATION: "add_recipient("h:reply-to", ...)" is deprecated. Please use "reply_to" instead.'
return reply_to(address, variables)
end
if (@counters[:recipients][recipient_type] || 0) >= Mailgun::Chains::MAX_RECIPIENTS
fail Mailgun::ParameterError, 'Too many recipients added to message.', address
end
compiled_address = parse_address(address, variables)
set_multi_complex(recipient_type, compiled_address)
@counters[:recipients][recipient_type] += 1 if @counters[:recipients].key?(recipient_type)
end
# Sets the from address for the message
#
# @param [String] address The address of the sender.
# @param [Hash] variables A hash of the variables associated with the recipient. We recommend "first" and "last" at a minimum!
# @return [void]
def from(address, vars = nil)
add_recipient(:from, address, vars)
end
# Deprecated: please use 'from' instead.
def set_from_address(address, variables = nil)
warn 'DEPRECATION: "set_from_address" is deprecated. Please use "from" instead.'
from(address, variables)
end
# Set the message's Reply-To address.
#
# Rationale: According to RFC, only one Reply-To address is allowed, so it
# is *okay* to bypass the set_multi_simple and set reply-to directly.
#
# @param [String] address The email address to provide as Reply-To.
# @param [Hash] variables A hash of variables associated with the recipient.
# @return [void]
def reply_to(address, variables = nil)
compiled_address = parse_address(address, variables)
header("reply-to", compiled_address)
end
# Set a subject for the message object
#
# @param [String] subject The subject for the email.
# @return [void]
def subject(subj = nil)
set_multi_simple(:subject, subj)
end
# Deprecated: Please use "subject" instead.
def set_subject(subj = nil)
warn 'DEPRECATION: "set_subject" is deprecated. Please use "subject" instead.'
subject(subj)
end
# Set a text body for the message object
#
# @param [String] text_body The text body for the email.
# @return [void]
def body_text(text_body = nil)
set_multi_simple(:text, text_body)
end
# Deprecated: Please use "body_text" instead.
def set_text_body(text_body = nil)
warn 'DEPRECATION: "set_text_body" is deprecated. Please use "body_text" instead.'
body_text(text_body)
end
# Set a html body for the message object
#
# @param [String] html_body The html body for the email.
# @return [void]
def body_html(html_body = nil)
set_multi_simple(:html, html_body)
end
# Deprecated: Please use "body_html" instead.
def set_html_body(html_body = nil)
warn 'DEPRECATION: "set_html_body" is deprecated. Please use "body_html" instead.'
body_html(html_body)
end
# Adds a series of attachments, when called upon.
#
# @param [String|File] attachment A file object for attaching as an attachment.
# @param [String] filename The filename you wish the attachment to be.
# @return [void]
def add_attachment(attachment, filename = nil)
add_file(:attachment, attachment, filename)
end
# Adds an inline image to the mesage object.
#
# @param [String|File] inline_image A file object for attaching an inline image.
# @param [String] filename The filename you wish the inline image to be.
# @return [void]
def add_inline_image(inline_image, filename = nil)
add_file(:inline, inline_image, filename)
end
# Adds a List-Unsubscribe for the message header.
#
# @param [Array<String>] *variables Any number of url or mailto
# @return [void]
def list_unsubscribe(*variables)
set_single('h:List-Unsubscribe', variables.map { |var| "<#{var}>" }.join(','))
end
# Send a message in test mode. (The message won't really be sent to the recipient)
#
# @param [Boolean] mode The boolean or string value (will fix itself)
# @return [void]
def test_mode(mode)
set_multi_simple('o:testmode', bool_lookup(mode))
end
# Deprecated: 'set_test_mode' is depreciated. Please use 'test_mode' instead.
def set_test_mode(mode)
warn 'DEPRECATION: "set_test_mode" is deprecated. Please use "test_mode" instead.'
test_mode(mode)
end
# Turn DKIM on or off per message
#
# @param [Boolean] mode The boolean or string value(will fix itself)
# @return [void]
def dkim(mode)
set_multi_simple('o:dkim', bool_lookup(mode))
end
# Deprecated: 'set_dkim' is deprecated. Please use 'dkim' instead.
def set_dkim(mode)
warn 'DEPRECATION: "set_dkim" is deprecated. Please use "dkim" instead.'
dkim(mode)
end
# Add campaign IDs to message. Limit of 3 per message.
#
# @param [String] campaign_id A defined campaign ID to add to the message.
# @return [void]
def add_campaign_id(campaign_id)
fail(Mailgun::ParameterError, 'Too many campaigns added to message.', campaign_id) if @counters[:attributes][:campaign_id] >= Mailgun::Chains::MAX_CAMPAIGN_IDS
set_multi_complex('o:campaign', campaign_id)
@counters[:attributes][:campaign_id] += 1
end
# Add tags to message. Limit of 3 per message.
#
# @param [String] tag A defined campaign ID to add to the message.
# @return [void]
# Turn Open Tracking on and off, on a per message basis.
#
# @param [Boolean] tracking Boolean true or false.
# @return [void]
def track_opens(mode)
set_multi_simple('o:tracking-opens', bool_lookup(mode))
end
# Deprecated: 'set_open_tracking' is deprecated. Please use 'track_opens' instead.
def set_open_tracking(tracking)
warn 'DEPRECATION: "set_open_tracking" is deprecated. Please use "track_opens" instead.'
track_opens(tracking)
end
# Turn Click Tracking on and off, on a per message basis.
#
# @param [String] mode True, False, or HTML (for HTML only tracking)
# @return [void]
def track_clicks(mode)
set_multi_simple('o:tracking-clicks', bool_lookup(mode))
end
# Depreciated: 'set_click_tracking. is deprecated. Please use 'track_clicks' instead.
def set_click_tracking(tracking)
warn 'DEPRECATION: "set_click_tracking" is deprecated. Please use "track_clicks" instead.'
track_clicks(tracking)
end
# Enable Delivery delay on message. Specify an RFC2822 date, and Mailgun
# will not deliver the message until that date/time. For conversion
# options, see Ruby "Time". Example: "October 25, 2013 10:00PM CST" will
# be converted to "Fri, 25 Oct 2013 22:00:00 -0600".
#
# @param [String] timestamp A date and time, including a timezone.
# @return [void]
def deliver_at(timestamp)
time_str = DateTime.parse(timestamp)
set_multi_simple('o:deliverytime', time_str.rfc2822)
end
# Deprecated: 'set_delivery_time' is deprecated. Please use 'deliver_at' instead.
def set_delivery_time(timestamp)
warn 'DEPRECATION: "set_delivery_time" is deprecated. Please use "deliver_at" instead.'
deliver_at timestamp
end
# Add custom data to the message. The data should be either a hash or JSON
# encoded. The custom data will be added as a header to your message.
#
# @param [string] name A name for the custom data. (Ex. X-Mailgun-<Name of Data>: {})
# @param [Hash] data Either a hash or JSON string.
# @return [void]
def header(name, data)
fail(Mailgun::ParameterError, 'Header name for message must be specified') if name.to_s.empty?
begin
jsondata = make_json data
set_single("h:#{name}", jsondata)
rescue Mailgun::ParameterError
set_single("h:#{name}", data)
end
end
# Deprecated: 'set_custom_data' is deprecated. Please use 'header' instead.
def set_custom_data(name, data)
warn 'DEPRECATION: "set_custom_data" is deprecated. Please use "header" instead.'
header name, data
end
# Attaches custom JSON data to the message. See the following doc page for more info.
# https://documentation.mailgun.com/user_manual.html#attaching-data-to-messages
#
# @param [String] name A name for the custom variable block.
# @param [String|Hash] data Either a string or a hash. If it is not valid JSON or
# can not be converted to JSON, ParameterError will be raised.
# @return [void]
def variable(name, data)
fail(Mailgun::ParameterError, 'Variable name must be specified') if name.to_s.empty?
jsondata = make_json data
set_single("v:#{name}", jsondata)
end
# Add custom parameter to the message. A custom parameter is any parameter that
# is not yet supported by the SDK, but available at the API. Note: No validation
# is performed. Don't forget to prefix the parameter with o, h, or v.
#
# @param [string] name A name for the custom parameter.
# @param [string] data A string of data for the parameter.
# @return [void]
def add_custom_parameter(name, data)
set_multi_complex(name, data)
end
# Set the Message-Id header to a custom value. Don't forget to enclose the
# Message-Id in angle brackets, and ensure the @domain is present. Doesn't
# use simple or complex setters because it should not set value in an array.
#
# @param [string] data A string of data for the parameter. Passing nil or
# empty string will delete h:Message-Id key and value from @message hash.
# @return [void]
def message_id(data = nil)
key = 'h:Message-Id'
return @message.delete(key) if data.to_s.empty?
set_single(key, data)
end
# Deprecated: 'set_message_id' is deprecated. Use 'message_id' instead.
def set_message_id(data = nil)
warn 'DEPRECATION: "set_message_id" is deprecated. Please use "message_id" instead.'
message_id data
end
private
# Sets a single value in the message hash where "multidict" features are not needed.
# Does *not* permit duplicate params.
#
# @param [String] parameter The message object parameter name.
# @param [String] value The value of the parameter.
# @return [void]
def set_single(parameter, value)
@message[parameter] = value ? value : ''
end
# Sets values within the multidict, however, prevents
# duplicate values for keys.
#
# @param [String] parameter The message object parameter name.
# @param [String] value The value of the parameter.
# @return [void]
def set_multi_simple(parameter, value)
@message[parameter] = value ? [value] : ['']
end
# Sets values within the multidict, however, allows
# duplicate values for keys.
#
# @param [String] parameter The message object parameter name.
# @param [String] value The value of the parameter.
# @return [void]
def set_multi_complex(parameter, value)
@message[parameter] << (value || '')
end
# Converts boolean type to string
#
# @param [String] value The item to convert
# @return [void]
def bool_lookup(value)
return 'yes' if %w(true yes yep).include? value.to_s.downcase
return 'no' if %w(false no nope).include? value.to_s.downcase
value
end
# Validates whether the input is JSON.
#
# @param [String] json_ The suspected JSON string.
# @return [void]
def valid_json?(json_)
JSON.parse(json_)
return true
rescue JSON::ParserError
false
end
# Private: given an object attempt to make it into JSON
#
# obj - an object. Hopefully a JSON string or Hash
#
# Returns a JSON object or raises ParameterError
def make_json(obj)
return JSON.parse(obj).to_json if obj.is_a?(String)
return obj.to_json if obj.is_a?(Hash)
return JSON.generate(obj).to_json
rescue
raise Mailgun::ParameterError, 'Provided data could not be made into JSON. Try a JSON string or Hash.', obj
end
# Parses the address and gracefully handles any
# missing parameters. The result should be something like:
# "'First Last' <person@domain.com>"
#
# @param [String] address The email address to parse.
# @param [Hash] variables A list of recipient variables.
# @return [void]
def parse_address(address, vars)
return address unless vars.is_a? Hash
fail(Mailgun::ParameterError, 'Email address not specified') unless address.is_a? String
if vars['full_name'] != nil && (vars['first'] != nil || vars['last'] != nil)
fail(Mailgun::ParameterError, 'Must specify at most one of full_name or first/last. Vars passed: #{vars}')
end
if vars['full_name']
full_name = vars['full_name']
elsif vars['first'] || vars['last']
full_name = "#{vars['first']} #{vars['last']}".strip
end
return "'#{full_name}' <#{address}>" if defined?(full_name)
address
end
# Private: Adds a file to the message.
#
# @param [Symbol] disposition The type of file: :attachment or :inline
# @param [String|File] attachment A file object for attaching as an attachment.
# @param [String] filename The filename you wish the attachment to be.
# @return [void]
#
# Returns nothing
def add_file(disposition, filedata, filename)
attachment = File.open(filedata, 'r') if filedata.is_a?(String)
attachment = filedata.dup unless attachment
fail(Mailgun::ParameterError,
'Unable to access attachment file object.'
) unless attachment.respond_to?(:read)
unless filename.nil?
attachment.instance_variable_set :@original_filename, filename
attachment.instance_eval 'def original_filename; @original_filename; end'
end
set_multi_complex(disposition, attachment)
end
end
|
jeremytregunna/ruby-trello | lib/trello/card.rb | Trello.Card.add_attachment | ruby | def add_attachment(attachment, name = '')
# Is it a file object or a string (url)?
if attachment.respond_to?(:path) && attachment.respond_to?(:read)
client.post("/cards/#{id}/attachments", {
file: attachment,
name: name
})
else
client.post("/cards/#{id}/attachments", {
url: attachment,
name: name
})
end
end | Add an attachment to this card | train | https://github.com/jeremytregunna/ruby-trello/blob/ad79c9d8152ad5395b3b61c43170908f1912bfb2/lib/trello/card.rb#L421-L434 | class Card < BasicData
register_attributes :id, :short_id, :name, :desc, :due, :due_complete, :closed, :url, :short_url,
:board_id, :member_ids, :list_id, :pos, :last_activity_date, :labels, :card_labels,
:cover_image_id, :badges, :card_members, :source_card_id, :source_card_properties,
readonly: [ :id, :short_id, :url, :short_url, :last_activity_date, :badges, :card_members ]
validates_presence_of :id, :name, :list_id
validates_length_of :name, in: 1..16384
validates_length_of :desc, in: 0..16384
include HasActions
SYMBOL_TO_STRING = {
id: 'id',
short_id: 'idShort',
name: 'name',
desc: 'desc',
due: 'due',
due_complete: 'dueComplete',
closed: 'closed',
url: 'url',
short_url: 'shortUrl',
board_id: 'idBoard',
member_ids: 'idMembers',
cover_image_id: 'idAttachmentCover',
list_id: 'idList',
pos: 'pos',
last_activity_date: 'dateLastActivity',
card_labels: 'idLabels',
labels: 'labels',
badges: 'badges',
card_members: 'members',
source_card_id: "idCardSource",
source_card_properties: "keepFromSource"
}
class << self
# Find a specific card by its id.
#
# @raise [Trello::Error] if the card could not be found.
#
# @return [Trello::Card]
def find(id, params = {})
client.find(:card, id, params)
end
# Create a new card and save it on Trello.
#
# If using source_card_id to duplicate a card, make sure to save
# the source card to Trello before calling this method to assure
# the correct data is used in the duplication.
#
# @param [Hash] options
# @option options [String] :name The name of the new card.
# @option options [String] :list_id ID of the list that the card should
# be added to.
# @option options [String] :desc A string with a
# length from 0 to 16384.
# @option options [String] :member_ids A comma-separated list of
# objectIds (24-character hex strings).
# @option options [String] :card_labels A comma-separated list of
# objectIds (24-character hex strings).
# @option options [Date] :due A date, or `nil`.
# @option options [String] :pos A position. `"top"`, `"bottom"`, or a
# positive number. Defaults to `"bottom"`.
# @option options [String] :source_card_id ID of the card to copy
# @option options [String] :source_card_properties A single, or array of,
# string properties to copy from source card.
# `"all"`, `"checklists"`, `"due"`, `"members"`, or `nil`.
# Defaults to `"all"`.
#
# @raise [Trello::Error] if the card could not be created.
#
# @return [Trello::Card]
def create(options)
client.create(:card,
'name' => options[:name],
'idList' => options[:list_id],
'desc' => options[:desc],
'idMembers' => options[:member_ids],
'idLabels' => options[:card_labels],
'due' => options[:due],
'due_complete' => options[:due_complete] || false,
'pos' => options[:pos],
'idCardSource' => options[:source_card_id],
'keepFromSource' => options.key?(:source_card_properties) ? options[:source_card_properties] : 'all'
)
end
end
# Update the fields of a card.
#
# Supply a hash of string keyed data retrieved from the Trello API representing
# a card.
#
# Note that this this method does not save anything new to the Trello API,
# it just assigns the input attributes to your local object. If you use
# this method to assign attributes, call `save` or `update!` afterwards if
# you want to persist your changes to Trello.
#
# @param [Hash] fields
# @option fields [String] :id
# @option fields [String] :short_id
# @option fields [String] :name The new name of the card.
# @option fields [String] :desc A string with a length from 0 to
# 16384.
# @option fields [Date] :due A date, or `nil`.
# @option fields [Boolean] :due_complete
# @option fields [Boolean] :closed
# @option fields [String] :url
# @option fields [String] :short_url
# @option fields [String] :board_id
# @option fields [String] :member_ids A comma-separated list of objectIds
# (24-character hex strings).
# @option fields [String] :pos A position. `"top"`, `"bottom"`, or a
# positive number. Defaults to `"bottom"`.
# @option fields [Array] :labels An Array of Trello::Label objects
# derived from the JSON response
# @option fields [String] :card_labels A comma-separated list of
# objectIds (24-character hex strings).
# @option fields [Object] :cover_image_id
# @option fields [Object] :badges
# @option fields [Object] :card_members
# @option fields [String] :source_card_id
# @option fields [Array] :source_card_properties
#
# @return [Trello::Card] self
def update_fields(fields)
attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || attributes[:id]
attributes[:short_id] = fields[SYMBOL_TO_STRING[:short_id]] || attributes[:short_id]
attributes[:name] = fields[SYMBOL_TO_STRING[:name]] || fields[:name] || attributes[:name]
attributes[:desc] = fields[SYMBOL_TO_STRING[:desc]] || fields[:desc] || attributes[:desc]
attributes[:due] = Time.iso8601(fields[SYMBOL_TO_STRING[:due]]) rescue nil if fields.has_key?(SYMBOL_TO_STRING[:due])
attributes[:due] = fields[:due] if fields.has_key?(:due)
attributes[:due_complete] = fields[SYMBOL_TO_STRING[:due_complete]] if fields.has_key?(SYMBOL_TO_STRING[:due_complete])
attributes[:due_complete] ||= false
attributes[:closed] = fields[SYMBOL_TO_STRING[:closed]] if fields.has_key?(SYMBOL_TO_STRING[:closed])
attributes[:url] = fields[SYMBOL_TO_STRING[:url]] || attributes[:url]
attributes[:short_url] = fields[SYMBOL_TO_STRING[:short_url]] || attributes[:short_url]
attributes[:board_id] = fields[SYMBOL_TO_STRING[:board_id]] || attributes[:board_id]
attributes[:member_ids] = fields[SYMBOL_TO_STRING[:member_ids]] || fields[:member_ids] || attributes[:member_ids]
attributes[:list_id] = fields[SYMBOL_TO_STRING[:list_id]] || fields[:list_id] || attributes[:list_id]
attributes[:pos] = fields[SYMBOL_TO_STRING[:pos]] || fields[:pos] || attributes[:pos]
attributes[:labels] = (fields[SYMBOL_TO_STRING[:labels]] || []).map { |lbl| Trello::Label.new(lbl) }.presence || attributes[:labels].presence || []
attributes[:card_labels] = fields[SYMBOL_TO_STRING[:card_labels]] || fields[:card_labels] || attributes[:card_labels]
attributes[:last_activity_date] = Time.iso8601(fields[SYMBOL_TO_STRING[:last_activity_date]]) rescue nil if fields.has_key?(SYMBOL_TO_STRING[:last_activity_date])
attributes[:cover_image_id] = fields[SYMBOL_TO_STRING[:cover_image_id]] || attributes[:cover_image_id]
attributes[:badges] = fields[SYMBOL_TO_STRING[:badges]] || attributes[:badges]
attributes[:card_members] = fields[SYMBOL_TO_STRING[:card_members]] || attributes[:card_members]
attributes[:source_card_id] = fields[SYMBOL_TO_STRING[:source_card_id]] || fields[:source_card_id] || attributes[:source_card_id]
attributes[:source_card_properties] = fields[SYMBOL_TO_STRING[:source_card_properties]] || fields[:source_card_properties] || attributes[:source_card_properties]
self
end
# Returns a reference to the board this card is part of.
one :board, path: :boards, using: :board_id
# Returns a reference to the cover image attachment
one :cover_image, path: :attachments, using: :cover_image_id
# Returns a list of checklists associated with the card.
#
# The options hash may have a filter key which can have its value set as any
# of the following values:
# :filter => [ :none, :all ] # default :all
many :checklists, filter: :all
# Returns a list of plugins associated with the card
many :plugin_data, path: "pluginData"
# List of custom field values on the card, only the ones that have been set
many :custom_field_items, path: 'customFieldItems'
def check_item_states
states = CheckItemState.from_response client.get("/cards/#{self.id}/checkItemStates")
MultiAssociation.new(self, states).proxy
end
# Returns a reference to the list this card is currently in.
one :list, path: :lists, using: :list_id
# Returns a list of members who are assigned to this card.
#
# @return [Array<Trello::Member>]
def members
members = Member.from_response client.get("/cards/#{self.id}/members")
MultiAssociation.new(self, members).proxy
end
# Returns a list of members who have upvoted this card
# NOTE: this fetches a list each time it's called to avoid case where
# card is voted (or vote is removed) after card is fetched. Optimizing
# accuracy over network performance
#
# @return [Array<Trello::Member>]
def voters
Member.from_response client.get("/cards/#{id}/membersVoted")
end
# Saves a record.
#
# @raise [Trello::Error] if the card could not be saved
#
# @return [String] The JSON representation of the saved card returned by
# the Trello API.
def save
# If we have an id, just update our fields.
return update! if id
from_response client.post("/cards", {
name: name,
desc: desc,
idList: list_id,
idMembers: member_ids,
idLabels: card_labels,
pos: pos,
due: due,
dueComplete: due_complete,
idCardSource: source_card_id,
keepFromSource: source_card_properties
})
end
# Update an existing record.
#
# Warning: this updates all fields using values already in memory. If
# an external resource has updated these fields, you should refresh!
# this object before making your changes, and before updating the record.
#
# @raise [Trello::Error] if the card could not be updated.
#
# @return [String] The JSON representation of the updated card returned by
# the Trello API.
def update!
@previously_changed = changes
# extract only new values to build payload
payload = Hash[changes.map { |key, values| [SYMBOL_TO_STRING[key.to_sym].to_sym, values[1]] }]
@changed_attributes.clear
client.put("/cards/#{id}", payload)
end
# Delete this card
#
# @return [String] the JSON response from the Trello API
def delete
client.delete("/cards/#{id}")
end
# Check if the card is not active anymore.
def closed?
closed
end
# Close the card.
#
# This only marks your local copy card as closed. Use `close!` if you
# want to close the card and persist the change to the Trello API.
#
# @return [Boolean] always returns true
#
# @return [String] The JSON representation of the closed card returned by
# the Trello API.
def close
self.closed = true
end
def close!
close
save
end
# Is the record valid?
def valid?
name && list_id
end
# Add a comment with the supplied text.
def add_comment(text)
client.post("/cards/#{id}/actions/comments", text: text)
end
# Add a checklist to this card
def add_checklist(checklist)
client.post("/cards/#{id}/checklists", {
value: checklist.id
})
end
# create a new checklist and add it to this card
def create_new_checklist(name)
client.post("/cards/#{id}/checklists", { name: name })
end
# Move this card to the given list
def move_to_list(list)
list_number = list.is_a?(String) ? list : list.id
unless list_id == list_number
client.put("/cards/#{id}/idList", {
value: list_number
})
end
end
# Moves this card to the given list no matter which board it is on
def move_to_list_on_any_board(list_id)
list = List.find(list_id)
if board.id == list.board_id
move_to_list(list_id)
else
move_to_board(Board.find(list.board_id), list)
end
end
# Move this card to the given board (and optional list on this board)
def move_to_board(new_board, new_list = nil)
unless board_id == new_board.id
payload = { value: new_board.id }
payload[:idList] = new_list.id if new_list
client.put("/cards/#{id}/idBoard", payload)
end
end
# Add a member to this card
def add_member(member)
client.post("/cards/#{id}/members", {
value: member.id
})
end
# Remove a member from this card
def remove_member(member)
client.delete("/cards/#{id}/members/#{member.id}")
end
# Current authenticated user upvotes a card
def upvote
begin
client.post("/cards/#{id}/membersVoted", {
value: me.id
})
rescue Trello::Error => e
fail e unless e.message =~ /has already voted/i
end
self
end
# Recind upvote. Noop if authenticated user hasn't previously voted
def remove_upvote
begin
client.delete("/cards/#{id}/membersVoted/#{me.id}")
rescue Trello::Error => e
fail e unless e.message =~ /has not voted/i
end
self
end
# Add a label
def add_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.post("/cards/#{id}/idLabels", {value: label.id})
end
# Remove a label
def remove_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.delete("/cards/#{id}/idLabels/#{label.id}")
end
# Add an attachment to this card
# Retrieve a list of attachments
def attachments
attachments = Attachment.from_response client.get("/cards/#{id}/attachments")
MultiAssociation.new(self, attachments).proxy
end
# Remove an attachment from this card
def remove_attachment(attachment)
client.delete("/cards/#{id}/attachments/#{attachment.id}")
end
# :nodoc:
def request_prefix
"/cards/#{id}"
end
# Retrieve a list of comments
def comments
comments = Comment.from_response client.get("/cards/#{id}/actions", filter: "commentCard")
end
# Find the creation date
def created_at
@created_at ||= Time.at(id[0..7].to_i(16)) rescue nil
end
private
def me
@me ||= Member.find(:me)
end
end
|
puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.add_ingress_rule | ruby | def add_ingress_rule(cl, sg_group, cidr_ip, from_port, to_port, protocol = 'tcp')
cl.authorize_security_group_ingress(
:cidr_ip => cidr_ip,
:ip_protocol => protocol,
:from_port => from_port,
:to_port => to_port,
:group_id => sg_group.group_id,
)
end | Authorizes connections from certain CIDR to a range of ports
@param cl [Aws::EC2::Client]
@param sg_group [Aws::EC2::SecurityGroup] the AWS security group
@param cidr_ip [String] CIDR used for outbound security group rule
@param from_port [String] Starting Port number in the range
@param to_port [String] Ending Port number in the range
@return [void]
@api private | train | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1105-L1113 | class AwsSdk < Beaker::Hypervisor
ZOMBIE = 3 #anything older than 3 hours is considered a zombie
PING_SECURITY_GROUP_NAME = 'beaker-ping'
attr_reader :default_region
# Initialize AwsSdk hypervisor driver
#
# @param [Array<Beaker::Host>] hosts Array of Beaker::Host objects
# @param [Hash<String, String>] options Options hash
def initialize(hosts, options)
@hosts = hosts
@options = options
@logger = options[:logger]
@default_region = ENV['AWS_REGION'] || 'us-west-2'
# Get AWS credentials
creds = options[:use_fog_credentials] ? load_credentials() : nil
config = {
:credentials => creds,
:logger => Logger.new($stdout),
:log_level => :debug,
:log_formatter => Aws::Log::Formatter.colored,
:retry_limit => 12,
:region => ENV['AWS_REGION'] || 'us-west-2'
}.delete_if{ |k,v| v.nil? }
Aws.config.update(config)
@client = {}
@client.default_proc = proc do |hash, key|
hash[key] = Aws::EC2::Client.new(:region => key)
end
test_split_install()
end
def client(region = default_region)
@client[region]
end
# Provision all hosts on EC2 using the Aws::EC2 API
#
# @return [void]
def provision
start_time = Time.now
# Perform the main launch work
launch_all_nodes()
# Add metadata tags to each instance
# tagging early as some nodes take longer
# to initialize and terminate before it has
# a chance to provision
add_tags()
# adding the correct security groups to the
# network interface, as during the `launch_all_nodes()`
# step they never get assigned, although they get created
modify_network_interface()
wait_for_status_netdev()
# Grab the ip addresses and dns from EC2 for each instance to use for ssh
populate_dns()
#enable root if user is not root
enable_root_on_hosts()
# Set the hostname for each box
set_hostnames()
# Configure /etc/hosts on each host
configure_hosts()
@logger.notify("aws-sdk: Provisioning complete in #{Time.now - start_time} seconds")
nil #void
end
def regions
@regions ||= client.describe_regions.regions.map(&:region_name)
end
# Kill all instances.
#
# @param instances [Enumerable<Aws::EC2::Types::Instance>]
# @return [void]
def kill_instances(instances)
running_instances = instances.compact.select do |instance|
instance_by_id(instance.instance_id).state.name == 'running'
end
instance_ids = running_instances.map(&:instance_id)
return nil if instance_ids.empty?
@logger.notify("aws-sdk: killing EC2 instance(s) #{instance_ids.join(', ')}")
client.terminate_instances(:instance_ids => instance_ids)
nil
end
# Cleanup all earlier provisioned hosts on EC2 using the Aws::EC2 library
#
# It goes without saying, but a #cleanup does nothing without a #provision
# method call first.
#
# @return [void]
def cleanup
# Provisioning should have set the host 'instance' values.
kill_instances(@hosts.map{ |h| h['instance'] }.select{ |x| !x.nil? })
delete_key_pair_all_regions()
nil
end
# Print instances to the logger. Instances will be from all regions
# associated with provided key name and limited by regex compared to
# instance status. Defaults to running instances.
#
# @param [String] key The key_name to match for
# @param [Regex] status The regular expression to match against the instance's status
def log_instances(key = key_name, status = /running/)
instances = []
regions.each do |region|
@logger.debug "Reviewing: #{region}"
client(region).describe_instances.reservations.each do |reservation|
reservation.instances.each do |instance|
if (instance.key_name =~ /#{key}/) and (instance.state.name =~ status)
instances << instance
end
end
end
end
output = ""
instances.each do |instance|
dns_name = instance.public_dns_name || instance.private_dns_name
output << "#{instance.instance_id} keyname: #{instance.key_name}, dns name: #{dns_name}, private ip: #{instance.private_ip_address}, ip: #{instance.public_ip_address}, launch time #{instance.launch_time}, status: #{instance.state.name}\n"
end
@logger.notify("aws-sdk: List instances (keyname: #{key})")
@logger.notify("#{output}")
end
# Provided an id return an instance object.
# Instance object will respond to methods described here: {http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/EC2/Instance.html AWS Instance Object}.
# @param [String] id The id of the instance to return
# @return [Aws::EC2::Types::Instance] An Aws::EC2 instance object
def instance_by_id(id)
client.describe_instances(:instance_ids => [id]).reservations.first.instances.first
end
# Return all instances currently on ec2.
# @see AwsSdk#instance_by_id
# @return [Array<Aws::Ec2::Types::Instance>] An array of Aws::EC2 instance objects
def instances
client.describe_instances.reservations.map(&:instances).flatten
end
# Provided an id return a VPC object.
# VPC object will respond to methods described here: {http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/EC2/VPC.html AWS VPC Object}.
# @param [String] id The id of the VPC to return
# @return [Aws::EC2::Types::Vpc] An Aws::EC2 vpc object
def vpc_by_id(id)
client.describe_vpcs(:vpc_ids => [id]).vpcs.first
end
# Return all VPCs currently on ec2.
# @see AwsSdk#vpc_by_id
# @return [Array<Aws::EC2::Types::Vpc>] An array of Aws::EC2 vpc objects
def vpcs
client.describe_vpcs.vpcs
end
# Provided an id return a security group object
# Security object will respond to methods described here: {http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/EC2/SecurityGroup.html AWS SecurityGroup Object}.
# @param [String] id The id of the security group to return
# @return [Aws::EC2::Types::SecurityGroup] An Aws::EC2 security group object
def security_group_by_id(id)
client.describe_security_groups(:group_ids => [id]).security_groups.first
end
# Return all security groups currently on ec2.
# @see AwsSdk#security_goup_by_id
# @return [Array<Aws::EC2::Types::SecurityGroup>] An array of Aws::EC2 security group objects
def security_groups
client.describe_security_groups.security_groups
end
# Shutdown and destroy ec2 instances idenfitied by key that have been alive
# longer than ZOMBIE hours.
#
# @param [Integer] max_age The age in hours that a machine needs to be older than to be considered a zombie
# @param [String] key The key_name to match for
def kill_zombies(max_age = ZOMBIE, key = key_name)
@logger.notify("aws-sdk: Kill Zombies! (keyname: #{key}, age: #{max_age} hrs)")
instances_to_kill = []
time_now = Time.now.getgm #ec2 uses GM time
#examine all available regions
regions.each do |region|
@logger.debug "Reviewing: #{region}"
client(region).describe_instances.reservations.each do |reservation|
reservation.instances.each do |instance|
if (instance.key_name =~ /#{key}/)
@logger.debug "Examining #{instance.instance_id} (keyname: #{instance.key_name}, launch time: #{instance.launch_time}, state: #{instance.state.name})"
if ((time_now - instance.launch_time) > max_age*60*60) and instance.state.name !~ /terminated/
@logger.debug "Kill! #{instance.instance_id}: #{instance.key_name} (Current status: #{instance.state.name})"
instances_to_kill << instance
end
end
end
end
end
kill_instances(instances_to_kill)
delete_key_pair_all_regions(key_name_prefix)
@logger.notify "#{key}: Killed #{instances_to_kill.length} instance(s)"
end
# Destroy any volumes marked 'available', INCLUDING THOSE YOU DON'T OWN! Use with care.
def kill_zombie_volumes
# Occasionaly, tearing down ec2 instances leaves orphaned EBS volumes behind -- these stack up quickly.
# This simply looks for EBS volumes that are not in use
@logger.notify("aws-sdk: Kill Zombie Volumes!")
volume_count = 0
regions.each do |region|
@logger.debug "Reviewing: #{region}"
available_volumes = client(region).describe_volumes(
:filters => [
{ :name => 'status', :values => ['available'], }
]
).volumes
available_volumes.each do |volume|
begin
client(region).delete_volume(:volume_id => volume.id)
volume_count += 1
rescue Aws::EC2::Errors::InvalidVolume::NotFound => e
@logger.debug "Failed to remove volume: #{volume.id} #{e}"
end
end
end
@logger.notify "Freed #{volume_count} volume(s)"
end
# Create an EC2 instance for host, tag it, and return it.
#
# @return [void]
# @api private
def create_instance(host, ami_spec, subnet_id)
amitype = host['vmname'] || host['platform']
amisize = host['amisize'] || 'm1.small'
vpc_id = host['vpc_id'] || @options['vpc_id'] || nil
host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0';
sg_cidr_ips = host['sg_cidr_ips'].split(',')
assoc_pub_ip_addr = host['associate_public_ip_address']
if vpc_id && !subnet_id
raise RuntimeError, "A subnet_id must be provided with a vpc_id"
end
if assoc_pub_ip_addr && !subnet_id
raise RuntimeError, "A subnet_id must be provided when configuring assoc_pub_ip_addr"
end
# Use snapshot provided for this host
image_type = host['snapshot']
raise RuntimeError, "No snapshot/image_type provided for EC2 provisioning" unless image_type
ami = ami_spec[amitype]
ami_region = ami[:region]
# Main region object for ec2 operations
region = ami_region
# If we haven't defined a vpc_id then we use the default vpc for the provided region
unless vpc_id
@logger.notify("aws-sdk: filtering available vpcs in region by 'isDefault'")
default_vpcs = client(region).describe_vpcs(:filters => [{:name => 'isDefault', :values => ['true']}])
vpc_id = if default_vpcs.vpcs.empty?
nil
else
default_vpcs.vpcs.first.vpc_id
end
end
# Grab the vpc object based upon provided id
vpc = vpc_id ? client(region).describe_vpcs(:vpc_ids => [vpc_id]).vpcs.first : nil
# Grab image object
image_id = ami[:image][image_type.to_sym]
@logger.notify("aws-sdk: Checking image #{image_id} exists and getting its root device")
image = client(region).describe_images(:image_ids => [image_id]).images.first
raise RuntimeError, "Image not found: #{image_id}" if image.nil?
@logger.notify("Image Storage Type: #{image.root_device_type}")
# Transform the images block_device_mappings output into a format
# ready for a create.
block_device_mappings = []
if image.root_device_type == :ebs
orig_bdm = image.block_device_mappings
@logger.notify("aws-sdk: Image block_device_mappings: #{orig_bdm}")
orig_bdm.each do |block_device|
block_device_mappings << {
:device_name => block_device.device_name,
:ebs => {
# Change the default size of the root volume.
:volume_size => host['volume_size'] || block_device.ebs.volume_size,
# This is required to override the images default for
# delete_on_termination, forcing all volumes to be deleted once the
# instance is terminated.
:delete_on_termination => true,
}
}
end
end
security_group = ensure_group(vpc || region, Beaker::EC2Helper.amiports(host), sg_cidr_ips)
#check if ping is enabled
ping_security_group = ensure_ping_group(vpc || region, sg_cidr_ips)
msg = "aws-sdk: launching %p on %p using %p/%p%s" %
[host.name, amitype, amisize, image_type,
subnet_id ? ("in %p" % subnet_id) : '']
@logger.notify(msg)
config = {
:max_count => 1,
:min_count => 1,
:image_id => image_id,
:monitoring => {
:enabled => true,
},
:key_name => ensure_key_pair(region).key_pairs.first.key_name,
:instance_type => amisize,
:disable_api_termination => false,
:instance_initiated_shutdown_behavior => "terminate",
}
if assoc_pub_ip_addr
# this never gets created, so they end up with
# default security group which only allows for
# ssh access from outside world which
# doesn't work well with remote devices etc.
config[:network_interfaces] = [{
:subnet_id => subnet_id,
:groups => [security_group.group_id, ping_security_group.group_id],
:device_index => 0,
:associate_public_ip_address => assoc_pub_ip_addr,
}]
else
config[:subnet_id] = subnet_id
end
config[:block_device_mappings] = block_device_mappings if image.root_device_type == :ebs
reservation = client(region).run_instances(config)
reservation.instances.first
end
# For each host, create an EC2 instance in one of the specified
# subnets and push it onto instances_created. Each subnet will be
# tried at most once for each host, and more than one subnet may
# be tried if capacity constraints are encountered. Each Hash in
# instances_created will contain an :instance and :host value.
#
# @param hosts [Enumerable<Host>]
# @param subnets [Enumerable<String>]
# @param ami_spec [Hash]
# @param instances_created Enumerable<Hash{Symbol=>EC2::Instance,Host}>
# @return [void]
# @api private
def launch_nodes_on_some_subnet(hosts, subnets, ami_spec, instances_created)
# Shuffle the subnets so we don't always hit the same one
# first, and cycle though the subnets independently of the
# host, so we stick with one that's working. Try each subnet
# once per-host.
if subnets.nil? or subnets.empty?
return
end
subnet_i = 0
shuffnets = subnets.shuffle
hosts.each do |host|
instance = nil
shuffnets.length.times do
begin
subnet_id = shuffnets[subnet_i]
instance = create_instance(host, ami_spec, subnet_id)
instances_created.push({:instance => instance, :host => host})
break
rescue Aws::EC2::Errors::InsufficientInstanceCapacity
@logger.notify("aws-sdk: hit #{subnet_id} capacity limit; moving on")
subnet_i = (subnet_i + 1) % shuffnets.length
end
end
if instance.nil?
raise RuntimeError, "unable to launch host in any requested subnet"
end
end
end
# Create EC2 instances for all hosts, tag them, and wait until
# they're running. When a host provides a subnet_id, create the
# instance in that subnet, otherwise prefer a CONFIG subnet_id.
# If neither are set but there is a CONFIG subnet_ids list,
# attempt to create the host in each specified subnet, which might
# fail due to capacity constraints, for example. Specifying both
# a CONFIG subnet_id and subnet_ids will provoke an error.
#
# @return [void]
# @api private
def launch_all_nodes
@logger.notify("aws-sdk: launch all hosts in configuration")
ami_spec = YAML.load_file(@options[:ec2_yaml])["AMI"]
global_subnet_id = @options['subnet_id']
global_subnets = @options['subnet_ids']
if global_subnet_id and global_subnets
raise RuntimeError, 'Config specifies both subnet_id and subnet_ids'
end
no_subnet_hosts = []
specific_subnet_hosts = []
some_subnet_hosts = []
@hosts.each do |host|
if global_subnet_id or host['subnet_id']
specific_subnet_hosts.push(host)
elsif global_subnets
some_subnet_hosts.push(host)
else
no_subnet_hosts.push(host)
end
end
instances = [] # Each element is {:instance => i, :host => h}
begin
@logger.notify("aws-sdk: launch instances not particular about subnet")
launch_nodes_on_some_subnet(some_subnet_hosts, global_subnets, ami_spec,
instances)
@logger.notify("aws-sdk: launch instances requiring a specific subnet")
specific_subnet_hosts.each do |host|
subnet_id = host['subnet_id'] || global_subnet_id
instance = create_instance(host, ami_spec, subnet_id)
instances.push({:instance => instance, :host => host})
end
@logger.notify("aws-sdk: launch instances requiring no subnet")
no_subnet_hosts.each do |host|
instance = create_instance(host, ami_spec, nil)
instances.push({:instance => instance, :host => host})
end
wait_for_status(:running, instances)
rescue Exception => ex
@logger.notify("aws-sdk: exception #{ex.class}: #{ex}")
kill_instances(instances.map{|x| x[:instance]})
raise ex
end
# At this point, all instances should be running since wait
# either returns on success or throws an exception.
if instances.empty?
raise RuntimeError, "Didn't manage to launch any EC2 instances"
end
# Assign the now known running instances to their hosts.
instances.each {|x| x[:host]['instance'] = x[:instance]}
nil
end
# Wait until all instances reach the desired state. Each Hash in
# instances must contain an :instance and :host value.
#
# @param state_name [String] EC2 state to wait for, 'running', 'stopped', etc.
# @param instances Enumerable<Hash{Symbol=>EC2::Instance,Host}>
# @param block [Proc] more complex checks can be made by passing a
# block in. This overrides the status parameter.
# EC2::Instance objects from the hosts will be
# yielded to the passed block
# @return [void]
# @api private
# FIXME: rename to #wait_for_state
def wait_for_status(state_name, instances, &block)
# Wait for each node to reach status :running
@logger.notify("aws-sdk: Waiting for all hosts to be #{state_name}")
instances.each do |x|
name = x[:host] ? x[:host].name : x[:name]
instance = x[:instance]
@logger.notify("aws-sdk: Wait for node #{name} to be #{state_name}")
# Here we keep waiting for the machine state to reach 'running' with an
# exponential backoff for each poll.
# TODO: should probably be a in a shared method somewhere
for tries in 1..10
refreshed_instance = instance_by_id(instance.instance_id)
if refreshed_instance.nil?
@logger.debug("Instance #{name} not yet available (#{e})")
else
if block_given?
test_result = yield refreshed_instance
else
test_result = refreshed_instance.state.name.to_s == state_name.to_s
end
if test_result
x[:instance] = refreshed_instance
# Always sleep, so the next command won't cause a throttle
backoff_sleep(tries)
break
elsif tries == 10
raise "Instance never reached state #{state_name}"
end
end
backoff_sleep(tries)
end
end
end
# Handles special checks needed for netdev platforms.
#
# @note if any host is an netdev one, these checks will happen once across all
# of the hosts, and then we'll exit
#
# @return [void]
# @api private
def wait_for_status_netdev()
@hosts.each do |host|
if host['platform'] =~ /f5-|netscaler/
wait_for_status(:running, @hosts)
wait_for_status(nil, @hosts) do |instance|
instance_status_collection = client.describe_instance_status({:instance_ids => [instance.instance_id]})
first_instance = instance_status_collection.first[:instance_statuses].first
first_instance[:instance_status][:status] == "ok" if first_instance
end
break
end
end
end
# Add metadata tags to all instances
#
# @return [void]
# @api private
def add_tags
@hosts.each do |host|
instance = host['instance']
# Define tags for the instance
@logger.notify("aws-sdk: Add tags for #{host.name}")
tags = [
{
:key => 'jenkins_build_url',
:value => @options[:jenkins_build_url],
},
{
:key => 'Name',
:value => host.name,
},
{
:key => 'department',
:value => @options[:department],
},
{
:key => 'project',
:value => @options[:project],
},
{
:key => 'created_by',
:value => @options[:created_by],
},
]
host[:host_tags].each do |name, val|
tags << { :key => name.to_s, :value => val }
end
client.create_tags(
:resources => [instance.instance_id],
:tags => tags.reject { |r| r[:value].nil? },
)
end
nil
end
# Add correct security groups to hosts network_interface
# as during the create_instance stage it is too early in process
# to configure
#
# @return [void]
# @api private
def modify_network_interface
@hosts.each do |host|
instance = host['instance']
host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0';
sg_cidr_ips = host['sg_cidr_ips'].split(',')
# Define tags for the instance
@logger.notify("aws-sdk: Update network_interface for #{host.name}")
security_group = ensure_group(instance[:network_interfaces].first, Beaker::EC2Helper.amiports(host), sg_cidr_ips)
ping_security_group = ensure_ping_group(instance[:network_interfaces].first, sg_cidr_ips)
client.modify_network_interface_attribute(
:network_interface_id => "#{instance[:network_interfaces].first[:network_interface_id]}",
:groups => [security_group.group_id, ping_security_group.group_id],
)
end
nil
end
# Populate the hosts IP address from the EC2 dns_name
#
# @return [void]
# @api private
def populate_dns
# Obtain the IP addresses and dns_name for each host
@hosts.each do |host|
@logger.notify("aws-sdk: Populate DNS for #{host.name}")
instance = host['instance']
host['ip'] = instance.public_ip_address || instance.private_ip_address
host['private_ip'] = instance.private_ip_address
host['dns_name'] = instance.public_dns_name || instance.private_dns_name
@logger.notify("aws-sdk: name: #{host.name} ip: #{host['ip']} private_ip: #{host['private_ip']} dns_name: #{host['dns_name']}")
end
nil
end
# Return a valid /etc/hosts line for a given host
#
# @param [Beaker::Host] host Beaker::Host object for generating /etc/hosts entry
# @param [Symbol] interface Symbol identifies which ip should be used for host
# @return [String] formatted hosts entry for host
# @api private
def etc_hosts_entry(host, interface = :ip)
name = host.name
domain = get_domain_name(host)
ip = host[interface.to_s]
"#{ip}\t#{name} #{name}.#{domain} #{host['dns_name']}\n"
end
# Configure /etc/hosts for each node
#
# @note f5 hosts are skipped since this isn't a valid step there
#
# @return [void]
# @api private
def configure_hosts
non_netdev_windows_hosts = @hosts.select{ |h| !(h['platform'] =~ /f5-|netscaler|windows/) }
non_netdev_windows_hosts.each do |host|
host_entries = non_netdev_windows_hosts.map do |h|
h == host ? etc_hosts_entry(h, :private_ip) : etc_hosts_entry(h)
end
host_entries.unshift "127.0.0.1\tlocalhost localhost.localdomain\n"
set_etc_hosts(host, host_entries.join(''))
end
nil
end
# Enables root for instances with custom username like ubuntu-amis
#
# @return [void]
# @api private
def enable_root_on_hosts
@hosts.each do |host|
if host['disable_root_ssh'] == true
@logger.notify("aws-sdk: Not enabling root for instance as disable_root_ssh is set to 'true'.")
else
@logger.notify("aws-sdk: Enabling root ssh")
enable_root(host)
end
end
end
# Enables root access for a host when username is not root
#
# @return [void]
# @api private
def enable_root(host)
if host['user'] != 'root'
if host['platform'] =~ /f5-/
enable_root_f5(host)
elsif host['platform'] =~ /netscaler/
enable_root_netscaler(host)
else
copy_ssh_to_root(host, @options)
enable_root_login(host, @options)
host['user'] = 'root'
end
host.close
end
end
# Enables root access for a host on an f5 platform
# @note This method does not support other platforms
#
# @return nil
# @api private
def enable_root_f5(host)
for tries in 1..10
begin
#This command is problematic as the F5 is not always done loading
if host.exec(Command.new("modify sys db systemauth.disablerootlogin value false"), :acceptable_exit_codes => [0,1]).exit_code == 0 \
and host.exec(Command.new("modify sys global-settings gui-setup disabled"), :acceptable_exit_codes => [0,1]).exit_code == 0 \
and host.exec(Command.new("save sys config"), :acceptable_exit_codes => [0,1]).exit_code == 0
backoff_sleep(tries)
break
elsif tries == 10
raise "Instance was unable to be configured"
end
rescue Beaker::Host::CommandFailure => e
@logger.debug("Instance not yet configured (#{e})")
end
backoff_sleep(tries)
end
host['user'] = 'admin'
sha256 = Digest::SHA256.new
password = sha256.hexdigest((1..50).map{(rand(86)+40).chr}.join.gsub(/\\/,'\&\&')) + 'password!'
# disabling password policy to account for the enforcement level set
# and the generated password is sometimes too `01070366:3: Bad password (admin): BAD PASSWORD: \
# it is too simplistic/systematic`
host.exec(Command.new('modify auth password-policy policy-enforcement disabled'))
host.exec(Command.new("modify auth user admin password #{password}"))
@logger.notify("f5: Configured admin password to be #{password}")
host.close
host['ssh'] = {:password => password}
end
# Enables root access for a host on an netscaler platform
# @note This method does not support other platforms
#
# @return nil
# @api private
def enable_root_netscaler(host)
host['ssh'] = {:password => host['instance'].instance_id}
@logger.notify("netscaler: nsroot password is #{host['instance'].instance_id}")
end
# Set the :vmhostname for each host object to be the dns_name, which is accessible
# publicly. Then configure each ec2 machine to that dns_name, so that when facter
# is installed the facts for hostname and domain match the dns_name.
#
# if :use_beaker_hostnames: is true, set the :vmhostname and hostname of each ec2
# machine to the host[:name] from the beaker hosts file.
#
# @return [@hosts]
# @api private
def set_hostnames
if @options[:use_beaker_hostnames]
@hosts.each do |host|
host[:vmhostname] = host.name
if host['platform'] =~ /el-7/
# on el-7 hosts, the hostname command doesn't "stick" randomly
host.exec(Command.new("hostnamectl set-hostname #{host.name}"))
elsif host['platform'] =~ /windows/
@logger.notify('aws-sdk: Change hostname on windows is not supported.')
else
next if host['platform'] =~ /f5-|netscaler/
host.exec(Command.new("hostname #{host.name}"))
if host['vmname'] =~ /^amazon/
# Amazon Linux requires this to preserve host name changes across reboots.
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-hostname.html
# Also note that without an elastic ip set, while this will
# preserve the hostname across a full shutdown/startup of the vm
# (as opposed to a reboot) -- the ip address will have changed.
host.exec(Command.new("sed -ie '/^HOSTNAME/ s/=.*/=#{host.name}/' /etc/sysconfig/network"))
end
end
end
else
@hosts.each do |host|
host[:vmhostname] = host[:dns_name]
if host['platform'] =~ /el-7/
# on el-7 hosts, the hostname command doesn't "stick" randomly
host.exec(Command.new("hostnamectl set-hostname #{host.hostname}"))
elsif host['platform'] =~ /windows/
@logger.notify('aws-sdk: Change hostname on windows is not supported.')
else
next if host['platform'] =~ /ft-|netscaler/
host.exec(Command.new("hostname #{host.hostname}"))
if host['vmname'] =~ /^amazon/
# See note above
host.exec(Command.new("sed -ie '/^HOSTNAME/ s/=.*/=#{host.hostname}/' /etc/sysconfig/network"))
end
end
end
end
end
# Calculates and waits a back-off period based on the number of tries
#
# Logs each backupoff time and retry value to the console.
#
# @param tries [Number] number of tries to calculate back-off period
# @return [void]
# @api private
def backoff_sleep(tries)
# Exponential with some randomization
sleep_time = 2 ** tries
@logger.notify("aws-sdk: Sleeping #{sleep_time} seconds for attempt #{tries}.")
sleep sleep_time
nil
end
# Retrieve the public key locally from the executing users ~/.ssh directory
#
# @return [String] contents of public key
# @api private
def public_key
keys = Array(@options[:ssh][:keys])
keys << '~/.ssh/id_rsa'
keys << '~/.ssh/id_dsa'
key_file = keys.find do |key|
key_pub = key + '.pub'
File.exist?(File.expand_path(key_pub)) && File.exist?(File.expand_path(key))
end
if key_file
@logger.debug("Using public key: #{key_file}")
else
raise RuntimeError, "Expected to find a public key, but couldn't in #{keys}"
end
File.read(File.expand_path(key_file + '.pub'))
end
# Generate a key prefix for key pair names
#
# @note This is the part of the key that will stay static between Beaker
# runs on the same host.
#
# @return [String] Beaker key pair name based on sanitized hostname
def key_name_prefix
safe_hostname = Socket.gethostname.gsub('.', '-')
"Beaker-#{local_user}-#{safe_hostname}"
end
# Generate a reusable key name from the local hosts hostname
#
# @return [String] safe key name for current host
# @api private
def key_name
"#{key_name_prefix}-#{@options[:aws_keyname_modifier]}-#{@options[:timestamp].strftime("%F_%H_%M_%S_%N")}"
end
# Returns the local user running this tool
#
# @return [String] username of local user
# @api private
def local_user
ENV['USER']
end
# Creates the KeyPair for this test run
#
# @param region [Aws::EC2::Region] region to create the key pair in
# @return [Aws::EC2::KeyPair] created key_pair
# @api private
def ensure_key_pair(region)
pair_name = key_name()
delete_key_pair(region, pair_name)
create_new_key_pair(region, pair_name)
end
# Deletes key pairs from all regions
#
# @param [String] keypair_name_filter if given, will get all keypairs that match
# a simple {::String#start_with?} filter. If no filter is given, the basic key
# name returned by {#key_name} will be used.
#
# @return nil
# @api private
def delete_key_pair_all_regions(keypair_name_filter=nil)
region_keypairs_hash = my_key_pairs(keypair_name_filter)
region_keypairs_hash.each_pair do |region, keypair_name_array|
keypair_name_array.each do |keypair_name|
delete_key_pair(region, keypair_name)
end
end
end
# Gets the Beaker user's keypairs by region
#
# @param [String] name_filter if given, will get all keypairs that match
# a simple {::String#start_with?} filter. If no filter is given, the basic key
# name returned by {#key_name} will be used.
#
# @return [Hash{String=>Array[String]}] a hash of region name to
# an array of the keypair names that match for the filter
# @api private
def my_key_pairs(name_filter=nil)
keypairs_by_region = {}
key_name_filter = name_filter ? "#{name_filter}-*" : key_name
regions.each do |region|
keypairs_by_region[region] = client(region).describe_key_pairs(
:filters => [{ :name => 'key-name', :values => [key_name_filter] }]
).key_pairs.map(&:key_name)
end
keypairs_by_region
end
# Deletes a given key pair
#
# @param [Aws::EC2::Region] region the region the key belongs to
# @param [String] pair_name the name of the key to be deleted
#
# @api private
def delete_key_pair(region, pair_name)
kp = client(region).describe_key_pairs(:key_names => [pair_name]).key_pairs.first
unless kp.nil?
@logger.debug("aws-sdk: delete key pair in region: #{region}")
client(region).delete_key_pair(:key_name => pair_name)
end
rescue Aws::EC2::Errors::InvalidKeyPairNotFound
nil
end
# Create a new key pair for a given Beaker run
#
# @param [Aws::EC2::Region] region the region the key pair will be imported into
# @param [String] pair_name the name of the key to be created
#
# @return [Aws::EC2::KeyPair] key pair created
# @raise [RuntimeError] raised if AWS keypair not created
def create_new_key_pair(region, pair_name)
@logger.debug("aws-sdk: importing new key pair: #{pair_name}")
client(region).import_key_pair(:key_name => pair_name, :public_key_material => public_key)
begin
client(region).wait_until(:key_pair_exists, { :key_names => [pair_name] }, :max_attempts => 5, :delay => 2)
rescue Aws::Waiters::Errors::WaiterFailed
raise RuntimeError, "AWS key pair #{pair_name} can not be queried, even after import"
end
end
# Return a reproducable security group identifier based on input ports
#
# @param ports [Array<Number>] array of port numbers
# @return [String] group identifier
# @api private
def group_id(ports)
if ports.nil? or ports.empty?
raise ArgumentError, "Ports list cannot be nil or empty"
end
unless ports.is_a? Set
ports = Set.new(ports)
end
# Lolwut, #hash is inconsistent between ruby processes
"Beaker-#{Zlib.crc32(ports.inspect)}"
end
# Return an existing group, or create new one
#
# Accepts a VPC as input for checking & creation.
#
# @param vpc [Aws::EC2::VPC] the AWS vpc control object
# @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule
# @return [Aws::EC2::SecurityGroup] created security group
# @api private
def ensure_ping_group(vpc, sg_cidr_ips = ['0.0.0.0/0'])
@logger.notify("aws-sdk: Ensure security group exists that enables ping, create if not")
group = client.describe_security_groups(
:filters => [
{ :name => 'group-name', :values => [PING_SECURITY_GROUP_NAME] },
{ :name => 'vpc-id', :values => [vpc.vpc_id] },
]
).security_groups.first
if group.nil?
group = create_ping_group(vpc, sg_cidr_ips)
end
group
end
# Return an existing group, or create new one
#
# Accepts a VPC as input for checking & creation.
#
# @param vpc [Aws::EC2::VPC] the AWS vpc control object
# @param ports [Array<Number>] an array of port numbers
# @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule
# @return [Aws::EC2::SecurityGroup] created security group
# @api private
def ensure_group(vpc, ports, sg_cidr_ips = ['0.0.0.0/0'])
@logger.notify("aws-sdk: Ensure security group exists for ports #{ports.to_s}, create if not")
name = group_id(ports)
group = client.describe_security_groups(
:filters => [
{ :name => 'group-name', :values => [name] },
{ :name => 'vpc-id', :values => [vpc.vpc_id] },
]
).security_groups.first
if group.nil?
group = create_group(vpc, ports, sg_cidr_ips)
end
group
end
# Create a new ping enabled security group
#
# Accepts a region or VPC for group creation.
#
# @param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object
# @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule
# @return [Aws::EC2::SecurityGroup] created security group
# @api private
def create_ping_group(region_or_vpc, sg_cidr_ips = ['0.0.0.0/0'])
@logger.notify("aws-sdk: Creating group #{PING_SECURITY_GROUP_NAME}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => 'Custom Beaker security group to enable ping',
:group_name => PING_SECURITY_GROUP_NAME,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
sg_cidr_ips.each do |cidr_ip|
add_ingress_rule(
cl,
group,
cidr_ip,
'8', # 8 == ICMPv4 ECHO request
'-1', # -1 == All ICMP codes
'icmp',
)
end
group
end
# Create a new security group
#
# Accepts a region or VPC for group creation.
#
# @param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object
# @param ports [Array<Number>] an array of port numbers
# @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule
# @return [Aws::EC2::SecurityGroup] created security group
# @api private
def create_group(region_or_vpc, ports, sg_cidr_ips = ['0.0.0.0/0'])
name = group_id(ports)
@logger.notify("aws-sdk: Creating group #{name} for ports #{ports.to_s}")
@logger.notify("aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => "Custom Beaker security group for #{ports.to_a}",
:group_name => name,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
unless ports.is_a? Set
ports = Set.new(ports)
end
sg_cidr_ips.each do |cidr_ip|
ports.each do |port|
add_ingress_rule(cl, group, cidr_ip, port, port)
end
end
group
end
# Authorizes connections from certain CIDR to a range of ports
#
# @param cl [Aws::EC2::Client]
# @param sg_group [Aws::EC2::SecurityGroup] the AWS security group
# @param cidr_ip [String] CIDR used for outbound security group rule
# @param from_port [String] Starting Port number in the range
# @param to_port [String] Ending Port number in the range
# @return [void]
# @api private
# Return a hash containing AWS credentials
#
# @return [Hash<Symbol, String>] AWS credentials
# @api private
def load_credentials
return load_env_credentials if load_env_credentials.set?
load_fog_credentials(@options[:dot_fog])
end
# Return AWS credentials loaded from environment variables
#
# @param prefix [String] environment variable prefix
# @return [Aws::Credentials] ec2 credentials
# @api private
def load_env_credentials(prefix='AWS')
Aws::Credentials.new(
ENV["#{prefix}_ACCESS_KEY_ID"],
ENV["#{prefix}_SECRET_ACCESS_KEY"],
ENV["#{prefix}_SESSION_TOKEN"]
)
end
# Return a hash containing the fog credentials for EC2
#
# @param dot_fog [String] dot fog path
# @return [Aws::Credentials] ec2 credentials
# @api private
def load_fog_credentials(dot_fog = '.fog')
default = get_fog_credentials(dot_fog)
raise "You must specify an aws_access_key_id in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_access_key_id]
raise "You must specify an aws_secret_access_key in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_secret_access_key]
Aws::Credentials.new(
default[:aws_access_key_id],
default[:aws_secret_access_key],
default[:aws_session_token]
)
end
# Adds port 8143 to host[:additional_ports]
# if master, database and dashboard are not on same instance
def test_split_install
@hosts.each do |host|
mono_roles = ['master', 'database', 'dashboard']
roles_intersection = host[:roles] & mono_roles
if roles_intersection.size != 3 && roles_intersection.any?
host[:additional_ports] ? host[:additional_ports].push(8143) : host[:additional_ports] = [8143]
end
end
end
end
|
state-machines/state_machines | lib/state_machines/transition_collection.rb | StateMachines.AttributeTransitionCollection.rollback | ruby | def rollback
super
each {|transition| transition.machine.write(object, :event, transition.event) unless transition.transient?}
end | Resets the event attribute so it can be re-evaluated if attempted again | train | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition_collection.rb#L241-L244 | class AttributeTransitionCollection < TransitionCollection
def initialize(transitions = [], options = {}) #:nodoc:
super(transitions, {use_transactions: false, :actions => false}.merge(options))
end
private
# Hooks into running transition callbacks so that event / event transition
# attributes can be properly updated
def run_callbacks(index = 0)
if index == 0
# Clears any traces of the event attribute to prevent it from being
# evaluated multiple times if actions are nested
each do |transition|
transition.machine.write(object, :event, nil)
transition.machine.write(object, :event_transition, nil)
end
# Rollback only if exceptions occur during before callbacks
begin
super
rescue
rollback unless @before_run
@success = nil # mimics ActiveRecord.save behavior on rollback
raise
end
# Persists transitions on the object if partial transition was successful.
# This allows us to reference them later to complete the transition with
# after callbacks.
each {|transition| transition.machine.write(object, :event_transition, transition)} if skip_after && success?
else
super
end
end
# Tracks that before callbacks have now completed
def persist
@before_run = true
super
end
# Resets callback tracking
def reset
super
@before_run = false
end
# Resets the event attribute so it can be re-evaluated if attempted again
end
|
amatsuda/rfd | lib/rfd.rb | Rfd.Controller.unarchive | ruby | def unarchive
unless in_zip?
zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]}
zips.each do |item|
FileUtils.mkdir_p current_dir.join(item.basename)
Zip::File.open(item) do |zip|
zip.each do |entry|
FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s))
zip.extract(entry, File.join(item.basename, entry.to_s)) { true }
end
end
end
gzs.each do |item|
Zlib::GzipReader.open(item) do |gz|
Gem::Package::TarReader.new(gz) do |tar|
dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '')
tar.each do |entry|
dest = nil
if entry.full_name == '././@LongLink'
dest = File.join dest_dir, entry.read.strip
next
end
dest ||= File.join dest_dir, entry.full_name
if entry.directory?
FileUtils.mkdir_p dest, :mode => entry.header.mode
elsif entry.file?
FileUtils.mkdir_p dest_dir
File.open(dest, 'wb') {|f| f.print entry.read}
FileUtils.chmod entry.header.mode, dest
elsif entry.header.typeflag == '2' # symlink
File.symlink entry.header.linkname, dest
end
unless Dir.exist? dest_dir
FileUtils.mkdir_p dest_dir
File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read}
end
end
end
end
end
else
Zip::File.open(current_zip) do |zip|
zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry|
FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s))
zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true }
end
end
end
ls
end | Unarchive .zip and .tar.gz files within selected files and directories into current_directory. | train | https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L533-L582 | class Controller
include Rfd::Commands
attr_reader :header_l, :header_r, :main, :command_line, :items, :displayed_items, :current_row, :current_page, :current_dir, :current_zip
# :nodoc:
def initialize
@main = MainWindow.new
@header_l = HeaderLeftWindow.new
@header_r = HeaderRightWindow.new
@command_line = CommandLineWindow.new
@debug = DebugWindow.new if ENV['DEBUG']
@direction, @dir_history, @last_command, @times, @yanked_items = nil, [], nil, nil, nil
end
# The main loop.
def run
loop do
begin
number_pressed = false
ret = case (c = Curses.getch)
when 10, 13 # enter, return
enter
when 27 # ESC
q
when ' ' # space
space
when 127 # DEL
del
when Curses::KEY_DOWN
j
when Curses::KEY_UP
k
when Curses::KEY_LEFT
h
when Curses::KEY_RIGHT
l
when Curses::KEY_CTRL_A..Curses::KEY_CTRL_Z
chr = ((c - 1 + 65) ^ 0b0100000).chr
public_send "ctrl_#{chr}" if respond_to?("ctrl_#{chr}")
when ?0..?9
public_send c
number_pressed = true
when ?!..?~
if respond_to? c
public_send c
else
debug "key: #{c}" if ENV['DEBUG']
end
when Curses::KEY_MOUSE
if (mouse_event = Curses.getmouse)
case mouse_event.bstate
when Curses::BUTTON1_CLICKED
click y: mouse_event.y, x: mouse_event.x
when Curses::BUTTON1_DOUBLE_CLICKED
double_click y: mouse_event.y, x: mouse_event.x
end
end
else
debug "key: #{c}" if ENV['DEBUG']
end
Curses.doupdate if ret
@times = nil unless number_pressed
rescue StopIteration
raise
rescue => e
command_line.show_error e.to_s
raise if ENV['DEBUG']
end
end
ensure
Curses.close_screen
end
# Change the number of columns in the main window.
def spawn_panes(num)
main.number_of_panes = num
@current_row = @current_page = 0
end
# Number of times to repeat the next command.
def times
(@times || 1).to_i
end
# The file or directory on which the cursor is on.
def current_item
items[current_row]
end
# * marked files and directories.
def marked_items
items.select(&:marked?)
end
# Marked files and directories or Array(the current file or directory).
#
# . and .. will not be included.
def selected_items
((m = marked_items).any? ? m : Array(current_item)).reject {|i| %w(. ..).include? i.name}
end
# Move the cursor to specified row.
#
# The main window and the headers will be updated reflecting the displayed files and directories.
# The row number can be out of range of the current page.
def move_cursor(row = nil)
if row
if (prev_item = items[current_row])
main.draw_item prev_item
end
page = row / max_items
switch_page page if page != current_page
main.activate_pane row / maxy
@current_row = row
else
@current_row = 0
end
item = items[current_row]
main.draw_item item, current: true
main.display current_page
header_l.draw_current_file_info item
@current_row
end
# Change the current directory.
def cd(dir = '~', pushd: true)
dir = load_item path: expand_path(dir) unless dir.is_a? Item
unless dir.zip?
Dir.chdir dir
@current_zip = nil
else
@current_zip = dir
end
@dir_history << current_dir if current_dir && pushd
@current_dir, @current_page, @current_row = dir, 0, nil
main.activate_pane 0
ls
@current_dir
end
# cd to the previous directory.
def popd
cd @dir_history.pop, pushd: false if @dir_history.any?
end
# Fetch files from current directory.
# Then update each windows reflecting the newest information.
def ls
fetch_items_from_filesystem_or_zip
sort_items_according_to_current_direction
@current_page ||= 0
draw_items
move_cursor (current_row ? [current_row, items.size - 1].min : nil)
draw_marked_items
draw_total_items
true
end
# Sort the whole files and directories in the current directory, then refresh the screen.
#
# ==== Parameters
# * +direction+ - Sort order in a String.
# nil : order by name
# r : reverse order by name
# s, S : order by file size
# sr, Sr: reverse order by file size
# t : order by mtime
# tr : reverse order by mtime
# c : order by ctime
# cr : reverse order by ctime
# u : order by atime
# ur : reverse order by atime
# e : order by extname
# er : reverse order by extname
def sort(direction = nil)
@direction, @current_page = direction, 0
sort_items_according_to_current_direction
switch_page 0
move_cursor 0
end
# Change the file permission of the selected files and directories.
#
# ==== Parameters
# * +mode+ - Unix chmod string (e.g. +w, g-r, 755, 0644)
def chmod(mode = nil)
return unless mode
begin
Integer mode
mode = Integer mode.size == 3 ? "0#{mode}" : mode
rescue ArgumentError
end
FileUtils.chmod mode, selected_items.map(&:path)
ls
end
# Change the file owner of the selected files and directories.
#
# ==== Parameters
# * +user_and_group+ - user name and group name separated by : (e.g. alice, nobody:nobody, :admin)
def chown(user_and_group)
return unless user_and_group
user, group = user_and_group.split(':').map {|s| s == '' ? nil : s}
FileUtils.chown user, group, selected_items.map(&:path)
ls
end
# Fetch files from current directory or current .zip file.
def fetch_items_from_filesystem_or_zip
unless in_zip?
@items = Dir.foreach(current_dir).map {|fn|
load_item dir: current_dir, name: fn
}.to_a.partition {|i| %w(. ..).include? i.name}.flatten
else
@items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)),
load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))]
zf = Zip::File.new current_dir
zf.each {|entry|
next if entry.name_is_directory?
stat = zf.file.stat entry.name
@items << load_item(dir: current_dir, name: entry.name, stat: stat)
}
end
end
# Focus at the first file or directory of which name starts with the given String.
def find(str)
index = items.index {|i| i.index > current_row && i.name.start_with?(str)} || items.index {|i| i.name.start_with? str}
move_cursor index if index
end
# Focus at the last file or directory of which name starts with the given String.
def find_reverse(str)
index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str}
move_cursor items.size - index - 1 if index
end
# Height of the currently active pane.
def maxy
main.maxy
end
# Number of files or directories that the current main window can show in a page.
def max_items
main.max_items
end
# Update the main window with the loaded files and directories. Also update the header.
def draw_items
main.newpad items
@displayed_items = items[current_page * max_items, max_items]
main.display current_page
header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages
end
# Sort the loaded files and directories in already given sort order.
def sort_items_according_to_current_direction
case @direction
when nil
@items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort)
when 'r'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse}
when 'S', 's'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}}
when 'Sr', 'sr'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)}
when 't'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}}
when 'tr'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)}
when 'c'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}}
when 'cr'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)}
when 'u'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}}
when 'ur'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)}
when 'e'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}}
when 'er'
@items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)}
end
items.each.with_index {|item, index| item.index = index}
end
# Search files and directories from the current directory, and update the screen.
#
# * +pattern+ - Search pattern against file names in Ruby Regexp string.
#
# === Example
#
# a : Search files that contains the letter "a" in their file name
# .*\.pdf$ : Search PDF files
def grep(pattern = '.*')
regexp = Regexp.new(pattern)
fetch_items_from_filesystem_or_zip
@items = items.shift(2) + items.select {|i| i.name =~ regexp}
sort_items_according_to_current_direction
draw_items
draw_total_items
switch_page 0
move_cursor 0
end
# Copy selected files and directories to the destination.
def cp(dest)
unless in_zip?
src = (m = marked_items).any? ? m.map(&:path) : current_item
FileUtils.cp_r src, expand_path(dest)
else
raise 'cping multiple items in .zip is not supported.' if selected_items.size > 1
Zip::File.open(current_zip) do |zip|
entry = zip.find_entry(selected_items.first.name).dup
entry.name, entry.name_length = dest, dest.size
zip.instance_variable_get(:@entry_set) << entry
end
end
ls
end
# Move selected files and directories to the destination.
def mv(dest)
unless in_zip?
src = (m = marked_items).any? ? m.map(&:path) : current_item
FileUtils.mv src, expand_path(dest)
else
raise 'mving multiple items in .zip is not supported.' if selected_items.size > 1
rename "#{selected_items.first.name}/#{dest}"
end
ls
end
# Rename selected files and directories.
#
# ==== Parameters
# * +pattern+ - new filename, or a shash separated Regexp like string
def rename(pattern)
from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/'
if to.nil?
from, to = current_item.name, from
else
from = Regexp.new from
end
unless in_zip?
selected_items.each do |item|
name = item.name.gsub from, to
FileUtils.mv item, current_dir.join(name) if item.name != name
end
else
Zip::File.open(current_zip) do |zip|
selected_items.each do |item|
name = item.name.gsub from, to
zip.rename item.name, name
end
end
end
ls
end
# Soft delete selected files and directories.
#
# If the OS is not OSX, performs the same as `delete` command.
def trash
unless in_zip?
if osx?
FileUtils.mv selected_items.map(&:path), File.expand_path('~/.Trash/')
else
#TODO support other OS
FileUtils.rm_rf selected_items.map(&:path)
end
else
return unless ask %Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)]
delete
end
@current_row -= selected_items.count {|i| i.index <= current_row}
ls
end
# Delete selected files and directories.
def delete
unless in_zip?
FileUtils.rm_rf selected_items.map(&:path)
else
Zip::File.open(current_zip) do |zip|
zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry|
if entry.name_is_directory?
zip.dir.delete entry.to_s
else
zip.file.delete entry.to_s
end
end
end
end
@current_row -= selected_items.count {|i| i.index <= current_row}
ls
end
# Create a new directory.
def mkdir(dir)
unless in_zip?
FileUtils.mkdir_p current_dir.join(dir)
else
Zip::File.open(current_zip) do |zip|
zip.dir.mkdir dir
end
end
ls
end
# Create a new empty file.
def touch(filename)
unless in_zip?
FileUtils.touch current_dir.join(filename)
else
Zip::File.open(current_zip) do |zip|
# zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file
zip.instance_variable_get(:@entry_set) << Zip::Entry.new(current_zip, filename)
end
end
ls
end
# Create a symlink to the current file or directory.
def symlink(name)
FileUtils.ln_s current_item, name
ls
end
# Yank selected file / directory names.
def yank
@yanked_items = selected_items
end
# Paste yanked files / directories here.
def paste
if @yanked_items
if current_item.directory?
FileUtils.cp_r @yanked_items.map(&:path), current_item
else
@yanked_items.each do |item|
if items.include? item
i = 1
while i += 1
new_item = load_item dir: current_dir, name: "#{item.basename}_#{i}#{item.extname}", stat: item.stat
break unless File.exist? new_item.path
end
FileUtils.cp_r item, new_item
else
FileUtils.cp_r item, current_dir
end
end
end
ls
end
end
# Copy selected files and directories' path into clipboard on OSX.
def clipboard
IO.popen('pbcopy', 'w') {|f| f << selected_items.map(&:path).join(' ')} if osx?
end
# Archive selected files and directories into a .zip file.
def zip(zipfile_name)
return unless zipfile_name
zipfile_name += '.zip' unless zipfile_name.end_with? '.zip'
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
selected_items.each do |item|
next if item.symlink?
if item.directory?
Dir[item.join('**/**')].each do |file|
zipfile.add file.sub("#{current_dir}/", ''), file
end
else
zipfile.add item.name, item
end
end
end
ls
end
# Unarchive .zip and .tar.gz files within selected files and directories into current_directory.
# Current page is the first page?
def first_page?
current_page == 0
end
# Do we have more pages?
def last_page?
current_page == total_pages - 1
end
# Number of pages in the current directory.
def total_pages
(items.size - 1) / max_items + 1
end
# Move to the given page number.
#
# ==== Parameters
# * +page+ - Target page number
def switch_page(page)
main.display (@current_page = page)
@displayed_items = items[current_page * max_items, max_items]
header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages
end
# Update the header information concerning currently marked files or directories.
def draw_marked_items
items = marked_items
header_r.draw_marked_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size}
end
# Update the header information concerning total files and directories in the current directory.
def draw_total_items
header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size}
end
# Swktch on / off marking on the current file or directory.
def toggle_mark
main.toggle_mark current_item
end
# Get a char as a String from user input.
def get_char
c = Curses.getch
c if (0..255) === c.ord
end
def clear_command_line
command_line.writeln 0, ""
command_line.clear
command_line.noutrefresh
end
# Accept user input, and directly execute it as a Ruby method call to the controller.
#
# ==== Parameters
# * +preset_command+ - A command that would be displayed at the command line before user input.
def process_command_line(preset_command: nil)
prompt = preset_command ? ":#{preset_command} " : ':'
command_line.set_prompt prompt
cmd, *args = command_line.get_command(prompt: prompt).split(' ')
if cmd && !cmd.empty? && respond_to?(cmd)
ret = self.public_send cmd, *args
clear_command_line
ret
end
rescue Interrupt
clear_command_line
end
# Accept user input, and directly execute it in an external shell.
def process_shell_command
command_line.set_prompt ':!'
cmd = command_line.get_command(prompt: ':!')[1..-1]
execute_external_command pause: true do
system cmd
end
rescue Interrupt
ensure
command_line.clear
command_line.noutrefresh
end
# Let the user answer y or n.
#
# ==== Parameters
# * +prompt+ - Prompt message
def ask(prompt = '(y/n)')
command_line.set_prompt prompt
command_line.refresh
while (c = Curses.getch)
next unless [?N, ?Y, ?n, ?y, 3, 27] .include? c # N, Y, n, y, ^c, esc
command_line.clear
command_line.noutrefresh
break (c == 'y') || (c == 'Y')
end
end
# Open current file or directory with the editor.
def edit
execute_external_command do
editor = ENV['EDITOR'] || 'vim'
unless in_zip?
system %Q[#{editor} "#{current_item.path}"]
else
begin
tmpdir, tmpfile_name = nil
Zip::File.open(current_zip) do |zip|
tmpdir = Dir.mktmpdir
FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name))
tmpfile_name = File.join(tmpdir, current_item.name)
File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)}
system %Q[#{editor} "#{tmpfile_name}"]
zip.add(current_item.name, tmpfile_name) { true }
end
ls
ensure
FileUtils.remove_entry_secure tmpdir if tmpdir
end
end
end
end
# Open current file or directory with the viewer.
def view
pager = ENV['PAGER'] || 'less'
execute_external_command do
unless in_zip?
system %Q[#{pager} "#{current_item.path}"]
else
begin
tmpdir, tmpfile_name = nil
Zip::File.open(current_zip) do |zip|
tmpdir = Dir.mktmpdir
FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name))
tmpfile_name = File.join(tmpdir, current_item.name)
File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)}
end
system %Q[#{pager} "#{tmpfile_name}"]
ensure
FileUtils.remove_entry_secure tmpdir if tmpdir
end
end
end
end
def move_cursor_by_click(y: nil, x: nil)
if (idx = main.pane_index_at(y: y, x: x))
row = current_page * max_items + main.maxy * idx + y - main.begy
move_cursor row if (row >= 0) && (row < items.size)
end
end
private
def execute_external_command(pause: false)
Curses.def_prog_mode
Curses.close_screen
yield
ensure
Curses.reset_prog_mode
Curses.getch if pause
#NOTE needs to draw borders and ls again here since the stdlib Curses.refresh fails to retrieve the previous screen
Rfd::Window.draw_borders
Curses.refresh
ls
end
def expand_path(path)
File.expand_path path.start_with?('/', '~') ? path : current_dir ? current_dir.join(path) : path
end
def load_item(path: nil, dir: nil, name: nil, stat: nil)
Item.new dir: dir || File.dirname(path), name: name || File.basename(path), stat: stat, window_width: main.width
end
def osx?
@_osx ||= RbConfig::CONFIG['host_os'] =~ /darwin/
end
def in_zip?
@current_zip
end
def debug(str)
@debug.debug str
end
end
|
phallguy/scorpion | lib/scorpion/hunt.rb | Scorpion.Hunt.inject | ruby | def inject( object )
trip.object = object
object.send :scorpion_hunt=, self
object.injected_attributes.each do |attr|
next if object.send "#{ attr.name }?"
next if attr.lazy?
object.send :inject_dependency, attr, fetch( attr.contract )
end
object.send :on_injected
object
end | Inject given `object` with its expected dependencies.
@param [Scorpion::Object] object to be injected.
@return [Scorpion::Object] the injected object. | train | https://github.com/phallguy/scorpion/blob/0bc9c1111a37e35991d48543dec88a36f16d7aee/lib/scorpion/hunt.rb#L80-L94 | class Hunt
extend Forwardable
# ============================================================================
# @!group Attributes
#
# @!attribute
# @return [Scorpion] scorpion used to fetch uncaptured dependency.
attr_reader :scorpion
# @!attribute
# @return [Array<Array>] the stack of trips conducted by the hunt to help
# resolve child dependencies.
attr_reader :trips
private :trips
# @!attribute
# @return [Trip] the current hunting trip.
attr_reader :trip
private :trip
delegate [:contract, :arguments, :block] => :trip
# @!attribute contract
# @return [Class,Module,Symbol] contract being hunted for.
# @!attribute [r] arguments
# @return [Array<Object>] positional arguments to pass to the initializer of {#contract} when found.
# @!attribute block
# @return [#call] block to pass to constructor of contract when found.
#
# @!endgroup Attributes
def initialize( scorpion, contract, *arguments, &block )
@scorpion = scorpion
@trips = []
@trip = Trip.new contract, arguments, block
end
# Hunt for additional dependency to satisfy the main hunt's contract.
# @see Scorpion#hunt
def fetch( contract, *arguments, &block )
push contract, arguments, block
execute
ensure
pop
end
# Inject given `object` with its expected dependencies.
# @param [Scorpion::Object] object to be injected.
# @return [Scorpion::Object] the injected object.
# Allow the hunt to spawn objects.
# @see Scorpion#spawn
def spawn( klass, *arguments, &block )
scorpion.spawn( self, klass, *arguments, &block )
end
alias_method :new, :spawn
private
def execute
execute_from_trips || execute_from_scorpion
end
def execute_from_trips
trips.each do |trip|
if resolved = execute_from_trip( trip )
return resolved
end
end
nil
end
def execute_from_trip( trip )
return unless obj = trip.object
return obj if contract === obj
# If we have already resolved an instance of this contract in this
# hunt, then return that same object.
if obj.is_a? Scorpion::Object
obj.injected_attributes.each do |attr|
next unless attr.contract == contract
return obj.send( attr.name ) if obj.send( :"#{ attr.name }?" )
end
end
nil
end
def execute_from_scorpion
scorpion.execute self
end
def push( contract, arguments, block )
trips.push trip
@trip = Trip.new contract, arguments, block
end
def pop
@trip = trips.pop
end
class Trip
attr_reader :contract
attr_reader :arguments
attr_reader :block
attr_accessor :object
def initialize( contract, arguments, block )
@contract = contract
@arguments = arguments
@block = block
end
end
class InitializerTrip < Trip; end
end
|
FormAPI/formapi-ruby | lib/form_api/api_client.rb | FormAPI.ApiClient.call_api | ruby | def call_api(http_method, path, opts = {})
request = build_request(http_method, path, opts)
response = request.run
if @config.debugging
@config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
if response.timed_out?
fail ApiError.new('Connection timed out')
elsif response.code == 0
# Errors from libcurl will be made visible here
fail ApiError.new(:code => 0,
:message => response.return_message)
else
exception_message = nil
response_json = JSON.parse(response.body) rescue nil
if response_json.is_a? Hash
if response_json['errors'].is_a? Array
response_errors = response_json['errors'].join(', ')
elsif response_json['error']
response_errors = response_json['error']
end
if response_errors
exception_message = "#{response.status_message}: #{response_errors}"
end
end
unless exception_message
exception_message = "#{response.status_message}: [Could not parse errors from response body]"
end
fail ApiError.new(:code => response.code,
:response_headers => response.headers,
:response_body => response.body),
exception_message
end
end
if opts[:return_type]
data = deserialize(response, opts[:return_type])
else
data = nil
end
return data, response.code, response.headers
end | Call an API with given options.
@return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
the data deserialized from response body (could be nil), response status code and response headers. | train | https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api_client.rb#L49-L95 | class ApiClient
# The Configuration object holding settings to be used in the API client.
attr_accessor :config
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Initializes the ApiClient
# @option config [Configuration] Configuration for initializing the object, default to Configuration.default
def initialize(config = Configuration.default)
@config = config
@user_agent = "formapi-ruby-#{VERSION}"
@default_headers = {
'Content-Type' => 'application/json',
'User-Agent' => @user_agent
}
end
def self.default
@@default ||= ApiClient.new
end
# Call an API with given options.
#
# @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
# the data deserialized from response body (could be nil), response status code and response headers.
# Builds the HTTP request
#
# @param [String] http_method HTTP method/verb (e.g. POST)
# @param [String] path URL path (e.g. /account/new)
# @option opts [Hash] :header_params Header parameters
# @option opts [Hash] :query_params Query parameters
# @option opts [Hash] :form_params Query parameters
# @option opts [Object] :body HTTP body (JSON/XML)
# @return [Typhoeus::Request] A Typhoeus Request
def build_request(http_method, path, opts = {})
url = build_request_url(path)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {})
query_params = opts[:query_params] || {}
form_params = opts[:form_params] || {}
update_params_for_auth! header_params, query_params, opts[:auth_names]
# set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
_verify_ssl_host = @config.verify_ssl_host ? 2 : 0
req_opts = {
:method => http_method,
:headers => header_params,
:params => query_params,
:params_encoding => @config.params_encoding,
:timeout => @config.timeout,
:ssl_verifypeer => @config.verify_ssl,
:ssl_verifyhost => _verify_ssl_host,
:sslcert => @config.cert_file,
:sslkey => @config.key_file,
:verbose => @config.debugging
}
# set custom cert, if provided
req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
if [:post, :patch, :put, :delete].include?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update :body => req_body
if @config.debugging
@config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
end
end
request = Typhoeus::Request.new(url, req_opts)
download_file(request) if opts[:return_type] == 'File'
request
end
# Check if the given MIME is a JSON MIME.
# JSON MIME examples:
# application/json
# application/json; charset=UTF8
# APPLICATION/JSON
# */*
# @param [String] mime MIME
# @return [Boolean] True if the MIME is application/json
def json_mime?(mime)
(mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
end
# Deserialize the response to the given return type.
#
# @param [Response] response HTTP response
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
return @tempfile if return_type == 'File'
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == 'String'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
# @param [Object] data Data to be converted
# @param [String] return_type Return type
# @return [Mixed] Data in a particular type
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object (usually a Hash), return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map { |item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
FormAPI.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
# The response body is written to the file in chunks in order to handle files which
# size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
# process can use.
#
# @see Configuration#temp_folder_path
def download_file(request)
tempfile = nil
encoding = nil
request.on_headers do |response|
content_disposition = response.headers['Content-Disposition']
if content_disposition && content_disposition =~ /filename=/i
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
prefix = sanitize_filename(filename)
else
prefix = 'download-'
end
prefix = prefix + '-' unless prefix.end_with?('-')
encoding = response.body.encoding
tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
@tempfile = tempfile
end
request.on_body do |chunk|
chunk.force_encoding(encoding)
tempfile.write(chunk)
end
request.on_complete do |response|
tempfile.close if tempfile
@config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
"with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
"will be deleted automatically with GC. It's also recommended to delete the temp file "\
"explicitly with `tempfile.delete`"
end
end
# Sanitize filename by removing path.
# e.g. ../../sun.gif becomes sun.gif
#
# @param [String] filename the filename to be sanitized
# @return [String] the sanitized filename
def sanitize_filename(filename)
filename.gsub(/.*[\/\\]/, '')
end
def build_request_url(path)
# Add leading and trailing slashes to path
path = "/#{path}".gsub(/\/+/, '/')
URI.encode(@config.base_url + path)
end
# Builds the HTTP request body
#
# @param [Hash] header_params Header parameters
# @param [Hash] form_params Query parameters
# @param [Object] body HTTP body (JSON/XML)
# @return [String] HTTP body data in the form of string
def build_request_body(header_params, form_params, body)
# http form
if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
header_params['Content-Type'] == 'multipart/form-data'
data = {}
form_params.each do |key, value|
case value
when ::File, ::Array, nil
# let typhoeus handle File, Array and nil parameters
data[key] = value
else
data[key] = value.to_s
end
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
# Update hearder and query params based on authentication settings.
#
# @param [Hash] header_params Header parameters
# @param [Hash] query_params Query parameters
# @param [String] auth_names Authentication scheme name
def update_params_for_auth!(header_params, query_params, auth_names)
Array(auth_names).each do |auth_name|
auth_setting = @config.auth_settings[auth_name]
next unless auth_setting
case auth_setting[:in]
when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
else fail ArgumentError, 'Authentication token must be in `query` of `header`'
end
end
end
# Sets user agent in HTTP header
#
# @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
def user_agent=(user_agent)
@user_agent = user_agent
@default_headers['User-Agent'] = @user_agent
end
# Return Accept header based on an array of accepts provided.
# @param [Array] accepts array for Accept
# @return [String] the Accept header (e.g. application/json)
def select_header_accept(accepts)
return nil if accepts.nil? || accepts.empty?
# use JSON when present, otherwise use all of the provided
json_accept = accepts.find { |s| json_mime?(s) }
json_accept || accepts.join(',')
end
# Return Content-Type header based on an array of content types provided.
# @param [Array] content_types array for Content-Type
# @return [String] the Content-Type header (e.g. application/json)
def select_header_content_type(content_types)
# use application/json by default
return 'application/json' if content_types.nil? || content_types.empty?
# use JSON when present, otherwise use the first one
json_content_type = content_types.find { |s| json_mime?(s) }
json_content_type || content_types.first
end
# Convert object (array, hash, object, etc) to JSON string.
# @param [Object] model object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_http_body(model)
return model if model.nil? || model.is_a?(String)
local_body = nil
if model.is_a?(Array)
local_body = model.map { |m| object_to_hash(m) }
else
local_body = object_to_hash(model)
end
local_body.to_json
end
# Convert object(non-array) to hash.
# @param [Object] obj object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_hash(obj)
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
# Build parameter value according to the given collection format.
# @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
def build_collection_param(param, collection_format)
case collection_format
when :csv
param.join(',')
when :ssv
param.join(' ')
when :tsv
param.join("\t")
when :pipes
param.join('|')
when :multi
# return the array directly as typhoeus will handle it as expected
param
else
fail "unknown collection format: #{collection_format.inspect}"
end
end
end
|
rakeoe/rakeoe | lib/rakeoe/toolchain.rb | RakeOE.Toolchain.dep | ruby | def dep(params = {})
extension = File.extname(params[:source])
dep = params[:dep]
source = params[:source]
incs = compiler_incs_for(params[:includes]) + " #{@settings['LIB_INC']}"
case
when cpp_source_extensions.include?(extension)
flags = @settings['CXXFLAGS'] + ' ' + params[:settings]['ADD_CXXFLAGS']
compiler = "#{@settings['CXX']} -x c++ "
when c_source_extensions.include?(extension)
flags = @settings['CFLAGS'] + ' ' + params[:settings]['ADD_CFLAGS']
compiler = "#{@settings['CC']} -x c "
when as_source_extensions.include?(extension)
flags = ''
compiler = "#{@settings['AS']}"
else
raise "unsupported source file extension (#{extension}) for creating dependency!"
end
sh "#{compiler} -MM #{flags} #{incs} -c #{source} -MT #{dep.ext('.o')} -MF #{dep}", silent: true
end | Creates dependency
@param [Hash] params
@option params [String] :source source filename with path
@option params [String] :dep dependency filename path
@option params [Hash] :settings project specific settings
@option params [Array] :includes include paths used | train | https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L434-L453 | class Toolchain
attr_reader :qt, :settings, :target, :config
# Initializes object
#
# @param [RakeOE::Config] config Project wide configurations
#
def initialize(config)
raise 'Configuration failure' unless config.checks_pass?
@config = config
begin
@kvr = KeyValueReader.new(config.platform)
rescue Exception => e
puts e.message
raise
end
@settings = @kvr.env
fixup_env
# save target platform of our compiler (gcc specific)
if RbConfig::CONFIG["host_os"] != "mingw32"
@target=`export PATH=#{@settings['PATH']} && #{@settings['CC']} -dumpmachine`.chop
else
@target=`PATH = #{@settings['PATH']} & #{@settings['CC']} -dumpmachine`.chop
end
# XXX DS: we should only instantiate @qt if we have any qt settings
@qt = QtSettings.new(self)
set_build_vars()
init_test_frameworks
sanity
end
# Do some sanity checks
def sanity
# TODO DS: check if libs and apps directories exist
# TODO DS: check if test frameworks exist
# check if target is valid
if @settings['CC'].empty?
raise "No Compiler specified. Either add platform configuration via RakeOE::Config object in Rakefile or use TOOLCHAIN_ENV environment variable"
end
if @target.nil? || @target.empty?
raise "Compiler #{@settings['CC']} does not work. Fix platform settings or use TOOLCHAIN_ENV environment variable "
end
end
# returns the build directory
def build_dir
"#{@config.directories[:build]}/#{@target}/#{@config.release}"
end
# Initializes definitions for test framework
# TODO: Add possibility to configure test framework specific CFLAGS/CXXFLAGS
def init_test_frameworks()
@@test_framework ||= Hash.new
config_empty_test_framework
if @config.test_fw.size > 0
if PrjFileCache.contain?('LIB', @config.test_fw)
@@test_framework[@config.test_fw] = TestFramework.new(:name => @config.test_fw,
:binary_path => "#{@settings['LIB_OUT']}/lib#{@config.test_fw}.a",
:include_dir => PrjFileCache.exported_lib_incs(@config.test_fw),
:cflags => '')
else
puts "WARNING: Configured test framework (#{@config.test_fw}) does not exist in project!"
end
end
end
# Configures empty test framework
def config_empty_test_framework
@@test_framework[''] = TestFramework.new(:name => '',
:binary_path => '',
:include_dir => '',
:cflags => '')
end
# Returns default test framework or nil if none defined
def default_test_framework
test_framework(@config.test_fw) || test_framework('')
end
# Returns definitions of specific test framework or none if
# specified test framework doesn't exist
def test_framework(name)
@@test_framework[name]
end
# Returns list of all registered test framework names
def test_frameworks
@@test_framework.keys
end
# returns library project setting
def lib_setting(name, setting)
@libs.get(name, setting)
end
# returns app project setting
def app_setting(name, setting)
@apps.get(name, setting)
end
# returns c++ source extensions
def cpp_source_extensions
(@config.suffixes[:cplus_sources] + [@config.suffixes[:moc_source]]).uniq
end
# returns c source extensions
def c_source_extensions
@config.suffixes[:c_sources].uniq
end
# returns assembler source extensions
def as_source_extensions
@config.suffixes[:as_sources].uniq
end
# returns all source extensions
def source_extensions
cpp_source_extensions + c_source_extensions + as_source_extensions
end
# returns c++ header extensions
def cpp_header_extensions
(@config.suffixes[:cplus_headers] + [@config.suffixes[:moc_header]]).uniq
end
# returns c header extensions
def c_header_extensions
@config.suffixes[:c_headers].uniq
end
# returns moc header extensions
def moc_header_extension
@config.suffixes[:moc_header]
end
# returns c++ header extensions
def moc_source
@config.suffixes[:moc_source]
end
# Specific fixups for toolchain
def fixup_env
# set system PATH if no PATH defined
@settings['PATH'] ||= ENV['PATH']
# replace $PATH
@settings['PATH'] = @settings['PATH'].gsub('$PATH', ENV['PATH'])
# create ARCH
@settings['ARCH'] = "#{@settings['TARGET_PREFIX']}".chop
# remove optimizations, we set these explicitly
@settings['CXXFLAGS'] = "#{@settings['CXXFLAGS']} -DPROGRAM_VERSION=\\\"#{@config.sw_version}\\\"".gsub('-O2', '')
@settings['CFLAGS'] = "#{@settings['CFLAGS']} -DPROGRAM_VERSION=\\\"#{@config.sw_version}\\\"".gsub('-O2', '')
KeyValueReader.substitute_dollar_symbols!(@settings)
end
# Set common build variables
#
def set_build_vars
warning_flags = ' -W -Wall'
if 'release' == @config.release
optimization_flags = " #{@config.optimization_release} -DRELEASE"
else
optimization_flags = " #{@config.optimization_dbg} -g"
end
# we could make these also arrays of source directories ...
@settings['APP_SRC_DIR'] = 'src/app'
@settings['LIB_SRC_DIR'] = 'src/lib'
# derived settings
@settings['BUILD_DIR'] = "#{build_dir}"
@settings['LIB_OUT'] = "#{@settings['BUILD_DIR']}/libs"
@settings['APP_OUT'] = "#{@settings['BUILD_DIR']}/apps"
unless @settings['OECORE_TARGET_SYSROOT'].nil? || @settings['OECORE_TARGET_SYSROOT'].empty?
@settings['SYS_LFLAGS'] = "-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib"
end
# set LD_LIBRARY_PATH
@settings['LD_LIBRARY_PATH'] = @settings['LIB_OUT']
# standard settings
@settings['CXXFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_cpp}"
@settings['CFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_c}"
if @settings['PRJ_TYPE'] == 'SOLIB'
@settings['CXXFLAGS'] += ' -fPIC'
@settings['CFLAGS'] += ' -fPIC'
end
# !! don't change order of the following string components without care !!
@settings['LDFLAGS'] = @settings['LDFLAGS'] + " -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group"
end
# Executes the command
def sh(cmd, silent = false)
if RbConfig::CONFIG["host_os"] != "mingw32"
full_cmd = "export PATH=#{@settings['PATH']} && #{cmd}"
else
full_cmd = "PATH = #{@settings['PATH']} & #{cmd}"
end
if silent
system full_cmd
else
Rake::sh full_cmd
end
end
# Removes list of given files
# @param [String] files List of files to be deleted
def rm(files)
if files
RakeFileUtils.rm_f(files) unless files.empty?
end
end
# Executes a given binary
#
# @param [String] binary Absolute path of the binary to be executed
#
def run(binary)
# compare ruby platform config and our target setting
if @target[RbConfig::CONFIG["target_cpu"]]
system "export LD_LIBRARY_PATH=#{@settings['LD_LIBRARY_PATH']} && #{binary}"
else
puts "Warning: Can't execute on this platform: #{binary}"
end
end
# Executes a given test binary with test runner specific parameter(s)
#
# @param [String] binary Absolute path of the binary to be executed
#
def run_junit_test(binary)
# compare ruby platform config and our target setting
if @target[RbConfig::CONFIG["target_cpu"]]
system "export LD_LIBRARY_PATH=#{@settings['LD_LIBRARY_PATH']} && #{binary} -o junit"
else
puts "Warning: Can't execute test on this platform: #{binary}"
end
end
# Tests given list of platforms if any of those matches the current platform
def current_platform_any?(platforms)
([@target] & platforms).any?
end
# Generates compiler include line from given include path list
#
# @param [Array] paths Paths to be used for include file search
#
# @return [String] Compiler include line
#
def compiler_incs_for(paths)
paths.each_with_object('') {|path, str| str << " -I#{path}"}
end
# Generates linker line from given library list.
# The linker line normally will be like -l<lib1> -l<lib2>, ...
#
# If a library has specific platform specific setting in the platform file
# with a specific -l<lib> alternative, this will be used instead.
#
# @param [Array] libs Libraries to be used for linker line
#
# @return [String] Linker line
#
def linker_line_for(libs)
return '' if (libs.nil? || libs.empty?)
libs.map do |lib|
settings = platform_settings_for(lib)
if settings[:LDFLAGS].nil? || settings[:LDFLAGS].empty?
# automatic linker line if no platform specific LDFLAGS exist
"-l#{lib}"
else
# only matches -l<libname> settings
/(\s|^)+-l\S+/.match(settings[:LDFLAGS]).to_s
end
end.join(' ').strip
end
# Reduces the given list of libraries to bare minimum, i.e.
# the minimum needed for actual platform
#
# @libs list of libraries
#
# @return reduced list of libraries
#
def reduce_libs_to_bare_minimum(libs)
rv = libs.clone
lib_entries = RakeOE::PrjFileCache.get_lib_entries(libs)
lib_entries.each_pair do |lib, entry|
rv.delete(lib) unless RakeOE::PrjFileCache.project_entry_buildable?(entry, @target)
end
rv
end
# Return array of library prerequisites for given file
def libs_for_binary(a_binary, visited=[])
return [] if visited.include?(a_binary)
visited << a_binary
pre = Rake::Task[a_binary].prerequisites
rv = []
pre.each do |p|
next if (File.extname(p) != '.a') && (File.extname(p) != '.so')
next if p =~ /\-app\.a/
rv << File.basename(p).gsub(/(\.a|\.so|^lib)/, '')
rv += libs_for_binary(p, visited) # Recursive call
end
reduce_libs_to_bare_minimum(rv.uniq)
end
# Touches a file
def touch(file)
RakeFileUtils.touch(file)
end
# Tests if all given files in given list exist
# @return true all file exist
# @return false not all file exist
def test_all_files_exist?(files)
files.each do |file|
raise "No such file: #{file}" unless File.exist?(file)
end
end
def diagnose_buildability(projects)
projects.each do |project|
RakeOE::PrjFileCache.project_entry_buildable?(entry, platform)
end
end
# Returns platform specific settings of a resource (APP/LIB/SOLIB or external resource like e.g. an external library)
# as a hash with the keys CFLAGS, CXXFLAGS and LDFLAGS. The values are empty if no such resource settings exist inside
# the platform file. The resulting hash values can be used for platform specific compilation/linkage against the
# the resource.
#
# @param resource_name [String] name of resource
# @return [Hash] Hash of compilation/linkage flags or empty hash if no settings are defined
# The returned hash has the following format:
# { :CFLAGS => '...', :CXXFLAGS => '...', :LDFLAGS => '...'}
#
def platform_settings_for(resource_name)
return {} if resource_name.empty?
rv = Hash.new
rv[:CFLAGS] = @settings["#{resource_name}_CFLAGS"]
rv[:CXXFLAGS]= @settings["#{resource_name}_CXXFLAGS"]
rv[:LDFLAGS] = @settings["#{resource_name}_LDFLAGS"]
rv = {} if rv.values.empty?
rv
end
# Creates compilation object
#
# @param [Hash] params
# @option params [String] :source source filename with path
# @option params [String] :object object filename path
# @option params [Hash] :settings project specific settings
# @option params [Array] :includes include paths used
#
def obj(params = {})
extension = File.extname(params[:source])
object = params[:object]
source = params[:source]
incs = compiler_incs_for(params[:includes]) + " #{@settings['LIB_INC']}"
case
when cpp_source_extensions.include?(extension)
flags = @settings['CXXFLAGS'] + ' ' + params[:settings]['ADD_CXXFLAGS']
compiler = "#{@settings['CXX']} -x c++ "
when c_source_extensions.include?(extension)
flags = @settings['CFLAGS'] + ' ' + params[:settings]['ADD_CFLAGS']
compiler = "#{@settings['CC']} -x c "
when as_source_extensions.include?(extension)
flags = ''
compiler = "#{@settings['AS']}"
else
raise "unsupported source file extension (#{extension}) for creating object!"
end
sh "#{compiler} #{flags} #{incs} -c #{source} -o #{object}"
end
# Creates dependency
#
# @param [Hash] params
# @option params [String] :source source filename with path
# @option params [String] :dep dependency filename path
# @option params [Hash] :settings project specific settings
# @option params [Array] :includes include paths used
#
# Creates moc_ source file
#
# @param [Hash] params
# @option params [String] :source source filename with path
# @option params [String] :moc moc_XXX filename path
# @option params [Hash] :settings project specific settings
#
def moc(params = {})
moc_compiler = @settings['OE_QMAKE_MOC']
raise 'No Qt Toolchain set' if moc_compiler.empty?
sh "#{moc_compiler} -i -f#{File.basename(params[:source])} #{params[:source]} >#{params[:moc]}"
end
# Creates library
#
# @param [Hash] params
# @option params [Array] :objects object filename paths
# @option params [String] :lib library filename path
# @option params [Hash] :settings project specific settings
#
def lib(params = {})
ldflags = params[:settings]['ADD_LDFLAGS'] + ' ' + @settings['LDFLAGS']
objs = params[:objects].join(' ')
dep_libs = (params[:libs] + libs_for_binary(params[:lib])).uniq
libs = linker_line_for(dep_libs)
extension = File.extname(params[:lib])
case extension
when ('.a')
# need to use 'touch' for correct timestamp, ar doesn't update the timestamp
# if archive hasn't changed
success = sh("#{@settings['AR']} curv #{params[:lib]} #{objs}")
touch(params[:lib]) if success
when '.so'
sh "#{@settings['CXX']} -shared #{ldflags} #{libs} #{objs} -o #{params[:lib]}"
if (@config.stripped) && File.exist?(params[:lib])
FileUtils.cp(params[:lib], "#{params[:lib]}.unstripped", :verbose => true)
sh "#{@settings['STRIP']} #{params[:lib]}"
end
else
raise "unsupported library extension (#{extension})!"
end
end
# Creates application
#
# @param [Hash] params
# @option params [Array] :objects array of object file paths
# @option params [Array] :libs array of libraries that should be linked against
# @option params [String] :app application filename path
# @option params [Hash] :settings project specific settings
# @option params [Array] :includes include paths used
#
def app(params = {})
incs = compiler_incs_for(params[:includes])
ldflags = params[:settings]['ADD_LDFLAGS'] + ' ' + @settings['LDFLAGS']
objs = params[:objects].join(' ')
dep_libs = (params[:libs] + libs_for_binary(params[:app])).uniq
libs = linker_line_for(dep_libs)
sh "#{@settings['SIZE']} #{objs} >#{params[:app]}.size" if @settings['SIZE']
sh "#{@settings['CXX']} #{incs} #{objs} #{ldflags} #{libs} -o #{params[:app]}"
sh "#{@settings['CXX']} #{incs} #{objs} #{ldflags} #{libs} -Wl,-Map,#{params[:app]}.map" if @config.generate_map
sh "#{@settings['OBJCOPY']} -O binary #{params[:app]} #{params[:app]}.bin" if @config.generate_bin
sh "#{@settings['OBJCOPY']} -O ihex #{params[:app]} #{params[:app]}.hex" if @config.generate_hex
if (@config.stripped) && File.exist?(params[:app])
FileUtils.cp(params[:app], "#{params[:app]}.unstripped", :verbose => true)
sh "#{@settings['STRIP']} #{params[:app]}"
end
end
# Creates test
#
# @param [Hash] params
# @option params [Array] :objects array of object file paths
# @option params [Array] :libs array of libraries that should be linked against
# @option params [String] :framework test framework name
# @option params [String] :test test filename path
# @option params [Hash] :settings project specific settings
# @option params [Array] :includes include paths used
#
def test(params = {})
incs = compiler_incs_for(params[:includes])
ldflags = params[:settings]['ADD_LDFLAGS'] + ' ' + @settings['LDFLAGS']
objs = params[:objects].join(' ')
test_fw = linker_line_for([params[:framework]])
dep_libs = (params[:libs] + libs_for_binary(params[:test])).uniq
libs = linker_line_for(dep_libs)
sh "#{@settings['CXX']} #{incs} #{objs} #{test_fw} #{ldflags} #{libs} -o #{params[:test]}"
end
def dump
puts '**************************'
puts '* Platform configuration *'
puts '**************************'
@kvr.dump
end
end
|
DigitPaint/roger | lib/roger/template.rb | Roger.Template.extract_front_matter | ruby | def extract_front_matter(source)
fm_regex = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m
return [{}, source] unless match = source.match(fm_regex)
source = source.sub(fm_regex, "")
begin
data = (YAML.safe_load(match[1]) || {}).inject({}) do |memo, (k, v)|
memo[k.to_sym] = v
memo
end
rescue *YAML_ERRORS => e
puts "YAML Exception: #{e.message}"
return false
end
[data, source]
rescue
[{}, source]
end | Get the front matter portion of the file and extract it. | train | https://github.com/DigitPaint/roger/blob/1153119f170d1b0289b659a52fcbf054df2d9633/lib/roger/template.rb#L90-L110 | class Template < BlankTemplate
# The source
attr_accessor :source
# Store the frontmatter
attr_accessor :data
# The path to the source file for this template
attr_accessor :source_path
# The current tilt template being used
attr_reader :current_tilt_template
class << self
def open(path, context = nil, options = {})
new(File.read(path), context, options.update(source_path: path))
end
end
# @option options [String,Pathname] :source_path The path to
# the source of the template being processed
def initialize(source, context = nil, options = {})
@context = context
self.source_path = options[:source_path]
self.data, self.source = extract_front_matter(source)
@templates = Tilt.templates_for(source_path)
end
def render(locals = {}, &block)
@templates.inject(source) do |src, template|
render_with_tilt_template(template, src, locals, &block)
end
end
# Actual path on disk, nil if it doesn't exist
# The nil case is mostly used with inline rendering.
def real_source_path
return @_real_source_path if @_real_source_path_cached
@_real_source_path_cached = true
@_real_source_path = if File.exist?(source_path)
Pathname.new(source_path).realpath
end
end
protected
# Render source with a specific tilt template class
def render_with_tilt_template(template_class, src, locals, &_block)
@current_tilt_template = template_class
template = template_class.new(source_path) { src }
block_content = if block_given?
yield
else
""
end
template.render(@context, locals) do |name|
if name
@context._content_for_blocks[name]
else
block_content
end
end
end
# Get the front matter portion of the file and extract it.
end
|
zhimin/rwebspec | lib/rwebspec-common/assert.rb | RWebSpec.Assert.assert_button_not_present | ruby | def assert_button_not_present(button_id)
@web_browser.buttons.each { |button|
the_button_id = RWebSpec.framework == "Watir" ? button.id : button["id"]
perform_assertion { assert(the_button_id != button_id, "unexpected button id: #{button_id} found") }
}
end | Button | train | https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/assert.rb#L328-L333 | module Assert
# own assert method
def assert test, msg = nil
msg ||= "Failed assertion, no message given."
# comment out self.assertions += 1 to counting assertions
unless test then
msg = msg.call if Proc === msg
raise RWebSpec::Assertion, msg
end
true
end
def fail(message)
perform_assertion { assert(false, message) }
end
def assert_not(condition, msg = "")
perform_assertion { assert(!condition, msg) }
end
def assert_not_nil(actual, msg="")
perform_assertion { assert(!actual.nil?, msg) }
end
def assert_title_equals(title)
assert_equals(title, @web_browser.page_title)
end
alias assert_title assert_title_equals
# Assert text present in page source (html)
# assert_text_in_page_source("<b>iTest2</b> Cool") # <b>iTest2</b> Cool
def assert_text_in_page_source(text)
perform_assertion { assert((@web_browser.page_source.include? text), 'expected html: ' + text + ' not found') }
end
# Assert text not present in page source (html)
# assert_text_not_in_page_source("<b>iTest2</b> Cool") # <b>iTest2</b> Cool
def assert_text_not_in_page_source(text)
perform_assertion { assert(!(@web_browser.page_source.include? text), 'expected html: ' + text + ' found') }
end
# Assert text present in page source (html)
# assert_text_present("iTest2 Cool") # <b>iTest2</b> Cool
def assert_text_present(text)
perform_assertion { assert((@web_browser.text.include? text), 'expected text: ' + text + ' not found') }
end
# Assert text not present in page source (html)
# assert_text_not_present("iTest2 Cool") # <b>iTest2</b> Cool
def assert_text_not_present(text)
perform_assertion { assert(!(@web_browser.text.include? text), 'expected text: ' + text + ' found') }
end
##
# Link
# Assert a link with specified text (exact match) in the page
#
# <a href="">Click Me</a>
# assert_link_present_with_exact("Click Me") => true
# assert_link_present_with_exact("Click") => false
#
def assert_link_present_with_exact(link_text)
@web_browser.links.each { |link|
return if link_text == link.text
}
fail( "can't find the link with text: #{link_text}")
end
def assert_link_not_present_with_exact(link_text)
@web_browser.links.each { |link|
perform_assertion { assert(link_text != link.text, "unexpected link (exact): #{link_text} found") }
}
end
# Assert a link containing specified text in the page
#
# <a href="">Click Me</a>
# assert_link_present_with_text("Click ") # =>
#
def assert_link_present_with_text(link_text)
@web_browser.links.each { |link|
return if link.text.include?(link_text)
}
fail( "can't find the link containing text: #{link_text}")
end
def assert_link_not_present_with_text(link_text)
@web_browser.links.each { |link|
perform_assertion { assert(!link.text.include?(link_text), "unexpected link containing: #{link_text} found") }
}
end
def is_selenium_element?(elem)
elem.class.name =~ /Selenium/
end
def element_name(elem)
elem.class.name =~ /Selenium/ ? elem['name'] : elem.name
end
def element_value(elem)
elem.class.name =~ /Selenium/ ? elem['value'] : elem.value
end
##
# Checkbox
def assert_checkbox_not_selected(checkbox_name)
@web_browser.checkboxes.each { |checkbox|
the_element_name = element_name(checkbox)
if (the_element_name == checkbox_name) then
if is_selenium_element?(checkbox)
perform_assertion { assert(!checkbox.selected?, "Checkbox #{checkbox_name} is checked unexpectly") }
else
perform_assertion { assert(!checkbox.set?, "Checkbox #{checkbox_name} is checked unexpectly") }
end
end
}
end
alias assert_checkbox_not_checked assert_checkbox_not_selected
def assert_checkbox_selected(checkbox_name)
@web_browser.checkboxes.each { |checkbox|
the_element_name = element_name(checkbox)
if (the_element_name == checkbox_name) then
if is_selenium_element?(checkbox)
perform_assertion { assert(checkbox.selected?, "Checkbox #{checkbox_name} not checked") }
else
perform_assertion { assert(checkbox.set?, "Checkbox #{checkbox_name} not checked") }
end
end
}
end
alias assert_checkbox_checked assert_checkbox_selected
##
# select
def assert_option_value_not_present(select_name, option_value)
@web_browser.select_lists.each { |select|
the_element_name = element_name(select)
next unless the_element_name == select_name
if RWebSpec.framework =~ /watir/i
select.options.each do |option| # items in the list
perform_assertion { assert(!(option.value == option_value), "unexpected select option: #{option_value} for #{select_name} found") }
end
else
select.find_elements(:tag_name => "option" ).each do |option|
fail("unexpected option value: #{option_label} found") if option.value == option_value
end
end
}
end
alias assert_select_value_not_present assert_option_value_not_present
def assert_option_not_present(select_name, option_label)
@web_browser.select_lists.each { |select|
the_element_name = element_name(select)
next unless the_element_name == select_name
if RWebSpec.framework =~ /watir/i
select.options.each do |option| # items in the list
perform_assertion { assert(!(option.text == option_label), "unexpected select option: #{option_label} for #{select_name} found") }
end
else
select.find_elements(:tag_name => "option" ).each do |option|
fail("unexpected option label: #{option_label} found") if option.text == option_label
end
end
}
end
alias assert_select_label_not_present assert_option_not_present
def assert_option_value_present(select_name, option_value)
@web_browser.select_lists.each { |select|
the_element_name = element_name(select)
next unless the_element_name == select_name
if RWebSpec.framework == "Watir"
select.options.each do |option| # items in the list
return if option.value == option_value
end
else
select.find_elements(:tag_name => "option" ).each do |option|
return if element_value(option) == option_value
end
end
}
fail("can't find the combo box with value: #{option_value}")
end
alias assert_select_value_present assert_option_value_present
alias assert_menu_value_present assert_option_value_present
def assert_option_present(select_name, option_label)
@web_browser.select_lists.each { |select|
the_element_name = element_name(select)
next unless the_element_name == select_name
if RWebSpec.framework == "Watir"
select.options.each do |option| # items in the list
return if option.text == option_label
end
else
select.find_elements(:tag_name => "option" ).each do |option|
return if option.text == option_label
end
end
}
fail("can't find the combo box: #{select_name} with value: #{option_label}")
end
alias assert_select_label_present assert_option_present
alias assert_menu_label_present assert_option_present
def assert_option_equals(select_name, option_label)
@web_browser.select_lists.each { |select|
the_element_name = element_name(select)
next unless the_element_name == select_name
if RWebSpec.framework == "Watir"
select.options.each do |option| # items in the list
if (option.text == option_label) then
perform_assertion { assert_equal(select.value, option.value, "Select #{select_name}'s value is not equal to expected option label: '#{option_label}'") }
end
end
else
select.find_elements(:tag_name => "option" ).each do |option|
if (option.text == option_label) then
assert option.selected?
end
end
end
}
end
alias assert_select_label assert_option_equals
alias assert_menu_label assert_option_equals
def assert_option_value_equals(select_name, option_value)
@web_browser.select_lists.each { |select|
the_element_name = element_name(select)
next unless the_element_name == select_name
if RWebSpec.framework == "Watir"
perform_assertion { assert_equal(select.value, option_value, "Select #{select_name}'s value is not equal to expected: '#{option_value}'") }
else
perform_assertion { assert_equal(element_value(select), option_value, "Select #{select_name}'s value is not equal to expected: '#{option_value}'") }
end
}
end
alias assert_select_value assert_option_value_equals
alias assert_menu_value assert_option_value_equals
##
# radio
# radio_group is the name field, radio options 'value' field
def assert_radio_option_not_present(radio_group, radio_option)
@web_browser.radios.each { |radio|
the_element_name = element_name(radio)
if (the_element_name == radio_group) then
perform_assertion { assert(!(radio_option == element_value(radio) ), "unexpected radio option: " + radio_option + " found") }
end
}
end
def assert_radio_option_present(radio_group, radio_option)
@web_browser.radios.each { |radio|
the_element_name = element_name(radio)
return if (the_element_name == radio_group) and (radio_option == element_value(radio) )
}
fail("can't find the radio option : '#{radio_option}'")
end
def assert_radio_option_selected(radio_group, radio_option)
@web_browser.radios.each { |radio|
the_element_name = element_name(radio)
if (the_element_name == radio_group and radio_option == element_value(radio) ) then
if is_selenium_element?(radio)
perform_assertion { assert(radio.selected?, "Radio button #{radio_group}-[#{radio_option}] not checked") }
else
perform_assertion { assert(radio.set?, "Radio button #{radio_group}-[#{radio_option}] not checked") }
end
end
}
end
alias assert_radio_button_checked assert_radio_option_selected
alias assert_radio_option_checked assert_radio_option_selected
def assert_radio_option_not_selected(radio_group, radio_option)
@web_browser.radios.each { |radio|
the_element_name = element_name(radio)
if (the_element_name == radio_group and radio_option == element_value(radio) ) then
if is_selenium_element?(radio)
perform_assertion { assert(!radio.selected?, "Radio button #{radio_group}-[#{radio_option}] checked unexpected") }
else
perform_assertion { assert(!radio.set?, "Radio button #{radio_group}-[#{radio_option}] checked unexpected") }
end
end
}
end
alias assert_radio_button_not_checked assert_radio_option_not_selected
alias assert_radio_option_not_checked assert_radio_option_not_selected
##
# Button
def assert_button_not_present(button_id)
@web_browser.buttons.each { |button|
the_button_id = RWebSpec.framework == "Watir" ? button.id : button["id"]
perform_assertion { assert(the_button_id != button_id, "unexpected button id: #{button_id} found") }
}
end
def assert_button_not_present_with_text(text)
@web_browser.buttons.each { |button|
perform_assertion { assert(element_value(button) != text, "unexpected button id: #{text} found") }
}
end
def assert_button_present(button_id)
@web_browser.buttons.each { |button|
the_button_id = RWebSpec.framework == "Watir" ? button.id : button["id"]
return if button_id == the_button_id
}
fail("can't find the button with id: #{button_id}")
end
def assert_button_present_with_text(button_text)
@web_browser.buttons.each { |button|
return if button_text == element_value(button)
}
fail("can't find the button with text: #{button_text}")
end
def assert_equals(expected, actual, msg=nil)
perform_assertion { assert(expected == actual, (msg.nil?) ? "Expected: #{expected} diff from actual: #{actual}" : msg) }
end
# Check a HTML element exists or not
# Example:
# assert_exists("label", "receipt_date")
# assert_exists(:span, :receipt_date)
def assert_exists(tag, element_id)
if RWebSpec.framework == "Watir"
perform_assertion { assert(eval("#{tag}(:id, '#{element_id.to_s}').exists?"), "Element '#{tag}' with id: '#{element_id}' not found") }
else
perform_assertion { assert( @web_browser.driver.find_element(:tag_name => tag, :id => element_id))}
end
end
alias assert_exists? assert_exists
alias assert_element_exists assert_exists
def assert_not_exists(tag, element_id)
if RWebSpec.framework == "Watir"
perform_assertion { assert_not(eval("#{tag}(:id, '#{element_id.to_s}').exists?"), "Unexpected element'#{tag}' + with id: '#{element_id}' found")}
else
perform_assertion {
begin
@web_browser.driver.find_element(:tag_name => tag, :id => element_id)
fail("the element #{tag}##{element_id} found")
rescue =>e
end
}
end
end
alias assert_not_exists? assert_not_exists
alias assert_element_not_exists? assert_not_exists
# Assert tag with element id is visible?, eg.
# assert_visible(:div, "public_notice")
# assert_visible(:span, "public_span")
def assert_visible(tag, element_id)
if RWebSpec.framework =~ /selenium/i
perform_assertion { assert(eval("#{tag}(:id, '#{element_id.to_s}').displayed?"), "Element '#{tag}' with id: '#{element_id}' not visible") }
else
perform_assertion { assert(eval("#{tag}(:id, '#{element_id.to_s}').visible?"), "Element '#{tag}' with id: '#{element_id}' not visible") }
end
end
# Assert tag with element id is hidden?, example
# assert_hidden(:div, "secret")
# assert_hidden(:span, "secret_span")
def assert_hidden(tag, element_id)
if RWebSpec.framework =~ /selenium/i
perform_assertion { assert(!eval("#{tag}(:id, '#{element_id.to_s}').displayed?"), "Element '#{tag}' with id: '#{element_id}' is visible") }
else
perform_assertion { assert(!eval("#{tag}(:id, '#{element_id.to_s}').visible?"), "Element '#{tag}' with id: '#{element_id}' is visible") }
end
end
alias assert_not_visible assert_hidden
# Assert given text appear inside a table (inside <table> tag like below)
#
# <table id="t1">
#
# <tbody>
# <tr id="row_1">
# <td id="cell_1_1">A</td>
# <td id="cell_1_2">B</td>
# </tr>
# <tr id="row_2">
# <td id="cell_2_1">a</td>
# <td id="cell_2_2">b</td>
# </tr>
# </tbody>
#
# </table>
#
# The plain text view of above table
# A B a b
#
# Examples
# assert_text_present_in_table("t1", ">A<") # => true
# assert_text_present_in_table("t1", ">A<", :just_plain_text => true) # => false
def assert_text_present_in_table(table_id, text, options = {})
options[:just_plain_text] ||= false
perform_assertion { assert(the_table_source(table_id, options).include?(text), "the text #{text} not found in table #{table_id}") }
end
alias assert_text_in_table assert_text_present_in_table
def assert_text_not_present_in_table(table_id, text, options = {})
options[:just_plain_text] ||= false
perform_assertion { assert_not(the_table_source(table_id, options).include?(text), "the text #{text} not found in table #{table_id}") }
end
alias assert_text_not_in_table assert_text_not_present_in_table
# Assert a text field (with given name) has the value
#
# <input id="tid" name="text1" value="text already there" type="text">
#
# assert_text_field_value("text1", "text already there") => true
#
def assert_text_field_value(textfield_name, text)
if RWebSpec.framework == "Watir"
perform_assertion { assert_equal(text, text_field(:name, textfield_name).value) }
else
the_element = @web_browser.driver.find_element(:name, textfield_name)
perform_assertion { assert_equal(text, element_value(the_element)) }
end
end
#-- Not tested
# -----
def assert_text_in_element(element_id, text)
elem = element_by_id(element_id)
if RWebSpec.framework == "Watir"
assert_not_nil(elem.innerText, "element #{element_id} has no text")
perform_assertion { assert(elem.innerText.include?(text), "the text #{text} not found in element #{element_id}") }
else
perform_assertion {
# this works in text field
assert(element_value(elem).include?(text), "the text #{text} not found in element #{element_id}")
# TODO
}
end
end
# Use
#
#TODO for drag-n-drop, check the postion in list
# def assert_position_in_list(list_element_id)
# raise "not implemented"
# end
private
def the_table_source(table_id, options)
elem_table = RWebSpec.framework == "Watir" ? table(:id, table_id.to_s) : @web_browser.driver.find_element(:id => table_id)
elem_table_text = elem_table.text
elem_table_html = RWebSpec.framework == "Watir" ? elem_table.html : elem_table["innerHTML"];
table_source = options[:just_plain_text] ? elem_table_text : elem_table_html
end
def perform_assertion(&block)
begin
yield
rescue StandardError => e
# puts "[DEBUG] Assertion error: #{e}"
take_screenshot if $take_screenshot
raise e
rescue MiniTest::Assertion => e2
take_screenshot if $take_screenshot
raise e2
end
end
end
|
state-machines/state_machines | lib/state_machines/event_collection.rb | StateMachines.EventCollection.valid_for | ruby | def valid_for(object, requirements = {})
match(requirements).select { |event| event.can_fire?(object, requirements) }
end | Gets the list of events that can be fired on the given object.
Valid requirement options:
* <tt>:from</tt> - One or more states being transitioned from. If none
are specified, then this will be the object's current state.
* <tt>:to</tt> - One or more states being transitioned to. If none are
specified, then this will match any to state.
* <tt>:on</tt> - One or more events that fire the transition. If none
are specified, then this will match any event.
* <tt>:guard</tt> - Whether to guard transitions with the if/unless
conditionals defined for each one. Default is true.
== Examples
class Vehicle
state_machine :initial => :parked do
event :park do
transition :idling => :parked
end
event :ignite do
transition :parked => :idling
end
end
end
events = Vehicle.state_machine(:state).events
vehicle = Vehicle.new # => #<Vehicle:0xb7c464b0 @state="parked">
events.valid_for(vehicle) # => [#<StateMachines::Event name=:ignite transitions=[:parked => :idling]>]
vehicle.state = 'idling'
events.valid_for(vehicle) # => [#<StateMachines::Event name=:park transitions=[:idling => :parked]>] | train | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event_collection.rb#L41-L43 | class EventCollection < NodeCollection
def initialize(machine) #:nodoc:
super(machine, :index => [:name, :qualified_name])
end
# Gets the list of events that can be fired on the given object.
#
# Valid requirement options:
# * <tt>:from</tt> - One or more states being transitioned from. If none
# are specified, then this will be the object's current state.
# * <tt>:to</tt> - One or more states being transitioned to. If none are
# specified, then this will match any to state.
# * <tt>:on</tt> - One or more events that fire the transition. If none
# are specified, then this will match any event.
# * <tt>:guard</tt> - Whether to guard transitions with the if/unless
# conditionals defined for each one. Default is true.
#
# == Examples
#
# class Vehicle
# state_machine :initial => :parked do
# event :park do
# transition :idling => :parked
# end
#
# event :ignite do
# transition :parked => :idling
# end
# end
# end
#
# events = Vehicle.state_machine(:state).events
#
# vehicle = Vehicle.new # => #<Vehicle:0xb7c464b0 @state="parked">
# events.valid_for(vehicle) # => [#<StateMachines::Event name=:ignite transitions=[:parked => :idling]>]
#
# vehicle.state = 'idling'
# events.valid_for(vehicle) # => [#<StateMachines::Event name=:park transitions=[:idling => :parked]>]
# Gets the list of transitions that can be run on the given object.
#
# Valid requirement options:
# * <tt>:from</tt> - One or more states being transitioned from. If none
# are specified, then this will be the object's current state.
# * <tt>:to</tt> - One or more states being transitioned to. If none are
# specified, then this will match any to state.
# * <tt>:on</tt> - One or more events that fire the transition. If none
# are specified, then this will match any event.
# * <tt>:guard</tt> - Whether to guard transitions with the if/unless
# conditionals defined for each one. Default is true.
#
# == Examples
#
# class Vehicle
# state_machine :initial => :parked do
# event :park do
# transition :idling => :parked
# end
#
# event :ignite do
# transition :parked => :idling
# end
# end
# end
#
# events = Vehicle.state_machine.events
#
# vehicle = Vehicle.new # => #<Vehicle:0xb7c464b0 @state="parked">
# events.transitions_for(vehicle) # => [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>]
#
# vehicle.state = 'idling'
# events.transitions_for(vehicle) # => [#<StateMachines::Transition attribute=:state event=:park from="idling" from_name=:idling to="parked" to_name=:parked>]
#
# # Search for explicit transitions regardless of the current state
# events.transitions_for(vehicle, :from => :parked) # => [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>]
def transitions_for(object, requirements = {})
match(requirements).map { |event| event.transition_for(object, requirements) }.compact
end
# Gets the transition that should be performed for the event stored in the
# given object's event attribute. This also takes an additional parameter
# for automatically invalidating the object if the event or transition are
# invalid. By default, this is turned off.
#
# *Note* that if a transition has already been generated for the event, then
# that transition will be used.
#
# == Examples
#
# class Vehicle < ActiveRecord::Base
# state_machine :initial => :parked do
# event :ignite do
# transition :parked => :idling
# end
# end
# end
#
# vehicle = Vehicle.new # => #<Vehicle id: nil, state: "parked">
# events = Vehicle.state_machine.events
#
# vehicle.state_event = nil
# events.attribute_transition_for(vehicle) # => nil # Event isn't defined
#
# vehicle.state_event = 'invalid'
# events.attribute_transition_for(vehicle) # => false # Event is invalid
#
# vehicle.state_event = 'ignite'
# events.attribute_transition_for(vehicle) # => #<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>
def attribute_transition_for(object, invalidate = false)
return unless machine.action
# TODO, simplify
machine.read(object, :event_transition) || if event_name = machine.read(object, :event)
if event = self[event_name.to_sym, :name]
event.transition_for(object) || begin
# No valid transition: invalidate
machine.invalidate(object, :event, :invalid_event, [[:state, machine.states.match!(object).human_name(object.class)]]) if invalidate
false
end
else
# Event is unknown: invalidate
machine.invalidate(object, :event, :invalid) if invalidate
false
end
end
end
private
def match(requirements) #:nodoc:
requirements && requirements[:on] ? [fetch(requirements.delete(:on))] : self
end
end
|
chaintope/bitcoinrb | lib/bitcoin/key.rb | Bitcoin.Key.verify | ruby | def verify(sig, origin)
return false unless valid_pubkey?
begin
sig = ecdsa_signature_parse_der_lax(sig)
secp256k1_module.verify_sig(origin, sig, pubkey)
rescue Exception
false
end
end | verify signature using public key
@param [String] sig signature data with binary format
@param [String] origin original message
@return [Boolean] verify result | train | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L110-L118 | class Key
PUBLIC_KEY_SIZE = 65
COMPRESSED_PUBLIC_KEY_SIZE = 33
SIGNATURE_SIZE = 72
COMPACT_SIGNATURE_SIZE = 65
attr_accessor :priv_key
attr_accessor :pubkey
attr_accessor :key_type
attr_reader :secp256k1_module
TYPES = {uncompressed: 0x00, compressed: 0x01, p2pkh: 0x10, p2wpkh: 0x11, pw2pkh_p2sh: 0x12}
MIN_PRIV_KEY_MOD_ORDER = 0x01
# Order of secp256k1's generator minus 1.
MAX_PRIV_KEY_MOD_ORDER = ECDSA::Group::Secp256k1.order - 1
# initialize private key
# @param [String] priv_key a private key with hex format.
# @param [String] pubkey a public key with hex format.
# @param [Integer] key_type a key type which determine address type.
# @param [Boolean] compressed [Deprecated] whether public key is compressed.
# @return [Bitcoin::Key] a key object.
def initialize(priv_key: nil, pubkey: nil, key_type: nil, compressed: true)
puts "[Warning] Use key_type parameter instead of compressed. compressed parameter removed in the future." if key_type.nil? && !compressed.nil? && pubkey.nil?
if key_type
@key_type = key_type
compressed = @key_type != TYPES[:uncompressed]
else
@key_type = compressed ? TYPES[:compressed] : TYPES[:uncompressed]
end
@secp256k1_module = Bitcoin.secp_impl
@priv_key = priv_key
if @priv_key
raise ArgumentError, 'private key is not on curve' unless validate_private_key_range(@priv_key)
end
if pubkey
@pubkey = pubkey
else
@pubkey = generate_pubkey(priv_key, compressed: compressed) if priv_key
end
end
# generate key pair
def self.generate(key_type = TYPES[:compressed])
priv_key, pubkey = Bitcoin.secp_impl.generate_key_pair
new(priv_key: priv_key, pubkey: pubkey, key_type: key_type)
end
# import private key from wif format
# https://en.bitcoin.it/wiki/Wallet_import_format
def self.from_wif(wif)
hex = Base58.decode(wif)
raise ArgumentError, 'data is too short' if hex.htb.bytesize < 4
version = hex[0..1]
data = hex[2...-8].htb
checksum = hex[-8..-1]
raise ArgumentError, 'invalid version' unless version == Bitcoin.chain_params.privkey_version
raise ArgumentError, 'invalid checksum' unless Bitcoin.calc_checksum(version + data.bth) == checksum
key_len = data.bytesize
if key_len == COMPRESSED_PUBLIC_KEY_SIZE && data[-1].unpack('C').first == 1
key_type = TYPES[:compressed]
data = data[0..-2]
elsif key_len == 32
key_type = TYPES[:uncompressed]
else
raise ArgumentError, 'Wrong number of bytes for a private key, not 32 or 33'
end
new(priv_key: data.bth, key_type: key_type)
end
# export private key with wif format
def to_wif
version = Bitcoin.chain_params.privkey_version
hex = version + priv_key
hex += '01' if compressed?
hex += Bitcoin.calc_checksum(hex)
Base58.encode(hex)
end
# sign +data+ with private key
# @param [String] data a data to be signed with binary format
# @param [Boolean] low_r flag to apply low-R.
# @param [String] extra_entropy the extra entropy for rfc6979.
# @return [String] signature data with binary format
def sign(data, low_r = true, extra_entropy = nil)
sig = secp256k1_module.sign_data(data, priv_key, extra_entropy)
if low_r && !sig_has_low_r?(sig)
counter = 1
until sig_has_low_r?(sig)
extra_entropy = [counter].pack('I*').bth.ljust(64, '0').htb
sig = secp256k1_module.sign_data(data, priv_key, extra_entropy)
counter += 1
end
end
sig
end
# verify signature using public key
# @param [String] sig signature data with binary format
# @param [String] origin original message
# @return [Boolean] verify result
# get hash160 public key.
def hash160
Bitcoin.hash160(pubkey)
end
# get pay to pubkey hash address
# @deprecated
def to_p2pkh
Bitcoin::Script.to_p2pkh(hash160).addresses.first
end
# get pay to witness pubkey hash address
# @deprecated
def to_p2wpkh
Bitcoin::Script.to_p2wpkh(hash160).addresses.first
end
# get p2wpkh address nested in p2sh.
# @deprecated
def to_nested_p2wpkh
Bitcoin::Script.to_p2wpkh(hash160).to_p2sh.addresses.first
end
def compressed?
key_type != TYPES[:uncompressed]
end
# generate pubkey ec point
# @return [ECDSA::Point]
def to_point
p = pubkey
p ||= generate_pubkey(priv_key, compressed: compressed)
ECDSA::Format::PointOctetString.decode(p.htb, Bitcoin::Secp256k1::GROUP)
end
# check +pubkey+ (hex) is compress or uncompress pubkey.
def self.compress_or_uncompress_pubkey?(pubkey)
p = pubkey.htb
return false if p.bytesize < COMPRESSED_PUBLIC_KEY_SIZE
case p[0]
when "\x04"
return false unless p.bytesize == PUBLIC_KEY_SIZE
when "\x02", "\x03"
return false unless p.bytesize == COMPRESSED_PUBLIC_KEY_SIZE
else
return false
end
true
end
# check +pubkey+ (hex) is compress pubkey.
def self.compress_pubkey?(pubkey)
p = pubkey.htb
p.bytesize == COMPRESSED_PUBLIC_KEY_SIZE && ["\x02", "\x03"].include?(p[0])
end
# check +sig+ is low.
def self.low_signature?(sig)
s = sig.unpack('C*')
len_r = s[3]
len_s = s[5 + len_r]
val_s = s.slice(6 + len_r, len_s)
max_mod_half_order = [
0x7f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0x5d,0x57,0x6e,0x73,0x57,0xa4,0x50,0x1d,
0xdf,0xe9,0x2f,0x46,0x68,0x1b,0x20,0xa0]
compare_big_endian(val_s, [0]) > 0 &&
compare_big_endian(val_s, max_mod_half_order) <= 0
end
# check +sig+ is correct der encoding.
# This function is consensus-critical since BIP66.
def self.valid_signature_encoding?(sig)
return false if sig.bytesize < 9 || sig.bytesize > 73 # Minimum and maximum size check
s = sig.unpack('C*')
return false if s[0] != 0x30 || s[1] != s.size - 3 # A signature is of type 0x30 (compound). Make sure the length covers the entire signature.
len_r = s[3]
return false if 5 + len_r >= s.size # Make sure the length of the S element is still inside the signature.
len_s = s[5 + len_r]
return false unless len_r + len_s + 7 == s.size #Verify that the length of the signature matches the sum of the length of the elements.
return false unless s[2] == 0x02 # Check whether the R element is an integer.
return false if len_r == 0 # Zero-length integers are not allowed for R.
return false unless s[4] & 0x80 == 0 # Negative numbers are not allowed for R.
# Null bytes at the start of R are not allowed, unless R would otherwise be interpreted as a negative number.
return false if len_r > 1 && (s[4] == 0x00) && (s[5] & 0x80 == 0)
return false unless s[len_r + 4] == 0x02 # Check whether the S element is an integer.
return false if len_s == 0 # Zero-length integers are not allowed for S.
return false unless (s[len_r + 6] & 0x80) == 0 # Negative numbers are not allowed for S.
# Null bytes at the start of S are not allowed, unless S would otherwise be interpreted as a negative number.
return false if len_s > 1 && (s[len_r + 6] == 0x00) && (s[len_r + 7] & 0x80 == 0)
true
end
# fully validate whether this is a valid public key (more expensive than IsValid())
def fully_valid_pubkey?
return false unless valid_pubkey?
point = ECDSA::Format::PointOctetString.decode(pubkey.htb, ECDSA::Group::Secp256k1)
ECDSA::Group::Secp256k1.valid_public_key?(point)
end
private
def self.compare_big_endian(c1, c2)
c1, c2 = c1.dup, c2.dup # Clone the arrays
while c1.size > c2.size
return 1 if c1.shift > 0
end
while c2.size > c1.size
return -1 if c2.shift > 0
end
c1.size.times{|idx| return c1[idx] - c2[idx] if c1[idx] != c2[idx] }
0
end
# generate publick key from private key
# @param [String] privkey a private key with string format
# @param [Boolean] compressed pubkey compressed?
# @return [String] a pubkey which generate from privkey
def generate_pubkey(privkey, compressed: true)
@secp256k1_module.generate_pubkey(privkey, compressed: compressed)
end
# check private key range.
def validate_private_key_range(private_key)
value = private_key.to_i(16)
MIN_PRIV_KEY_MOD_ORDER <= value && value <= MAX_PRIV_KEY_MOD_ORDER
end
# Supported violations include negative integers, excessive padding, garbage
# at the end, and overly long length descriptors. This is safe to use in
# Bitcoin because since the activation of BIP66, signatures are verified to be
# strict DER before being passed to this module, and we know it supports all
# violations present in the blockchain before that point.
def ecdsa_signature_parse_der_lax(sig)
sig_array = sig.unpack('C*')
len_r = sig_array[3]
r = sig_array[4...(len_r+4)].pack('C*').bth
len_s = sig_array[len_r + 5]
s = sig_array[(len_r + 6)...(len_r + 6 + len_s)].pack('C*').bth
ECDSA::Signature.new(r.to_i(16), s.to_i(16)).to_der
end
def valid_pubkey?
!pubkey.nil? && pubkey.size > 0
end
# check whether the signature is low-R
# @param [String] sig the signature data
# @return [Boolean] result
def sig_has_low_r?(sig)
sig[3].bth.to_i(16) == 0x20 && sig[4].bth.to_i(16) < 0x80
end
end
|
projectcypress/health-data-standards | lib/hqmf-parser/converter/pass1/data_criteria_converter.rb | HQMF.DataCriteriaConverter.create_group_data_criteria | ruby | def create_group_data_criteria(preconditions, type, value, parent_id, id, standard_category, qds_data_type)
extract_group_data_criteria_tree(HQMF::DataCriteria::UNION,preconditions, type, parent_id)
end | grouping data criteria are used to allow a single reference off of a temporal reference or subset operator
grouping data criteria can reference either regular data criteria as children, or other grouping data criteria | train | https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/converter/pass1/data_criteria_converter.rb#L46-L48 | class DataCriteriaConverter
attr_reader :v1_data_criteria_by_id, :v2_data_criteria, :v2_data_criteria_to_delete, :measure_period_criteria, :measure_period_v1_keys, :specific_occurrences
def initialize(doc, measure_period)
@doc = doc
@v1_data_criteria_by_id = {}
@v2_data_criteria = []
@v2_data_criteria_to_delete = {}
@specific_occurrences = {}
@measure_period = measure_period
parse()
end
def final_v2_data_criteria
@v2_data_criteria.delete_if {|criteria| @v2_data_criteria_to_delete[criteria.id] }
end
# duplicates a data criteria. This is important because we may be modifying source data criteria like patient characteristic birthdate to add restrictions
# the restrictions added may be different for the numerator, denominator, different IPP_1, IPP_2, etc.
def duplicate_data_criteria(data_criteria, parent_id)
if (data_criteria.is_a? HQMF::Converter::SimpleDataCriteria and data_criteria.precondition_id == parent_id)
new_data_criteria = data_criteria
else
new_data_criteria = HQMF::Converter::SimpleDataCriteria.from_data_criteria(data_criteria)
new_data_criteria.assign_precondition(parent_id)
@v2_data_criteria << new_data_criteria
# we want to delete the original for data criteria that have been duplicated
@v2_data_criteria_to_delete[data_criteria.id] = true if !@v2_data_criteria_to_delete.keys.include? data_criteria.id
end
new_data_criteria
end
# make sure that if a data criteria is used as a target, that it is not deleted by someone else.
# this is required for birthdate in NQF0106
def validate_not_deleted(target)
@v2_data_criteria_to_delete[target] = false
end
# grouping data criteria are used to allow a single reference off of a temporal reference or subset operator
# grouping data criteria can reference either regular data criteria as children, or other grouping data criteria
def build_group_data_criteria(children, section, parent_id, derivation_operator)
criteria_ids = children.map(&:id)
# make sure nobody else is going to delete the criteria we've grouped
criteria_ids.each {|target| validate_not_deleted(target)}
id = "#{parent_id}_#{section}_#{HQMF::Counter.instance.next}"
title = "#{id}"
description = ""
definition = 'derived'
_display_name,_code_list_id,_status,_value,_field_values,_effective_time,_inline_code_list,_negation_code_list_id, = nil
_negation = false
group_criteria = HQMF::DataCriteria.new(id, title, _display_name, description, _code_list_id, criteria_ids, derivation_operator, definition, _status,
_value, _field_values, _effective_time, _inline_code_list,_negation,_negation_code_list_id,nil,nil,nil,nil)
@v2_data_criteria << group_criteria
group_criteria
end
# pull the children data criteria out of a set of preconditions
def extract_group_data_criteria_tree(conjunction, preconditions, type, parent_id)
children = []
preconditions.each do |precondition|
if (precondition.comparison?)
if (precondition.reference.id == HQMF::Document::MEASURE_PERIOD_ID)
children << measure_period_criteria
else
children << v2_data_criteria_by_id[precondition.reference.id]
end
else
converted_conjunction = convert_grouping_conjunction(precondition.conjunction_code)
children << extract_group_data_criteria_tree(converted_conjunction, precondition.preconditions, type, parent_id)
end
end
# if we have just one child element, just return it. An AND or OR of a single item is not useful.
if (children.size > 1)
build_group_data_criteria(children, type, parent_id, conjunction)
else
children.first
end
end
def convert_grouping_conjunction(conjunction)
case conjunction
when HQMF::Precondition::AT_LEAST_ONE_TRUE
HQMF::DataCriteria::UNION
when HQMF::Precondition::ALL_TRUE
HQMF::DataCriteria::XPRODUCT
else
'unknown'
end
end
# pull the children data criteria out of a set of preconditions
def self.extract_data_criteria(preconditions, data_criteria_converter)
flattened = []
preconditions.each do |precondition|
if (precondition.comparison?)
if (precondition.reference.id == HQMF::Document::MEASURE_PERIOD_ID)
flattened << data_criteria_converter.measure_period_criteria
else
flattened << data_criteria_converter.v2_data_criteria_by_id[precondition.reference.id]
end
else
flattened.concat(extract_data_criteria(precondition.preconditions,data_criteria_converter))
end
end
flattened
end
def v2_data_criteria_by_id
criteria_by_id = {}
@v2_data_criteria.each do |criteria|
criteria_by_id[criteria.id] = criteria
end
criteria_by_id
end
private
def parse()
@doc[:data_criteria].each do |key,criteria|
parsed_criteria = HQMF::DataCriteriaConverter.convert(key, criteria)
@v2_data_criteria << parsed_criteria
@v1_data_criteria_by_id[criteria[:id]] = parsed_criteria
@specific_occurrences[parsed_criteria.id] = criteria[:derived_from] != nil
end
create_measure_period_v1_data_criteria(@doc,@measure_period,@v1_data_criteria_by_id)
end
def self.convert(key, criteria)
# @param [String] id
# @param [String] title
# @param [String] standard_category
# @param [String] qds_data_type
# @param [String] subset_code
# @param [String] code_list_id
# @param [String] property
# @param [String] type
# @param [String] status
# @param [boolean] negation
# @param [String] negation_code_list_id
# @param [Value|Range|Coded] value
# @param [Range] effective_time
# @param [Hash<String,String>] inline_code_list
id = convert_key(key)
title = criteria[:title]
title = title.match(/.*:\s+(.+)/)[1]
description = criteria[:description]
code_list_id = criteria[:code_list_id]
definition = criteria[:definition]
status = criteria[:status]
negation = criteria[:negation]
negation_code_list_id = criteria[:negation_code_list_id]
specific_occurrence = criteria[:specific_occurrence]
specific_occurrence_const = nil
# specific occurrences do not properly set the description, so we want to add the definition and status
if (specific_occurrence)
if status
statusText = ", #{status.titleize}"
elsif definition == 'laboratory_test'
# laboratory_test without a status is actually a Result
statusText = ", Result"
end
description = "#{definition.titleize}#{statusText}: #{description}"
specific_occurrence_const = (description.gsub(/\W/,' ').split.collect {|word| word.strip.upcase }).join '_'
end
value = nil # value is filled out by backfill_patient_characteristics for things like gender and by REFR restrictions
effective_time = nil # filled out by temporal reference code
temporal_references = # filled out by operator code
subset_operators = nil # filled out by operator code
children_criteria = nil # filled out by operator and temporal reference code
derivation_operator = nil # filled out by operator and temporal reference code
negation_code_list_id = nil # filled out by RSON restrictions
field_values = nil # field values are filled out by SUBJ and REFR restrictions
inline_code_list = nil # inline code list is only used in HQMF V2, so we can just pass in nil
display_name=nil
# transfers should be modeled as a field. The code_list_id of the transfer data criteria is cleared and the oid is added to a transfer field
# The definition of the data criteria is still transfer, but it is marked as an encounter using the patient api funciton.
if ['transfer_to', 'transfer_from'].include? definition
field_values ||= {}
field_values[definition.upcase] = HQMF::Coded.for_code_list(code_list_id, title)
code_list_id = nil
end
HQMF::DataCriteria.new(id, title, display_name, description, code_list_id, children_criteria, derivation_operator, definition, status,
value, field_values, effective_time, inline_code_list, negation, negation_code_list_id, temporal_references, subset_operators,specific_occurrence,specific_occurrence_const)
end
# this method creates V1 data criteria for the measurement period. These data criteria can be
# referenced properly within the restrictions
def create_measure_period_v1_data_criteria(doc,measure_period,v1_data_criteria_by_id)
attributes = doc[:attributes]
attributes.keys.each {|key| attributes[key.to_s] = attributes[key]}
measure_period_key = attributes['MEASUREMENT_PERIOD'][:id]
measure_start_key = attributes['MEASUREMENT_START_DATE'][:id]
measure_end_key = attributes['MEASUREMENT_END_DATE'][:id]
@measure_period_v1_keys = {measure_start: measure_start_key, measure_end: measure_end_key, measure_period: measure_period_key}
type = 'variable'
code_list_id,negation_code_list_id,property,status,field_values,effective_time,inline_code_list,children_criteria,derivation_operator,temporal_references,subset_operators=nil
#####
##
######### SET MEASURE PERIOD
##
#####
measure_period_id = HQMF::Document::MEASURE_PERIOD_ID
value = measure_period
measure_criteria = HQMF::DataCriteria.new(measure_period_id,measure_period_id,nil,measure_period_id,code_list_id,children_criteria,derivation_operator,measure_period_id,status,
value,field_values,effective_time,inline_code_list, false, nil, temporal_references,subset_operators,nil,nil)
# set the measure period data criteria for all measure period keys
v1_data_criteria_by_id[measure_period_key] = measure_criteria
v1_data_criteria_by_id[measure_start_key] = measure_criteria
v1_data_criteria_by_id[measure_end_key] = measure_criteria
@measure_period_criteria = measure_criteria
end
def self.title_from_description(title, description)
title.gsub(/^#{Regexp.escape(description).gsub('\\ ',':?,?\\ ')}:\s*/i,'')
end
def self.convert_key(key)
key.to_s.downcase.gsub('_', ' ').split(' ').map {|w| w.capitalize }.join('')
end
end
|
rossf7/elasticrawl | lib/elasticrawl/config.rb | Elasticrawl.Config.status_message | ruby | def status_message(bucket_name, state)
message = ['', "Bucket s3://#{bucket_name} #{state}"]
message << "Config dir #{config_dir} #{state}"
state = 'complete' if state == 'created'
message << "Config #{state}"
message.join("\n")
end | Notifies user of results of init or destroy commands. | train | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L232-L240 | class Config
CONFIG_DIR = '.elasticrawl'
DATABASE_FILE = 'elasticrawl.sqlite3'
TEMPLATES_DIR = '../../templates'
TEMPLATE_FILES = ['aws.yml', 'cluster.yml', 'jobs.yml']
attr_reader :access_key_id
attr_reader :secret_access_key
# Sets the AWS access credentials needed for the S3 and EMR API calls.
def initialize(access_key_id = nil, secret_access_key = nil)
# Credentials have been provided to the init command.
@access_key_id = access_key_id
@secret_access_key = secret_access_key
# If credentials are not set then check if they are available in aws.yml.
if dir_exists?
config = load_config('aws')
key = config['access_key_id']
secret = config['secret_access_key']
@access_key_id ||= key unless key == 'ACCESS_KEY_ID'
@secret_access_key ||= secret unless secret == 'SECRET_ACCESS_KEY'
end
# If credentials are still not set then check AWS environment variables.
@access_key_id ||= ENV['AWS_ACCESS_KEY_ID']
@secret_access_key ||= ENV['AWS_SECRET_ACCESS_KEY']
# Set AWS credentials for use when accessing the S3 API.
AWS.config(:access_key_id => @access_key_id,
:secret_access_key => @secret_access_key)
end
# Returns the location of the config directory.
def config_dir
File.join(Dir.home, CONFIG_DIR)
end
# Checks if the configuration directory exists.
def dir_exists?
Dir.exists?(config_dir)
end
# Loads a YAML configuration file.
def load_config(config_file)
if dir_exists?
begin
config_file = File.join(config_dir, "#{config_file}.yml")
config = YAML::load(File.open(config_file))
rescue StandardError => e
raise FileAccessError, e.message
end
else
raise ConfigDirMissingError, 'Config dir missing. Run init command'
end
end
# Loads the sqlite database. If no database exists it will be created
# and the database migrations will be run.
def load_database
if dir_exists?
config = {
'adapter' => 'sqlite3',
'database' => File.join(config_dir, DATABASE_FILE),
'pool' => 5,
'timeout' => 5000
}
begin
ActiveRecord::Base.establish_connection(config)
ActiveRecord::Migrator.migrate(File.join(File.dirname(__FILE__), \
'../../db/migrate'), ENV['VERSION'] ? ENV['VERSION'].to_i : nil )
rescue StandardError => e
raise DatabaseAccessError, e.message
end
else
raise ConfigDirMissingError, 'Config dir missing. Run init command'
end
end
# Checks if a S3 bucket name is in use.
def bucket_exists?(bucket_name)
begin
s3 = AWS::S3.new
s3.buckets[bucket_name].exists?
rescue AWS::S3::Errors::SignatureDoesNotMatch => e
raise AWSCredentialsInvalidError, 'AWS access credentials are invalid'
rescue AWS::Errors::Base => s3e
raise S3AccessError.new(s3e.http_response), s3e.message
end
end
# Creates the S3 bucket and config directory. Deploys the config templates
# and creates the sqlite database.
def create(bucket_name)
create_bucket(bucket_name)
deploy_templates(bucket_name)
load_database
status_message(bucket_name, 'created')
end
# Deletes the S3 bucket and config directory.
def delete
bucket_name = load_config('jobs')['s3_bucket_name']
delete_bucket(bucket_name)
delete_config_dir
status_message(bucket_name, 'deleted')
end
# Displayed by destroy command to confirm deletion.
def delete_warning
bucket_name = load_config('jobs')['s3_bucket_name']
message = ['WARNING:']
message << "Bucket s3://#{bucket_name} and its data will be deleted"
message << "Config dir #{config_dir} will be deleted"
message.join("\n")
end
# Displayed by init command.
def access_key_prompt
prompt = "Enter AWS Access Key ID:"
prompt += " [#{@access_key_id}]" if @access_key_id.present?
prompt
end
# Displayed by init command.
def secret_key_prompt
prompt = "Enter AWS Secret Access Key:"
prompt += " [#{@secret_access_key}]" if @secret_access_key.present?
prompt
end
private
# Creates a bucket using the S3 API.
def create_bucket(bucket_name)
begin
s3 = AWS::S3.new
s3.buckets.create(bucket_name)
rescue AWS::Errors::Base => s3e
raise S3AccessError.new(s3e.http_response), s3e.message
end
end
# Deletes a bucket and its contents using the S3 API.
def delete_bucket(bucket_name)
begin
s3 = AWS::S3.new
bucket = s3.buckets[bucket_name]
bucket.delete!
rescue AWS::Errors::Base => s3e
raise S3AccessError.new(s3e.http_response), s3e.message
end
end
# Creates config directory and copies config templates into it.
# Saves S3 bucket name to jobs.yml and AWS credentials to aws.yml.
def deploy_templates(bucket_name)
begin
Dir.mkdir(config_dir, 0755) if dir_exists? == false
TEMPLATE_FILES.each do |template_file|
FileUtils.cp(File.join(File.dirname(__FILE__), TEMPLATES_DIR, template_file),
File.join(config_dir, template_file))
end
save_config('jobs', { 'BUCKET_NAME' => bucket_name })
save_aws_config
rescue StandardError => e
raise FileAccessError, e.message
end
end
# Saves AWS access credentials to aws.yml unless they are configured as
# environment variables.
def save_aws_config
env_key = ENV['AWS_ACCESS_KEY_ID']
env_secret = ENV['AWS_SECRET_ACCESS_KEY']
creds = {}
creds['ACCESS_KEY_ID'] = @access_key_id unless @access_key_id == env_key
creds['SECRET_ACCESS_KEY'] = @secret_access_key \
unless @secret_access_key == env_secret
save_config('aws', creds)
end
# Saves config values by overwriting placeholder values in template.
def save_config(template, params)
config_file = File.join(config_dir, "#{template}.yml")
config = File.read(config_file)
params.map { |key, value| config = config.gsub(key, value) }
File.open(config_file, 'w') { |file| file.write(config) }
end
# Deletes the config directory including its contents.
def delete_config_dir
begin
FileUtils.rm_r(config_dir) if dir_exists?
rescue StandardError => e
raise FileAccessError, e.message
end
end
# Notifies user of results of init or destroy commands.
end
|
puppetlabs/beaker-hostgenerator | lib/beaker-hostgenerator/generator.rb | BeakerHostGenerator.Generator.unstringify_values! | ruby | def unstringify_values!(config)
config['HOSTS'].each do |host, settings|
settings.each do |k, v|
config['HOSTS'][host][k] = unstringify_value(v)
end
end
config['CONFIG'].each do |k, v|
config['CONFIG'][k] = unstringify_value(v)
end
end | Passes over all the values of config['HOSTS'] and config['CONFIG'] and
subsequent arrays to convert numbers or booleans into proper integer
or boolean types. | train | https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/generator.rb#L128-L137 | class Generator
include BeakerHostGenerator::Data
include BeakerHostGenerator::Parser
include BeakerHostGenerator::Roles
# Main host generation entry point, returns a Ruby map for the given host
# specification and optional configuration.
#
# @param layout [String] The raw hosts specification user input.
# For example `"centos6-64m-redhat7-64a"`.
# @param options [Hash] Global, optional configuration such as the default
# hypervisor or OS info version.
#
# @returns [Hash] A complete Ruby map as defining the HOSTS and CONFIG
# sections as required by Beaker.
def generate(layout, options)
layout = prepare(layout)
tokens = tokenize_layout(layout)
config = {}.deep_merge(BASE_CONFIG)
nodeid = Hash.new(1)
ostype = nil
bhg_version = options[:osinfo_version] || 0
tokens.each do |token|
if is_ostype_token?(token, bhg_version)
if nodeid[ostype] == 1 and ostype != nil
raise "Error: no nodes generated for #{ostype}"
end
ostype = token
next
end
node_info = parse_node_info_token(token)
# Build node host name
platform = "#{ostype}-#{node_info['bits']}"
host_name = "#{platform}-#{nodeid[ostype]}"
node_info['platform'] = platform
node_info['ostype'] = ostype
node_info['nodeid'] = nodeid[ostype]
host_config = base_host_config(options)
# Delegate to the hypervisor
hypervisor = BeakerHostGenerator::Hypervisor.create(node_info, options)
host_config = hypervisor.generate_node(node_info, host_config, bhg_version)
config['CONFIG'].deep_merge!(hypervisor.global_config())
# Merge in any arbitrary key-value host settings. Treat the 'hostname'
# setting specially, and don't merge it in as an arbitrary setting.
arbitrary_settings = node_info['host_settings']
host_name = arbitrary_settings.delete('hostname') if
arbitrary_settings.has_key?('hostname')
host_config.merge!(arbitrary_settings)
if PE_USE_WIN32 && ostype =~ /windows/ && node_info['bits'] == "64"
host_config['ruby_arch'] = 'x86'
host_config['install_32'] = true
end
generate_host_roles!(host_config, node_info, options)
config['HOSTS'][host_name] = host_config
nodeid[ostype] += 1
end
# Merge in global configuration settings after the hypervisor defaults
if options[:global_config]
decoded = prepare(options[:global_config])
# Support for strings without '{}' was introduced, so just double
# check here to ensure that we pass in values surrounded by '{}'.
if !decoded.start_with?('{')
decoded = "{#{decoded}}"
end
global_config = settings_string_to_map(decoded)
config['CONFIG'].deep_merge!(global_config)
end
# Munge non-string scalar values into proper data types
unstringify_values!(config)
return config
end
def get_host_roles(node_info)
roles = []
node_info['roles'].each_char do |c|
roles << ROLES[c]
end
node_info['arbitrary_roles'].each do |role|
roles << role
end
return roles
end
private
def generate_host_roles!(host_config, node_info, options)
if not options[:disable_default_role]
host_config['roles'] = ['agent']
else
host_config['roles'] = []
end
host_config['roles'].concat get_host_roles(node_info)
host_config['roles'].uniq!
if not options[:disable_role_config]
host_config['roles'].each do |role|
host_config.deep_merge! get_role_config(role)
end
end
end
# Passes over all the values of config['HOSTS'] and config['CONFIG'] and
# subsequent arrays to convert numbers or booleans into proper integer
# or boolean types.
# Attempts to convert numeric strings and boolean strings into proper
# integer and boolean types. If value is an array, it will recurse
# through those values.
# Returns the input value if it's not a number string or boolean string.
# For example "123" would be converted to 123, and "true"/"false" would be
# converted to true/false.
# The only valid boolean-strings are "true" and "false".
def unstringify_value(value)
result = Integer(value) rescue value
if value == 'true'
result = true
elsif value == 'false'
result = false
elsif value.kind_of?(Array)
value.each_with_index do |v, i|
result[i] = unstringify_value(v)
end
end
result
end
end
|
mswart/cany | lib/cany/recipe.rb | Cany.Recipe.exec | ruby | def exec(*args)
args.flatten!
Cany.logger.info args.join(' ')
unless system(*args)
raise CommandExecutionFailed.new args
end
end | API to use inside the recipe
@api public
Run a command inside the build directory. In most cases it is not needed to call this method
directly. Look at the other helper methods.
The method expects as arguments the program name and additional parameters for the program.
The arguments can be group with arguments, but must not:
@example
exec 'echo', %w(a b)
exec ['echo', 'a', 'b']
exec 'echo', 'a', 'b'
@raise [CommandExecutionFailed] if the executed program exists with a
non-zero exit code. | train | https://github.com/mswart/cany/blob/0d2bf4d3704d4e9a222b11f6d764b57234ddf36d/lib/cany/recipe.rb#L69-L75 | class Recipe
# @api public
# This method should be call in subclasses to register new recipe instances. Cany ignores any
# recipe subclasses which does not call register_as. If multiple recipes register on the same
# name the later one will overwrite the earlier one and therefore used by Cany.
# @param [Symbol] name A ruby symbol as name for the recipe. It should be short and recognizable
def self.register_as(name)
@@recipes ||= {}
@@recipes[name] = self
module_eval(<<-EOS, __FILE__, __LINE__)
def name
:#{name}
end
EOS
end
# @api public
# Looks for the class registered for the given name
# @param [Symbol] name the name the class is search for
# @return [Cany::Recipe] Returns the found class or nil
# @raise UnknownRecipe if there is no recipe registered for this name.
def self.from_name(name)
raise UnknownRecipe.new(name) unless @@recipes[name]
@@recipes[name]
end
# Creates a new instance of this recipe
# @param [Cany::Specification] spec Specification object
def initialize(spec, &configure_block)
@spec = spec
@inner = nil
@hooks = Hash[(self.class.defined_hooks || []).map do |name|
[name, Cany.hash_with_array_as_default]
end]
@options = Hash[(self.class.defined_options || {}).map do |name, default|
[name, default.dup]
end]
self.class.const_get(:DSL).new(self).exec(&configure_block) if configure_block
end
# Specify the inner recipe for the current one.
# @param [Cany::Recipe, nil] inner Inner recipes should should be call between the pre and post
# actions of this class. Nil means most inner recipes.
def inner=(inner)
@inner = inner
end
attr_reader :spec, :inner
# API to use inside the recipe
##############################
# @api public
# Run a command inside the build directory. In most cases it is not needed to call this method
# directly. Look at the other helper methods.
#
# The method expects as arguments the program name and additional parameters for the program.
# The arguments can be group with arguments, but must not:
# @example
# exec 'echo', %w(a b)
# exec ['echo', 'a', 'b']
# exec 'echo', 'a', 'b'
# @raise [CommandExecutionFailed] if the executed program exists with a
# non-zero exit code.
# exec is special name in same situations it may no work but this alias should work always
alias :exec_ :exec
# @api public
# Run a ruby task (like gem, bundle, rake ...)
#
# The method expects as arguments the program name and additional parameters for the program.
# See exec for more examples
def ruby_bin(*args)
exec RbConfig.ruby, '-S', *args
end
# @api public
# Install files or directory from the build directory
# @param source[String] The relative file name to a filename or directory inside the build
# directory that should be installed/copied into the destination package
# @param destination[String] The diretory name into that the file or directory should be
# installed
def install(source, destination)
exec 'dh_install', source, destination
end
# @api public
# Install a file. The content is passed as argument. This method is designed to be used by
# recipes to create files dynamically.
# @param [String] filename The absolute file name for the file inside the package.
# @param [String] content The file content
def install_content(filename, content)
FileUtils.mkdir_p File.dirname File.join('debian', spec.name, filename)
File.open File.join('debian', spec.name, filename), 'w' do |f|
f.write content
end
end
# @api public
# Installs/creates an empty directory
# @param [String] path The path name
def install_dir(path)
exec 'dh_installdirs', path
end
# @api public
# Create a file named destination as a link to a file named source
def install_link(source, destination)
exec 'dh_link', source, destination
end
# @api public
# Specify a command call (program + args) that should be installed as service and started
# automatically.
# This method should be only call inside the binary step.
# @param name[Symbol] A short identifier. Used to separate different services. E.g. the name
# of the web server that is launched by this command (like puma, unicorn, thin)
# @param command[Array<String>] The command that should be started and its parameter. The first
# element is the command name - can be absolute or relative path name (than searched in path)
# @param opts[Hash] Service behavior options
# @option opts[String] :user As which user should the command executed (default is root)
# @option opts[String] :group As which group should the command executed (default is root)
def install_service(*args)
recipe(:system).install_service(*args)
end
# @api public
# Ensure that the given files or directories are no present. Directories are removed
# recursively.
def rmtree(*args)
args.flatten.each do |path|
::FileUtils.remove_entry path if File.exists? path
end
end
class << self
attr_accessor :defined_hooks, :defined_options
# @api public
# Define a new hook
# @param name[Symbol]
def hook(name)
@defined_hooks ||= []
@defined_hooks << name
end
# @api public
# Define a configure option. These kind of option are design for other
# recipes not for the user. See Recipe::DSL for this.
# @param name[Symbol] The name of the option. The option name is scoped
# inside a recipe.
def option(name, default={})
@defined_options ||= {}
@defined_options[name] = default
end
end
def hook(name)
@hooks[name].tap do |hook|
raise UnknownHook.new name unless hook
end
end
# @api public
# Ask for the current values for a defined option
def option(name)
@options[name].tap do |option|
raise UnknownOption.new name unless option
end
end
# @api public
# Configure an other recipe
# @param name[Symbol] The option name
# @param options[Hash] The configuration data itself.
def configure(name, options)
option(name).merge! options
end
# @api public
# Run defined actions for a hook
# @param name[Symbol] hook identification, no error is raised on unknown hooks
# @param state[Symbol] state that should be executed (:before, :after or :around)
def run_hook(name, state)
hook(name)[state].each do |block|
Cany.logger.info "run #{block} for hook #{name} in state #{state} ..."
instance_eval(&block)
end
end
# @api public
# Access the recipe instance from another loaded recipe of this
# specification
# @param name[Symbol] recipe name
def recipe(name)
return spec.system_recipe if name == :system
recipe_class = Recipe.from_name(name)
@spec.recipes.each do |one_recipe|
return one_recipe if one_recipe.instance_of? recipe_class
end
raise UnloadedRecipe.new name
end
# @api public
# Adds a new dependency for the software. See Cany::Dependency for a more
# abstract description about dependencies
# See Cany::Mixins::DependMixin for parameter description
include Cany::Mixins::DependMixin
def depend(*args)
@spec.dependencies << create_dep(*args)
end
# default implementation:
#########################
# @!group Recipe Steps - to be overridden in subclass
# @api public
# Prepares the recipes to run things. This is call exactly once for all recipes before
# recipes actions are executed.
def prepare
end
# @api public
# This step is executed to create the distribution specific packages from canspec. The recipe
# can e.g. add additional dependencies or adjust the package meta data.
def create(creator)
end
# @api public
# clean the build directory from all temporary and created files
def clean
inner.clean
end
# @api public
# build the program (means ./configure and make)
def build
inner.build
end
# @api public
# create binary (package) version of this file (means make install)
def binary
inner.binary
end
# @!endgroup
# This superclass helps recipes to create easily an own mini DSL to let the user configure the
# recipe with it.
class DSL
def initialize(recipe)
@recipe = recipe
end
# Evaluate a given block inside the dsl.
def exec(&block)
instance_eval(&block)
end
# This is a simple delegate helper. It can be used to pass option directly to recipe instance.
# @param [Symbol] param1 Multiple symbol names
def self.delegate(*methods)
methods.each do |method|
module_eval(<<-EOS, __FILE__, __LINE__)
def #{method}(*args, &block)
@recipe.send :'#{method}=', *args, &block
end
EOS
end
end
def before(hook_name, &block)
@recipe.hook(hook_name)[:before] << block
end
def after(hook_name, &block)
@recipe.hook(hook_name)[:after] << block
end
def around(hook_name, &block)
@recipe.hook(hook_name)[:around] << block
end
end
end
|
fnando/troy | lib/troy/page.rb | Troy.Page.render | ruby | def render
ExtensionMatcher.new(path)
.default { content }
.on("html") { compress render_erb }
.on("md") { compress render_erb }
.on("erb") { compress render_erb }
.match
end | Render the current page. | train | https://github.com/fnando/troy/blob/6940116610abef3490da168c31a19fc26840cb99/lib/troy/page.rb#L73-L80 | class Page
extend Forwardable
def_delegators :meta, :template
# Set the page path, which must contain a valid
# meta section and page content.
#
attr_reader :path
# Set the meta data for this particular page.
#
attr_reader :meta
# Set the current site object, which contains reference to
# all existing pages.
#
attr_reader :site
# Initialize a new page, which can be simply rendered or
# persisted to the filesystem.
#
def initialize(site, path, meta = nil)
@site = site
@path = path
@meta = meta || Meta.new(path)
end
#
#
def method_missing(name, *args, &block)
return meta[name.to_s] if meta.key?(name.to_s)
super
end
#
#
def respond_to_missing?(name, include_private = false)
meta.key?(name.to_s)
end
#
#
def content
ExtensionMatcher.new(path)
.default { meta.content }
.on("builder") { XML.new(meta.content, to_context).to_xml }
.on("erb") { EmbeddedRuby.new(meta.content, to_context).render }
.on("md") { Markdown.new(meta.content).to_html }
.on("txt") { EmbeddedRuby.new(meta.content, to_context).render }
.match
end
#
#
def to_context
{
page: self,
site: site
}
end
#
#
def compress(content)
content = HtmlPress.press(content) if config.assets.compress_html
content
end
# Render the current page.
#
#
#
def permalink
meta.fetch("permalink", File.basename(path).gsub(/\..*?$/, ""))
end
#
#
def filename
ExtensionMatcher.new(path)
.default { "#{permalink}.html" }
.on("builder") { "#{permalink}.xml" }
.on("xml") { "#{permalink}.xml" }
.on("txt") { "#{permalink}.txt" }
.match
end
#
#
def layout
site.root.join("layouts/#{meta.fetch("layout", "default")}.erb")
end
#
#
def render_erb
if layout.exist?
EmbeddedRuby.new(
layout.read,
to_context.merge(content: content)
).render
else
content
end
end
# Save current page to the specified path.
#
def save_to(path)
File.open(path, "w") do |file|
I18n.with_locale(meta.locale) do
file << render
end
end
end
#
#
def output_file
base = File.dirname(path)
.gsub(site.root.join("source").to_s, "")
.gsub(%r[^/], "")
site.root.join("public", base, filename)
end
#
#
def save
FileUtils.mkdir_p(File.dirname(output_file))
save_to(output_file)
end
#
#
def config
Troy.configuration
end
end
|
sugaryourcoffee/syclink | lib/syclink/designer.rb | SycLink.Designer.remove_links_from_file | ruby | def remove_links_from_file(file)
urls = File.foreach(file).map { |url| url.chomp unless url.empty? }
remove_links(urls)
end | Deletes links based on URLs that are provided in a file. Each URL has to
be in one line | train | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L122-L125 | class Designer
# extend Forwardable
# def_delegators :@website, :report_links_availability
include Infrastructure
# The website the designer is working on
attr_accessor :website
# Creates a new website where designer can operate on
def new_website(title = "SYC LINK")
@website = Website.new(title)
end
# Adds a link based on the provided arguments to the website
def add_link(url, args = {})
website.add_link(Link.new(url, args))
end
# Reads arguments from a CSV file and creates links accordingly. The links
# are added to the websie
def add_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.add_link(Link.new(url, { name: name,
description: description,
tag: tag }))
end
end
# Accepts and SycLink::Importer to import Links and add them to the website
def import_links(importer)
importer.links.each do |link|
website.add_link(link)
end
end
# Export links to specified format
def export(format)
message = "to_#{format.downcase}"
if website.respond_to? message
website.send(message)
else
raise "cannot export to #{format}"
end
end
# List links contained in the website and optionally filter on attributes
def list_links(args = {})
website.list_links(args)
end
# Finds links based on a search string
def find_links(search)
website.find_links(search)
end
# Check links availability. Takes a filter which values to return and
# whether to return available, unavailable or available and unavailable
# links. In the following example only unavailable links' url and response
# would be returned
# report_links_availability(available: false,
# unavailable: false,
# columns: "url,response")
def report_links_availability(opts)
cols = opts[:columns].gsub(/ /, "").split(',')
website.report_links_availability.map do |url, response|
result = if response == "200" and opts[:available]
{ "url" => url, "response" => response }
elsif response != "200" and opts[:unavailable]
{ "url" => url, "response" => response }
end
next if result.nil?
cols.inject([]) { |res, c| res << result[c.downcase] }
end.compact
end
# Updates a link. The link is identified by the URL. If there is more than
# one link with the same URL, only the first link is updated
def update_link(url, args)
website.find_links(url).first.update(args)
end
# Updates links read from a file
def update_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.find_links(url).first.update({ name: name,
description: description,
tag: tag })
end
end
# Merge links with same URL
def merge_links
website.merge_links_on(:url)
end
# Deletes one or more links from the website. Returns the deleted links.
# Expects the links provided in an array
def remove_links(urls)
urls.map { |url| list_links({ url: url }) }.flatten.compact.each do |link|
website.remove_link(link)
end
end
# Deletes links based on URLs that are provided in a file. Each URL has to
# be in one line
# Saves the website to the specified directory with the downcased name of
# the website and the extension 'website'. The website is save as YAML
def save_website(directory)
File.open(yaml_file(directory, website.title), 'w') do |f|
YAML.dump(website, f)
end
end
# Loads a website based on the provided YAML-file and asigns it to the
# designer to operate on
def load_website(website)
@website = YAML.load_file(website)
end
# Deletes the website if it already exists
def delete_website(directory)
if File.exists? yaml_file(directory, website.title)
FileUtils.rm(yaml_file(directory, website.title))
end
end
# Creates the html representation of the website. The website is saved to
# the directory with websites title and needs an erb-template where the
# links are integrated to. An example template can be found at
# templates/syclink.html.erb
def create_website(directory, template_filename)
template = File.read(template_filename)
File.open(html_file(directory, website.title), 'w') do |f|
f.puts website.to_html(template)
end
end
end
|
hashicorp/vagrant | lib/vagrant/box.rb | Vagrant.Box.has_update? | ruby | def has_update?(version=nil, download_options: {})
if !@metadata_url
raise Errors::BoxUpdateNoMetadata, name: @name
end
if download_options.delete(:automatic_check) && !automatic_update_check_allowed?
@logger.info("Skipping box update check")
return
end
version += ", " if version
version ||= ""
version += "> #{@version}"
md = self.load_metadata(download_options)
newer = md.version(version, provider: @provider)
return nil if !newer
[md, newer, newer.provider(@provider)]
end | Checks if the box has an update and returns the metadata, version,
and provider. If the box doesn't have an update that satisfies the
constraints, it will return nil.
This will potentially make a network call if it has to load the
metadata from the network.
@param [String] version Version constraints the update must
satisfy. If nil, the version constrain defaults to being a
larger version than this box.
@return [Array] | train | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L155-L173 | class Box
include Comparable
# Number of seconds to wait between checks for box updates
BOX_UPDATE_CHECK_INTERVAL = 3600
# The box name. This is the logical name used when adding the box.
#
# @return [String]
attr_reader :name
# This is the provider that this box is built for.
#
# @return [Symbol]
attr_reader :provider
# The version of this box.
#
# @return [String]
attr_reader :version
# This is the directory on disk where this box exists.
#
# @return [Pathname]
attr_reader :directory
# This is the metadata for the box. This is read from the "metadata.json"
# file that all boxes require.
#
# @return [Hash]
attr_reader :metadata
# This is the URL to the version info and other metadata for this
# box.
#
# @return [String]
attr_reader :metadata_url
# This is used to initialize a box.
#
# @param [String] name Logical name of the box.
# @param [Symbol] provider The provider that this box implements.
# @param [Pathname] directory The directory where this box exists on
# disk.
def initialize(name, provider, version, directory, **opts)
@name = name
@version = version
@provider = provider
@directory = directory
@metadata_url = opts[:metadata_url]
metadata_file = directory.join("metadata.json")
raise Errors::BoxMetadataFileNotFound, name: @name if !metadata_file.file?
begin
@metadata = JSON.parse(directory.join("metadata.json").read)
rescue JSON::ParserError
raise Errors::BoxMetadataCorrupted, name: @name
end
@logger = Log4r::Logger.new("vagrant::box")
end
# This deletes the box. This is NOT undoable.
def destroy!
# Delete the directory to delete the box.
FileUtils.rm_r(@directory)
# Just return true always
true
rescue Errno::ENOENT
# This means the directory didn't exist. Not a problem.
return true
end
# Checks if this box is in use according to the given machine
# index and returns the entries that appear to be using the box.
#
# The entries returned, if any, are not tested for validity
# with {MachineIndex::Entry#valid?}, so the caller should do that
# if the caller cares.
#
# @param [MachineIndex] index
# @return [Array<MachineIndex::Entry>]
def in_use?(index)
results = []
index.each do |entry|
box_data = entry.extra_data["box"]
next if !box_data
# If all the data matches, record it
if box_data["name"] == self.name &&
box_data["provider"] == self.provider.to_s &&
box_data["version"] == self.version.to_s
results << entry
end
end
return nil if results.empty?
results
end
# Loads the metadata URL and returns the latest metadata associated
# with this box.
#
# @param [Hash] download_options Options to pass to the downloader.
# @return [BoxMetadata]
def load_metadata(**download_options)
tf = Tempfile.new("vagrant-load-metadata")
tf.close
url = @metadata_url
if File.file?(url) || url !~ /^[a-z0-9]+:.*$/i
url = File.expand_path(url)
url = Util::Platform.cygwin_windows_path(url)
url = "file:#{url}"
end
opts = { headers: ["Accept: application/json"] }.merge(download_options)
Util::Downloader.new(url, tf.path, **opts).download!
BoxMetadata.new(File.open(tf.path, "r"))
rescue Errors::DownloaderError => e
raise Errors::BoxMetadataDownloadError,
message: e.extra_data[:message]
ensure
tf.unlink if tf
end
# Checks if the box has an update and returns the metadata, version,
# and provider. If the box doesn't have an update that satisfies the
# constraints, it will return nil.
#
# This will potentially make a network call if it has to load the
# metadata from the network.
#
# @param [String] version Version constraints the update must
# satisfy. If nil, the version constrain defaults to being a
# larger version than this box.
# @return [Array]
# Check if a box update check is allowed. Uses a file
# in the box data directory to track when the last auto
# update check was performed and returns true if the
# BOX_UPDATE_CHECK_INTERVAL has passed.
#
# @return [Boolean]
def automatic_update_check_allowed?
check_path = directory.join("box_update_check")
if check_path.exist?
last_check_span = Time.now.to_i - check_path.mtime.to_i
if last_check_span < BOX_UPDATE_CHECK_INTERVAL
@logger.info("box update check is under the interval threshold")
return false
end
end
FileUtils.touch(check_path)
true
end
# This repackages this box and outputs it to the given path.
#
# @param [Pathname] path The full path (filename included) of where
# to output this box.
# @return [Boolean] true if this succeeds.
def repackage(path)
@logger.debug("Repackaging box '#{@name}' to: #{path}")
Util::SafeChdir.safe_chdir(@directory) do
# Find all the files in our current directory and tar it up!
files = Dir.glob(File.join(".", "**", "*")).select { |f| File.file?(f) }
# Package!
Util::Subprocess.execute("bsdtar", "-czf", path.to_s, *files)
end
@logger.info("Repackaged box '#{@name}' successfully: #{path}")
true
end
# Implemented for comparison with other boxes. Comparison is
# implemented by comparing names and providers.
def <=>(other)
return super if !other.is_a?(self.class)
# Comparison is done by composing the name and provider
"#{@name}-#{@version}-#{@provider}" <=>
"#{other.name}-#{other.version}-#{other.provider}"
end
end
|
igrigorik/http-2 | lib/http/2/framer.rb | HTTP2.Framer.generate | ruby | def generate(frame)
bytes = Buffer.new
length = 0
frame[:flags] ||= []
frame[:stream] ||= 0
case frame[:type]
when :data
bytes << frame[:payload]
length += frame[:payload].bytesize
when :headers
if frame[:weight] || frame[:stream_dependency] || !frame[:exclusive].nil?
unless frame[:weight] && frame[:stream_dependency] && !frame[:exclusive].nil?
fail CompressionError, "Must specify all of priority parameters for #{frame[:type]}"
end
frame[:flags] += [:priority] unless frame[:flags].include? :priority
end
if frame[:flags].include? :priority
bytes << [(frame[:exclusive] ? EBIT : 0) | (frame[:stream_dependency] & RBIT)].pack(UINT32)
bytes << [frame[:weight] - 1].pack(UINT8)
length += 5
end
bytes << frame[:payload]
length += frame[:payload].bytesize
when :priority
unless frame[:weight] && frame[:stream_dependency] && !frame[:exclusive].nil?
fail CompressionError, "Must specify all of priority parameters for #{frame[:type]}"
end
bytes << [(frame[:exclusive] ? EBIT : 0) | (frame[:stream_dependency] & RBIT)].pack(UINT32)
bytes << [frame[:weight] - 1].pack(UINT8)
length += 5
when :rst_stream
bytes << pack_error(frame[:error])
length += 4
when :settings
if (frame[:stream]).nonzero?
fail CompressionError, "Invalid stream ID (#{frame[:stream]})"
end
frame[:payload].each do |(k, v)|
if k.is_a? Integer
DEFINED_SETTINGS.value?(k) || next
else
k = DEFINED_SETTINGS[k]
fail CompressionError, "Unknown settings ID for #{k}" if k.nil?
end
bytes << [k].pack(UINT16)
bytes << [v].pack(UINT32)
length += 6
end
when :push_promise
bytes << [frame[:promise_stream] & RBIT].pack(UINT32)
bytes << frame[:payload]
length += 4 + frame[:payload].bytesize
when :ping
if frame[:payload].bytesize != 8
fail CompressionError, "Invalid payload size (#{frame[:payload].size} != 8 bytes)"
end
bytes << frame[:payload]
length += 8
when :goaway
bytes << [frame[:last_stream] & RBIT].pack(UINT32)
bytes << pack_error(frame[:error])
length += 8
if frame[:payload]
bytes << frame[:payload]
length += frame[:payload].bytesize
end
when :window_update
bytes << [frame[:increment] & RBIT].pack(UINT32)
length += 4
when :continuation
bytes << frame[:payload]
length += frame[:payload].bytesize
when :altsvc
bytes << [frame[:max_age], frame[:port]].pack(UINT32 + UINT16)
length += 6
if frame[:proto]
fail CompressionError, 'Proto too long' if frame[:proto].bytesize > 255
bytes << [frame[:proto].bytesize].pack(UINT8)
bytes << frame[:proto].force_encoding(Encoding::BINARY)
length += 1 + frame[:proto].bytesize
else
bytes << [0].pack(UINT8)
length += 1
end
if frame[:host]
fail CompressionError, 'Host too long' if frame[:host].bytesize > 255
bytes << [frame[:host].bytesize].pack(UINT8)
bytes << frame[:host].force_encoding(Encoding::BINARY)
length += 1 + frame[:host].bytesize
else
bytes << [0].pack(UINT8)
length += 1
end
if frame[:origin]
bytes << frame[:origin]
length += frame[:origin].bytesize
end
end
# Process padding.
# frame[:padding] gives number of extra octets to be added.
# - http://tools.ietf.org/html/draft-ietf-httpbis-http2-16#section-6.1
if frame[:padding]
unless FRAME_TYPES_WITH_PADDING.include?(frame[:type])
fail CompressionError, "Invalid padding flag for #{frame[:type]}"
end
padlen = frame[:padding]
if padlen <= 0 || padlen > 256 || padlen + length > @max_frame_size
fail CompressionError, "Invalid padding #{padlen}"
end
length += padlen
bytes.prepend([padlen -= 1].pack(UINT8))
frame[:flags] << :padded
# Padding: Padding octets that contain no application semantic value.
# Padding octets MUST be set to zero when sending and ignored when
# receiving.
bytes << "\0" * padlen
end
frame[:length] = length
bytes.prepend(common_header(frame))
end | Generates encoded HTTP/2 frame.
- http://tools.ietf.org/html/draft-ietf-httpbis-http2
@param frame [Hash] | train | https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/framer.rb#L177-L320 | class Framer
include Error
# Default value of max frame size (16384 bytes)
DEFAULT_MAX_FRAME_SIZE = 2**14
# Current maximum frame size
attr_accessor :max_frame_size
# Maximum stream ID (2^31)
MAX_STREAM_ID = 0x7fffffff
# Maximum window increment value (2^31)
MAX_WINDOWINC = 0x7fffffff
# HTTP/2 frame type mapping as defined by the spec
FRAME_TYPES = {
data: 0x0,
headers: 0x1,
priority: 0x2,
rst_stream: 0x3,
settings: 0x4,
push_promise: 0x5,
ping: 0x6,
goaway: 0x7,
window_update: 0x8,
continuation: 0x9,
altsvc: 0xa,
}.freeze
FRAME_TYPES_WITH_PADDING = [:data, :headers, :push_promise].freeze
# Per frame flags as defined by the spec
FRAME_FLAGS = {
data: {
end_stream: 0,
padded: 3,
compressed: 5,
},
headers: {
end_stream: 0,
end_headers: 2,
padded: 3,
priority: 5,
},
priority: {},
rst_stream: {},
settings: { ack: 0 },
push_promise: {
end_headers: 2,
padded: 3,
},
ping: { ack: 0 },
goaway: {},
window_update: {},
continuation: { end_headers: 2 },
altsvc: {},
}.each_value(&:freeze).freeze
# Default settings as defined by the spec
DEFINED_SETTINGS = {
settings_header_table_size: 1,
settings_enable_push: 2,
settings_max_concurrent_streams: 3,
settings_initial_window_size: 4,
settings_max_frame_size: 5,
settings_max_header_list_size: 6,
}.freeze
# Default error types as defined by the spec
DEFINED_ERRORS = {
no_error: 0,
protocol_error: 1,
internal_error: 2,
flow_control_error: 3,
settings_timeout: 4,
stream_closed: 5,
frame_size_error: 6,
refused_stream: 7,
cancel: 8,
compression_error: 9,
connect_error: 10,
enhance_your_calm: 11,
inadequate_security: 12,
http_1_1_required: 13,
}.freeze
RBIT = 0x7fffffff
RBYTE = 0x0fffffff
EBIT = 0x80000000
UINT32 = 'N'.freeze
UINT16 = 'n'.freeze
UINT8 = 'C'.freeze
HEADERPACK = (UINT8 + UINT16 + UINT8 + UINT8 + UINT32).freeze
FRAME_LENGTH_HISHIFT = 16
FRAME_LENGTH_LOMASK = 0xFFFF
private_constant :RBIT, :RBYTE, :EBIT, :HEADERPACK, :UINT32, :UINT16, :UINT8
# Initializes new framer object.
#
def initialize
@max_frame_size = DEFAULT_MAX_FRAME_SIZE
end
# Generates common 9-byte frame header.
# - http://tools.ietf.org/html/draft-ietf-httpbis-http2-16#section-4.1
#
# @param frame [Hash]
# @return [String]
def common_header(frame)
header = []
unless FRAME_TYPES[frame[:type]]
fail CompressionError, "Invalid frame type (#{frame[:type]})"
end
if frame[:length] > @max_frame_size
fail CompressionError, "Frame size is too large: #{frame[:length]}"
end
if frame[:length] < 0
fail CompressionError, "Frame size is invalid: #{frame[:length]}"
end
if frame[:stream] > MAX_STREAM_ID
fail CompressionError, "Stream ID (#{frame[:stream]}) is too large"
end
if frame[:type] == :window_update && frame[:increment] > MAX_WINDOWINC
fail CompressionError, "Window increment (#{frame[:increment]}) is too large"
end
header << (frame[:length] >> FRAME_LENGTH_HISHIFT)
header << (frame[:length] & FRAME_LENGTH_LOMASK)
header << FRAME_TYPES[frame[:type]]
header << frame[:flags].reduce(0) do |acc, f|
position = FRAME_FLAGS[frame[:type]][f]
unless position
fail CompressionError, "Invalid frame flag (#{f}) for #{frame[:type]}"
end
acc | (1 << position)
end
header << frame[:stream]
header.pack(HEADERPACK) # 8+16,8,8,32
end
# Decodes common 9-byte header.
#
# @param buf [Buffer]
def read_common_header(buf)
frame = {}
len_hi, len_lo, type, flags, stream = buf.slice(0, 9).unpack(HEADERPACK)
frame[:length] = (len_hi << FRAME_LENGTH_HISHIFT) | len_lo
frame[:type], _ = FRAME_TYPES.find { |_t, pos| type == pos }
if frame[:type]
frame[:flags] = FRAME_FLAGS[frame[:type]].each_with_object([]) do |(name, pos), acc|
acc << name if (flags & (1 << pos)) > 0
end
end
frame[:stream] = stream & RBIT
frame
end
# Generates encoded HTTP/2 frame.
# - http://tools.ietf.org/html/draft-ietf-httpbis-http2
#
# @param frame [Hash]
# Decodes complete HTTP/2 frame from provided buffer. If the buffer
# does not contain enough data, no further work is performed.
#
# @param buf [Buffer]
def parse(buf)
return nil if buf.size < 9
frame = read_common_header(buf)
return nil if buf.size < 9 + frame[:length]
fail ProtocolError, 'payload too large' if frame[:length] > DEFAULT_MAX_FRAME_SIZE
buf.read(9)
payload = buf.read(frame[:length])
# Implementations MUST discard frames
# that have unknown or unsupported types.
# - http://tools.ietf.org/html/draft-ietf-httpbis-http2-16#section-5.5
return nil if frame[:type].nil?
# Process padding
padlen = 0
if FRAME_TYPES_WITH_PADDING.include?(frame[:type])
padded = frame[:flags].include?(:padded)
if padded
padlen = payload.read(1).unpack(UINT8).first
frame[:padding] = padlen + 1
fail ProtocolError, 'padding too long' if padlen > payload.bytesize
payload.slice!(-padlen, padlen) if padlen > 0
frame[:length] -= frame[:padding]
frame[:flags].delete(:padded)
end
end
case frame[:type]
when :data
frame[:payload] = payload.read(frame[:length])
when :headers
if frame[:flags].include? :priority
e_sd = payload.read_uint32
frame[:stream_dependency] = e_sd & RBIT
frame[:exclusive] = (e_sd & EBIT) != 0
frame[:weight] = payload.getbyte + 1
end
frame[:payload] = payload.read(frame[:length])
when :priority
e_sd = payload.read_uint32
frame[:stream_dependency] = e_sd & RBIT
frame[:exclusive] = (e_sd & EBIT) != 0
frame[:weight] = payload.getbyte + 1
when :rst_stream
frame[:error] = unpack_error payload.read_uint32
when :settings
# NOTE: frame[:length] might not match the number of frame[:payload]
# because unknown extensions are ignored.
frame[:payload] = []
unless (frame[:length] % 6).zero?
fail ProtocolError, 'Invalid settings payload length'
end
if (frame[:stream]).nonzero?
fail ProtocolError, "Invalid stream ID (#{frame[:stream]})"
end
(frame[:length] / 6).times do
id = payload.read(2).unpack(UINT16).first
val = payload.read_uint32
# Unsupported or unrecognized settings MUST be ignored.
# Here we send it along.
name, _ = DEFINED_SETTINGS.find { |_name, v| v == id }
frame[:payload] << [name, val] if name
end
when :push_promise
frame[:promise_stream] = payload.read_uint32 & RBIT
frame[:payload] = payload.read(frame[:length])
when :ping
frame[:payload] = payload.read(frame[:length])
when :goaway
frame[:last_stream] = payload.read_uint32 & RBIT
frame[:error] = unpack_error payload.read_uint32
size = frame[:length] - 8 # for last_stream and error
frame[:payload] = payload.read(size) if size > 0
when :window_update
frame[:increment] = payload.read_uint32 & RBIT
when :continuation
frame[:payload] = payload.read(frame[:length])
when :altsvc
frame[:max_age], frame[:port] = payload.read(6).unpack(UINT32 + UINT16)
len = payload.getbyte
frame[:proto] = payload.read(len) if len > 0
len = payload.getbyte
frame[:host] = payload.read(len) if len > 0
frame[:origin] = payload.read(payload.size) if payload.size > 0
# else # Unknown frame type is explicitly allowed
end
frame
end
private
def pack_error(e)
unless e.is_a? Integer
if DEFINED_ERRORS[e].nil?
fail CompressionError, "Unknown error ID for #{e}"
end
e = DEFINED_ERRORS[e]
end
[e].pack(UINT32)
end
def unpack_error(e)
name, _ = DEFINED_ERRORS.find { |_name, v| v == e }
name || error
end
end
|
hashicorp/vagrant | lib/vagrant/bundler.rb | Vagrant.Bundler.generate_builtin_set | ruby | def generate_builtin_set(system_plugins=[])
builtin_set = BuiltinSet.new
@logger.debug("Generating new builtin set instance.")
vagrant_internal_specs.each do |spec|
if !system_plugins.include?(spec.name)
builtin_set.add_builtin_spec(spec)
end
end
builtin_set
end | Generate the builtin resolver set | train | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L446-L455 | class Bundler
# Location of HashiCorp gem repository
HASHICORP_GEMSTORE = "https://gems.hashicorp.com/".freeze
# Default gem repositories
DEFAULT_GEM_SOURCES = [
HASHICORP_GEMSTORE,
"https://rubygems.org/".freeze
].freeze
def self.instance
@bundler ||= self.new
end
# @return [Pathname] Global plugin path
attr_reader :plugin_gem_path
# @return [Pathname] Vagrant environment specific plugin path
attr_reader :env_plugin_gem_path
def initialize
@plugin_gem_path = Vagrant.user_data_path.join("gems", RUBY_VERSION).freeze
@logger = Log4r::Logger.new("vagrant::bundler")
end
# Enable Vagrant environment specific plugins at given data path
#
# @param [Pathname] Path to Vagrant::Environment data directory
# @return [Pathname] Path to environment specific gem directory
def environment_path=(env_data_path)
@env_plugin_gem_path = env_data_path.join("plugins", "gems", RUBY_VERSION).freeze
end
# Initializes Bundler and the various gem paths so that we can begin
# loading gems.
def init!(plugins, repair=false)
if !@initial_specifications
@initial_specifications = Gem::Specification.find_all{true}
else
Gem::Specification.all = @initial_specifications
Gem::Specification.reset
end
# Add HashiCorp RubyGems source
if !Gem.sources.include?(HASHICORP_GEMSTORE)
current_sources = Gem.sources.sources.dup
Gem.sources.clear
Gem.sources << HASHICORP_GEMSTORE
current_sources.each do |src|
Gem.sources << src
end
end
# Generate dependencies for all registered plugins
plugin_deps = plugins.map do |name, info|
Gem::Dependency.new(name, info['installed_gem_version'].to_s.empty? ? '> 0' : info['installed_gem_version'])
end
@logger.debug("Current generated plugin dependency list: #{plugin_deps}")
# Load dependencies into a request set for resolution
request_set = Gem::RequestSet.new(*plugin_deps)
# Never allow dependencies to be remotely satisfied during init
request_set.remote = false
repair_result = nil
begin
# Compose set for resolution
composed_set = generate_vagrant_set
# Resolve the request set to ensure proper activation order
solution = request_set.resolve(composed_set)
rescue Gem::UnsatisfiableDependencyError => failure
if repair
raise failure if @init_retried
@logger.debug("Resolution failed but attempting to repair. Failure: #{failure}")
install(plugins)
@init_retried = true
retry
else
raise
end
end
# Activate the gems
activate_solution(solution)
full_vagrant_spec_list = @initial_specifications +
solution.map(&:full_spec)
if(defined?(::Bundler))
@logger.debug("Updating Bundler with full specification list")
::Bundler.rubygems.replace_entrypoints(full_vagrant_spec_list)
end
Gem.post_reset do
Gem::Specification.all = full_vagrant_spec_list
end
Gem::Specification.reset
nil
end
# Removes any temporary files created by init
def deinit
# no-op
end
# Installs the list of plugins.
#
# @param [Hash] plugins
# @param [Boolean] env_local Environment local plugin install
# @return [Array<Gem::Specification>]
def install(plugins, env_local=false)
internal_install(plugins, nil, env_local: env_local)
end
# Installs a local '*.gem' file so that Bundler can find it.
#
# @param [String] path Path to a local gem file.
# @return [Gem::Specification]
def install_local(path, opts={})
plugin_source = Gem::Source::SpecificFile.new(path)
plugin_info = {
plugin_source.spec.name => {
"gem_version" => plugin_source.spec.version.to_s,
"local_source" => plugin_source,
"sources" => opts.fetch(:sources, [])
}
}
@logger.debug("Installing local plugin - #{plugin_info}")
internal_install(plugin_info, nil, env_local: opts[:env_local])
plugin_source.spec
end
# Update updates the given plugins, or every plugin if none is given.
#
# @param [Hash] plugins
# @param [Array<String>] specific Specific plugin names to update. If
# empty or nil, all plugins will be updated.
def update(plugins, specific, **opts)
specific ||= []
update = opts.merge({gems: specific.empty? ? true : specific})
internal_install(plugins, update)
end
# Clean removes any unused gems.
def clean(plugins, **opts)
@logger.debug("Cleaning Vagrant plugins of stale gems.")
# Generate dependencies for all registered plugins
plugin_deps = plugins.map do |name, info|
gem_version = info['installed_gem_version']
gem_version = info['gem_version'] if gem_version.to_s.empty?
gem_version = "> 0" if gem_version.to_s.empty?
Gem::Dependency.new(name, gem_version)
end
@logger.debug("Current plugin dependency list: #{plugin_deps}")
# Load dependencies into a request set for resolution
request_set = Gem::RequestSet.new(*plugin_deps)
# Never allow dependencies to be remotely satisfied during cleaning
request_set.remote = false
# Sets that we can resolve our dependencies from. Note that we only
# resolve from the current set as all required deps are activated during
# init.
current_set = generate_vagrant_set
# Collect all plugin specifications
plugin_specs = Dir.glob(plugin_gem_path.join('specifications/*.gemspec').to_s).map do |spec_path|
Gem::Specification.load(spec_path)
end
# Include environment specific specification if enabled
if env_plugin_gem_path
plugin_specs += Dir.glob(env_plugin_gem_path.join('specifications/*.gemspec').to_s).map do |spec_path|
Gem::Specification.load(spec_path)
end
end
@logger.debug("Generating current plugin state solution set.")
# Resolve the request set to ensure proper activation order
solution = request_set.resolve(current_set)
solution_specs = solution.map(&:full_spec)
solution_full_names = solution_specs.map(&:full_name)
# Find all specs installed to plugins directory that are not
# found within the solution set.
plugin_specs.delete_if do |spec|
solution_full_names.include?(spec.full_name)
end
if env_plugin_gem_path
# If we are cleaning locally, remove any global specs. If
# not, remove any local specs
if opts[:env_local]
@logger.debug("Removing specifications that are not environment local")
plugin_specs.delete_if do |spec|
spec.full_gem_path.to_s.include?(plugin_gem_path.realpath.to_s)
end
else
@logger.debug("Removing specifications that are environment local")
plugin_specs.delete_if do |spec|
spec.full_gem_path.to_s.include?(env_plugin_gem_path.realpath.to_s)
end
end
end
@logger.debug("Specifications to be removed - #{plugin_specs.map(&:full_name)}")
# Now delete all unused specs
plugin_specs.each do |spec|
@logger.debug("Uninstalling gem - #{spec.full_name}")
Gem::Uninstaller.new(spec.name,
version: spec.version,
install_dir: plugin_gem_path,
all: true,
executables: true,
force: true,
ignore: true,
).uninstall_gem(spec)
end
solution.find_all do |spec|
plugins.keys.include?(spec.name)
end
end
# During the duration of the yielded block, Bundler loud output
# is enabled.
def verbose
if block_given?
initial_state = @verbose
@verbose = true
yield
@verbose = initial_state
else
@verbose = true
end
end
protected
def internal_install(plugins, update, **extra)
update = {} if !update.is_a?(Hash)
skips = []
source_list = {}
system_plugins = plugins.map do |plugin_name, plugin_info|
plugin_name if plugin_info["system"]
end.compact
installer_set = VagrantSet.new(:both)
installer_set.system_plugins = system_plugins
# Generate all required plugin deps
plugin_deps = plugins.map do |name, info|
gem_version = info['gem_version'].to_s.empty? ? '> 0' : info['gem_version']
if update[:gems] == true || (update[:gems].respond_to?(:include?) && update[:gems].include?(name))
if Gem::Requirement.new(gem_version).exact?
gem_version = "> 0"
@logger.debug("Detected exact version match for `#{name}` plugin update. Reset to loose constraint #{gem_version.inspect}.")
end
skips << name
end
source_list[name] ||= []
if plugin_source = info.delete("local_source")
installer_set.add_local(plugin_source.spec.name, plugin_source.spec, plugin_source)
source_list[name] << plugin_source.path
end
Array(info["sources"]).each do |source|
if !source.end_with?("/")
source = source + "/"
end
source_list[name] << source
end
Gem::Dependency.new(name, gem_version)
end
if Vagrant.strict_dependency_enforcement
@logger.debug("Enabling strict dependency enforcement")
plugin_deps += vagrant_internal_specs.map do |spec|
next if system_plugins.include?(spec.name)
Gem::Dependency.new(spec.name, spec.version)
end.compact
else
@logger.debug("Disabling strict dependency enforcement")
end
@logger.debug("Dependency list for installation:\n - " \
"#{plugin_deps.map{|d| "#{d.name} #{d.requirement}"}.join("\n - ")}")
all_sources = source_list.values.flatten.uniq
default_sources = DEFAULT_GEM_SOURCES & all_sources
all_sources -= DEFAULT_GEM_SOURCES
# Only allow defined Gem sources
Gem.sources.clear
@logger.debug("Enabling user defined remote RubyGems sources")
all_sources.each do |src|
begin
next if File.file?(src) || URI.parse(src).scheme.nil?
rescue URI::InvalidURIError
next
end
@logger.debug("Adding RubyGems source #{src}")
Gem.sources << src
end
@logger.debug("Enabling default remote RubyGems sources")
default_sources.each do |src|
@logger.debug("Adding source - #{src}")
Gem.sources << src
end
validate_configured_sources!
source_list.values.each{|srcs| srcs.delete_if{|src| default_sources.include?(src)}}
installer_set.prefer_sources = source_list
@logger.debug("Current source list for install: #{Gem.sources.to_a}")
# Create the request set for the new plugins
request_set = Gem::RequestSet.new(*plugin_deps)
installer_set = Gem::Resolver.compose_sets(
installer_set,
generate_builtin_set(system_plugins),
generate_plugin_set(skips)
)
@logger.debug("Generating solution set for installation.")
# Generate the required solution set for new plugins
solution = request_set.resolve(installer_set)
activate_solution(solution)
# Remove gems which are already installed
request_set.sorted_requests.delete_if do |activation_req|
rs_spec = activation_req.spec
if vagrant_internal_specs.detect{|ispec| ispec.name == rs_spec.name && ispec.version == rs_spec.version }
@logger.debug("Removing activation request from install. Already installed. (#{rs_spec.spec.full_name})")
true
end
end
@logger.debug("Installing required gems.")
# Install all remote gems into plugin path. Set the installer to ignore dependencies
# as we know the dependencies are satisfied and it will attempt to validate a gem's
# dependencies are satisfied by gems in the install directory (which will likely not
# be true)
install_path = extra[:env_local] ? env_plugin_gem_path : plugin_gem_path
result = request_set.install_into(install_path.to_s, true,
ignore_dependencies: true,
prerelease: Vagrant.prerelease?,
wrappers: true
)
result = result.map(&:full_spec)
result.each do |spec|
existing_paths = $LOAD_PATH.find_all{|s| s.include?(spec.full_name) }
if !existing_paths.empty?
@logger.debug("Removing existing LOAD_PATHs for #{spec.full_name} - " +
existing_paths.join(", "))
existing_paths.each{|s| $LOAD_PATH.delete(s) }
end
spec.full_require_paths.each do |r_path|
if !$LOAD_PATH.include?(r_path)
@logger.debug("Adding path to LOAD_PATH - #{r_path}")
$LOAD_PATH.unshift(r_path)
end
end
end
result
end
# Generate the composite resolver set totally all of vagrant (builtin + plugin set)
def generate_vagrant_set
sets = [generate_builtin_set, generate_plugin_set]
if env_plugin_gem_path && env_plugin_gem_path.exist?
sets << generate_plugin_set(env_plugin_gem_path)
end
Gem::Resolver.compose_sets(*sets)
end
# @return [Array<[Gem::Specification, String]>] spec and directory pairs
def vagrant_internal_specs
list = {}
directories = [Gem::Specification.default_specifications_dir]
Gem::Specification.find_all{true}.each do |spec|
list[spec.full_name] = spec
end
if(!defined?(::Bundler))
directories += Gem::Specification.dirs.find_all do |path|
!path.start_with?(Gem.user_dir)
end
end
Gem::Specification.each_spec(directories) do |spec|
if !list[spec.full_name]
list[spec.full_name] = spec
end
end
list.values
end
# Iterates each configured RubyGem source to validate that it is properly
# available. If source is unavailable an exception is raised.
def validate_configured_sources!
Gem.sources.each_source do |src|
begin
src.load_specs(:released)
rescue Gem::Exception => source_error
if ENV["VAGRANT_ALLOW_PLUGIN_SOURCE_ERRORS"]
@logger.warn("Failed to load configured plugin source: #{src}!")
@logger.warn("Error received attempting to load source (#{src}): #{source_error}")
@logger.warn("Ignoring plugin source load failure due user request via env variable")
else
@logger.error("Failed to load configured plugin source `#{src}`: #{source_error}")
raise Vagrant::Errors::PluginSourceError,
source: src.uri.to_s,
error_msg: source_error.message
end
end
end
end
# Generate the builtin resolver set
# Generate the plugin resolver set. Optionally provide specification names (short or
# full) that should be ignored
#
# @param [Pathname] path to plugins
# @param [Array<String>] gems to skip
# @return [PluginSet]
def generate_plugin_set(*args)
plugin_path = args.detect{|i| i.is_a?(Pathname) } || plugin_gem_path
skip = args.detect{|i| i.is_a?(Array) } || []
plugin_set = PluginSet.new
@logger.debug("Generating new plugin set instance. Skip gems - #{skip}")
Dir.glob(plugin_path.join('specifications/*.gemspec').to_s).each do |spec_path|
spec = Gem::Specification.load(spec_path)
desired_spec_path = File.join(spec.gem_dir, "#{spec.name}.gemspec")
# Vendor set requires the spec to be within the gem directory. Some gems will package their
# spec file, and that's not what we want to load.
if !File.exist?(desired_spec_path) || !FileUtils.cmp(spec.spec_file, desired_spec_path)
File.write(desired_spec_path, spec.to_ruby)
end
next if skip.include?(spec.name) || skip.include?(spec.full_name)
plugin_set.add_vendor_gem(spec.name, spec.gem_dir)
end
plugin_set
end
# Activate a given solution
def activate_solution(solution)
retried = false
begin
@logger.debug("Activating solution set: #{solution.map(&:full_name)}")
solution.each do |activation_request|
unless activation_request.full_spec.activated?
@logger.debug("Activating gem #{activation_request.full_spec.full_name}")
activation_request.full_spec.activate
if(defined?(::Bundler))
@logger.debug("Marking gem #{activation_request.full_spec.full_name} loaded within Bundler.")
::Bundler.rubygems.mark_loaded activation_request.full_spec
end
end
end
rescue Gem::LoadError => e
# Depending on the version of Ruby, the ordering of the solution set
# will be either 0..n (molinillo) or n..0 (pre-molinillo). Instead of
# attempting to determine what's in use, or if it has some how changed
# again, just reverse order on failure and attempt again.
if retried
@logger.error("Failed to load solution set - #{e.class}: #{e}")
matcher = e.message.match(/Could not find '(?<gem_name>[^']+)'/)
if matcher && !matcher["gem_name"].empty?
desired_activation_request = solution.detect do |request|
request.name == matcher["gem_name"]
end
if desired_activation_request && !desired_activation_request.full_spec.activated?
activation_request = desired_activation_request
@logger.warn("Found misordered activation request for #{desired_activation_request.full_name}. Moving to solution HEAD.")
solution.delete(desired_activation_request)
solution.unshift(desired_activation_request)
retry
end
end
raise
else
@logger.debug("Failed to load solution set. Retrying with reverse order.")
retried = true
solution.reverse!
retry
end
end
end
# This is a custom Gem::Resolver::InstallerSet. It will prefer sources which are
# explicitly provided over default sources when matches are found. This is generally
# the entire set used for performing full resolutions on install.
class VagrantSet < Gem::Resolver::InstallerSet
attr_accessor :prefer_sources
attr_accessor :system_plugins
def initialize(domain, defined_sources={})
@prefer_sources = defined_sources
@system_plugins = []
super(domain)
end
# Allow InstallerSet to find matching specs, then filter
# for preferred sources
def find_all(req)
result = super
if system_plugins.include?(req.name)
result.delete_if do |spec|
spec.is_a?(Gem::Resolver::InstalledSpecification)
end
end
subset = result.find_all do |idx_spec|
preferred = false
if prefer_sources[req.name]
if idx_spec.source.respond_to?(:path)
preferred = prefer_sources[req.name].include?(idx_spec.source.path.to_s)
end
if !preferred
preferred = prefer_sources[req.name].include?(idx_spec.source.uri.to_s)
end
end
preferred
end
subset.empty? ? result : subset
end
end
# This is a custom Gem::Resolver::Set for use with vagrant "system" gems. It
# allows the installed set of gems to be used for providing a solution while
# enforcing strict constraints. This ensures that plugins cannot "upgrade"
# gems that are builtin to vagrant itself.
class BuiltinSet < Gem::Resolver::Set
def initialize
super
@remote = false
@specs = []
end
def add_builtin_spec(spec)
@specs.push(spec).uniq!
end
def find_all(req)
@specs.select do |spec|
allow_prerelease = spec.name == "vagrant" && Vagrant.prerelease?
req.match?(spec, allow_prerelease)
end.map do |spec|
Gem::Resolver::InstalledSpecification.new(self, spec)
end
end
end
# This is a custom Gem::Resolver::Set for use with Vagrant plugins. It is
# a modified Gem::Resolver::VendorSet that supports multiple versions of
# a specific gem
class PluginSet < Gem::Resolver::VendorSet
##
# Adds a specification to the set with the given +name+ which has been
# unpacked into the given +directory+.
def add_vendor_gem(name, directory)
gemspec = File.join(directory, "#{name}.gemspec")
spec = Gem::Specification.load(gemspec)
if !spec
raise Gem::GemNotFoundException,
"unable to find #{gemspec} for gem #{name}"
end
spec.full_gem_path = File.expand_path(directory)
spec.base_dir = File.dirname(spec.base_dir)
@specs[spec.name] ||= []
@specs[spec.name] << spec
@directories[spec] = directory
spec
end
##
# Returns an Array of VendorSpecification objects matching the
# DependencyRequest +req+.
def find_all(req)
@specs.values.flatten.select do |spec|
req.match?(spec)
end.map do |spec|
source = Gem::Source::Vendor.new(@directories[spec])
Gem::Resolver::VendorSpecification.new(self, spec, source)
end
end
##
# Loads a spec with the given +name+. +version+, +platform+ and +source+ are
# ignored.
def load_spec (name, version, platform, source)
version = Gem::Version.new(version) if !version.is_a?(Gem::Version)
@specs.fetch(name, []).detect{|s| s.name == name && s.version == version}
end
end
end
|
chicks/sugarcrm | lib/sugarcrm/associations/association.rb | SugarCRM.Association.resolve_target | ruby | def resolve_target
# Use the link_field name first
klass = @link_field.singularize.camelize
namespace = @owner.class.session.namespace_const
return namespace.const_get(klass) if namespace.const_defined? klass
# Use the link_field attribute "module"
if @attributes["module"].length > 0
module_name = SugarCRM::Module.find(@attributes["module"], @owner.class.session)
return namespace.const_get(module_name.klass) if module_name && namespace.const_defined?(module_name.klass)
end
# Use the "relationship" target
if @attributes["relationship"].length > 0
klass = @relationship[:target][:name].singularize.camelize
return namespace.const_get(klass) if namespace.const_defined? klass
end
false
end | Attempts to determine the class of the target in the association | train | https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/associations/association.rb#L67-L83 | class Association
attr_accessor :owner, :target, :link_field, :relationship, :attributes, :proxy_methods, :cardinality
# Creates a new instance of an Association
def initialize(owner,link_field,opts={})
@options = { :define_methods? => true }.merge! opts
@owner = owner
check_valid_owner
@link_field = link_field
@attributes = owner.link_fields[link_field]
@relationship = relationship_for(@attributes["relationship"])
@target = resolve_target
@proxy_methods = define_methods if @options[:define_methods?]
@cardinality = resolve_cardinality
self
end
# Returns true if the association includes an attribute that matches
# the provided string
def include?(attribute)
return true if attribute.class == @target
return true if attribute == link_field
return true if methods.include? attribute
false
end
def ==(comparison_object)
comparison_object.instance_of?(self.class) &&
@target.class == comparison_object.class &&
@link_field == comparison_object.link_field
end
alias :eql? :==
def hash
"#{@target.class}##{@link_field}".hash
end
def inspect
self
end
def to_s
"#<#{@owner.class.session.namespace_const}::Association @proxy_methods=[#{@proxy_methods.join(", ")}], " +
"@link_field=\"#{@link_field}\", @target=#{@target}, @owner=#{@owner.class}, " +
"@cardinality=:#{@cardinality}>"
end
def pretty_print(pp)
pp.text self.inspect, 0
end
protected
def check_valid_owner
valid = @owner.class.ancestors.include? SugarCRM::Base
raise InvalidModule, "#{@owner} is not registered, or is not a descendant of SugarCRM::Base" unless valid
end
# Attempts to determine the class of the target in the association
# Defines methods for accessing the association target on the owner class.
# If the link_field name includes the owner class name, it is stripped before
# creating the method. If this occurs, we also create an alias to the stripped
# method using the full link_field name.
def define_methods
methods = []
pretty_name = @relationship[:target][:name]
methods << define_method(@link_field)
methods << define_alias(pretty_name, @link_field) if pretty_name != @link_field
methods
end
# Generates the association proxy method for related module
def define_method(link_field)
raise ArgumentError, "argument cannot be nil" if link_field.nil?
if (@owner.respond_to? link_field.to_sym) && @owner.debug
warn "Warning: Overriding method: #{@owner.class}##{link_field}"
end
@owner.class.module_eval %Q?
def #{link_field}
query_association :#{link_field}
end
?
link_field
end
# Defines a method alias. Checks to see if a method is already defined.
def define_alias(alias_name, method_name)
@owner.class.module_eval %Q?
alias :#{alias_name} :#{method_name}
?
alias_name
end
# This method breaks the relationship into parts and returns them
def relationship_for(relationship)
# We need to run both regexes, because the plurality of the @owner module name is
# important
plural_regex = /((.*)_)?(#{Regexp.quote(@owner.class._module.name.downcase)})(_(.*))?/
singular_regex = /((.*)_)?(#{Regexp.quote(@owner.class._module.name.downcase.singularize)})(_(.*))?/
# Break the loop if we match
[plural_regex, singular_regex].each {|r| break if relationship.match(r)}
# Assign sane values to things if we didnt match
o = $3
o = @owner.class._module.name.downcase if o.nil? || o.empty?
t = [$2, $5].compact.join('_')
t = @link_field if t.nil? || t.empty?
# Look up the cardinality
o_c, t_c = cardinality_for(o,t)
{:owner => {:name => o, :cardinality => o_c},
:target => {:name => t, :cardinality => t_c}}
end
# Determines if the provided string is plural or singular
# Plurality == Cardinality
def cardinality_for(*args)
args.inject([]) {|results,arg|
result = :many
result = :one if arg.singularize == arg
results << result
}
end
def resolve_cardinality
"#{@relationship[:owner][:cardinality]}_to_#{@relationship[:target][:cardinality]}".to_sym
end
end
|
charypar/cyclical | lib/cyclical/occurrence.rb | Cyclical.Occurrence.list_occurrences | ruby | def list_occurrences(from, direction = :forward, &block)
raise ArgumentError, "From #{from} not matching the rule #{@rule} and start time #{@start_time}" unless @rule.match?(from, @start_time)
results = []
n, current = init_loop(from, direction)
loop do
# Rails.logger.debug("Listing occurrences of #{@rule}, going #{direction.to_s}, current: #{current}")
# break on schedule span limits
return results unless (current >= @start_time) && (@rule.stop.nil? || current < @rule.stop) && (@rule.count.nil? || (n -= 1) >= 0)
# break on block condition
return results unless yield current
results << current
# step
if direction == :forward
current = @rule.next(current, @start_time)
else
current = @rule.previous(current, @start_time)
end
end
end | yields valid occurrences, return false from the block to stop | train | https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/occurrence.rb#L70-L93 | class Occurrence
attr_reader :rule, :start_time
attr_accessor :duration
def initialize(rule, start_time)
@rule = rule
@start_time = @rule.match?(start_time, start_time) ? start_time : @rule.next(start_time, start_time)
end
def next_occurrence(after)
next_occurrences(1, after).first
end
def next_occurrences(n, after)
return [] if @rule.stop && after > @rule.stop
time = (after <= @start_time ? @start_time : after)
time = @rule.next(time, @start_time) unless @rule.match?(time, @start_time)
list_occurrences(time) { (n -= 1) >= 0 }
end
def previous_occurrence(before)
previous_occurrences(1, before).first
end
def previous_occurrences(n, before)
return [] if before <= @start_time
time = (@rule.stop.nil? || before < @rule.stop ? before : @rule.stop)
time = @rule.previous(time, @start_time) # go back even if before matches the rule (half-open time intervals, remember?)
list_occurrences(time, :back) { (n -= 1) >= 0 }.reverse
end
def occurrences_between(t1, t2)
raise ArgumentError, "Empty time interval" unless t2 > t1
return [] if t2 <= @start_time || @rule.stop && t1 >= @rule.stop
time = (t1 <= @start_time ? @start_time : t1)
time = @rule.next(time, @start_time) unless @rule.match?(time, @start_time)
list_occurrences(time) { |t| t < t2 }
end
def suboccurrences_between(t1, t2)
occurrences = occurrences_between(t1 - duration, t2)
occurrences.map { |occ| Suboccurrence.find(:occurrence => (occ)..(occ + duration), :interval => t1..t2) }
end
def all
if @rule.stop
list_occurrences(@start_time) { |t| t < @rule.stop }
else
n = @rule.count
list_occurrences(@start_time) { (n -= 1) >= 0 }
end
end
def to_hash
@rule.to_hash
end
private
# yields valid occurrences, return false from the block to stop
def init_loop(from, direction)
return 0, from unless @rule.count # without count limit, life is easy
# with it, it's... well...
if direction == :forward
n = 0
current = @start_time
while current < from
n += 1
current = @rule.next(current, @start_time)
end
# return the n remaining events
return (@rule.count - n), current
else
n = 0
current = @start_time
while current < from && (n += 1) < @rule.count
current = @rule.next(current, @start_time)
end
# return all events (downloop - yaay, I invented a word - will stop on start time)
return @rule.count, current
end
end
end
|
wvanbergen/request-log-analyzer | lib/request_log_analyzer/file_format.rb | RequestLogAnalyzer::FileFormat.CommonRegularExpressions.timestamp | ruby | def timestamp(format_string, blank = false)
regexp = ''
format_string.scan(/([^%]*)(?:%([A-Za-z%]))?/) do |literal, variable|
regexp << Regexp.quote(literal)
if variable
if TIMESTAMP_PARTS.key?(variable)
regexp << TIMESTAMP_PARTS[variable]
else
fail "Unknown variable: %#{variable}"
end
end
end
add_blank_option(Regexp.new(regexp), blank)
end | Create a regular expression for a timestamp, generated by a strftime call.
Provide the format string to construct a matching regular expression.
Set blank to true to allow and empty string, or set blank to a string to set
a substitute for the nil value. | train | https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/file_format.rb#L143-L157 | module CommonRegularExpressions
TIMESTAMP_PARTS = {
'a' => '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)',
'b' => '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)',
'y' => '\d{2}', 'Y' => '\d{4}', 'm' => '\d{2}', 'd' => '\d{2}',
'H' => '\d{2}', 'M' => '\d{2}', 'S' => '\d{2}', 'k' => '(?:\d| )\d',
'z' => '(?:[+-]\d{4}|[A-Z]{3,4})',
'Z' => '(?:[+-]\d{4}|[A-Z]{3,4})',
'%' => '%'
}
# Creates a regular expression to match a hostname
def hostname(blank = false)
regexp = /(?:(?:[a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*(?:[A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])/
add_blank_option(regexp, blank)
end
# Creates a regular expression to match a hostname or ip address
def hostname_or_ip_address(blank = false)
regexp = Regexp.union(hostname, ip_address)
add_blank_option(regexp, blank)
end
# Create a regular expression for a timestamp, generated by a strftime call.
# Provide the format string to construct a matching regular expression.
# Set blank to true to allow and empty string, or set blank to a string to set
# a substitute for the nil value.
# Construct a regular expression to parse IPv4 and IPv6 addresses.
#
# Allow nil values if the blank option is given. This can be true to
# allow an empty string or to a string substitute for the nil value.
def ip_address(blank = false)
# IP address regexp copied from Resolv::IPv4 and Resolv::IPv6,
# but adjusted to work for the purpose of request-log-analyzer.
ipv4_regexp = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/
ipv6_regex_8_hex = /(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}/
ipv6_regex_compressed_hex = /(?:(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::(?:(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)/
ipv6_regex_6_hex_4_dec = /(?:(?:[0-9A-Fa-f]{1,4}:){6})#{ipv4_regexp}/
ipv6_regex_compressed_hex_4_dec = /(?:(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::(?:(?:[0-9A-Fa-f]{1,4}:)*)#{ipv4_regexp}/
ipv6_regexp = Regexp.union(ipv6_regex_8_hex, ipv6_regex_compressed_hex, ipv6_regex_6_hex_4_dec, ipv6_regex_compressed_hex_4_dec)
add_blank_option(Regexp.union(ipv4_regexp, ipv6_regexp), blank)
end
def anchored(regexp)
/^#{regexp}$/
end
protected
# Allow the field to be blank if this option is given. This can be true to
# allow an empty string or a string alternative for the nil value.
def add_blank_option(regexp, blank)
case blank
when String then Regexp.union(regexp, Regexp.new(Regexp.quote(blank)))
when true then Regexp.union(regexp, //)
else regexp
end
end
end
|
weshatheleopard/rubyXL | lib/rubyXL/convenience_methods/cell.rb | RubyXL.CellConvenienceMethods.change_font_size | ruby | def change_font_size(font_size = 10)
validate_worksheet
raise 'Argument must be a number' unless font_size.is_a?(Integer) || font_size.is_a?(Float)
font = get_cell_font.dup
font.set_size(font_size)
update_font_references(font)
end | Changes font size of cell | train | https://github.com/weshatheleopard/rubyXL/blob/e61d78de9486316cdee039d3590177dc05db0f0c/lib/rubyXL/convenience_methods/cell.rb#L167-L174 | module CellConvenienceMethods
def change_contents(data, formula_expression = nil)
validate_worksheet
if formula_expression then
self.datatype = nil
self.formula = RubyXL::Formula.new(:expression => formula_expression)
else
self.datatype = case data
when Date, Numeric then nil
else RubyXL::DataType::RAW_STRING
end
end
data = workbook.date_to_num(data) if data.is_a?(Date)
self.raw_value = data
end
def get_border(direction)
validate_worksheet
get_cell_border.get_edge_style(direction)
end
def get_border_color(direction)
validate_worksheet
get_cell_border.get_edge_color(direction)
end
def change_horizontal_alignment(alignment = 'center')
validate_worksheet
self.style_index = workbook.modify_alignment(self.style_index) { |a| a.horizontal = alignment }
end
def change_vertical_alignment(alignment = 'center')
validate_worksheet
self.style_index = workbook.modify_alignment(self.style_index) { |a| a.vertical = alignment }
end
def change_text_wrap(wrap = false)
validate_worksheet
self.style_index = workbook.modify_alignment(self.style_index) { |a| a.wrap_text = wrap }
end
def change_text_rotation(rot)
validate_worksheet
self.style_index = workbook.modify_alignment(self.style_index) { |a| a.text_rotation = rot }
end
def change_text_indent(indent)
validate_worksheet
self.style_index = workbook.modify_alignment(self.style_index) { |a| a.indent = indent }
end
def change_border(direction, weight)
validate_worksheet
self.style_index = workbook.modify_border(self.style_index, direction, weight)
end
def change_border_color(direction, color)
validate_worksheet
Color.validate_color(color)
self.style_index = workbook.modify_border_color(self.style_index, direction, color)
end
def is_italicized()
validate_worksheet
get_cell_font.is_italic
end
def is_bolded()
validate_worksheet
get_cell_font.is_bold
end
def is_underlined()
validate_worksheet
get_cell_font.is_underlined
end
def is_struckthrough()
validate_worksheet
get_cell_font.is_strikethrough
end
def font_name()
validate_worksheet
get_cell_font.get_name
end
def font_size()
validate_worksheet
get_cell_font.get_size
end
def font_color()
validate_worksheet
get_cell_font.get_rgb_color || '000000'
end
def fill_color()
validate_worksheet
return workbook.get_fill_color(get_cell_xf)
end
def horizontal_alignment()
validate_worksheet
xf_obj = get_cell_xf
return nil if xf_obj.alignment.nil?
xf_obj.alignment.horizontal
end
def vertical_alignment()
validate_worksheet
xf_obj = get_cell_xf
return nil if xf_obj.alignment.nil?
xf_obj.alignment.vertical
end
def text_wrap()
validate_worksheet
xf_obj = get_cell_xf
return nil if xf_obj.alignment.nil?
xf_obj.alignment.wrap_text
end
def text_rotation
validate_worksheet
xf_obj = get_cell_xf
return nil if xf_obj.alignment.nil?
xf_obj.alignment.text_rotation
end
def text_indent()
validate_worksheet
xf_obj = get_cell_xf
return nil if xf_obj.alignment.nil?
xf_obj.alignment.indent
end
def set_number_format(format_code)
new_xf = get_cell_xf.dup
new_xf.num_fmt_id = workbook.stylesheet.register_number_format(format_code)
new_xf.apply_number_format = true
self.style_index = workbook.register_new_xf(new_xf)
end
# Changes fill color of cell
def change_fill(rgb = 'ffffff')
validate_worksheet
Color.validate_color(rgb)
self.style_index = workbook.modify_fill(self.style_index, rgb)
end
# Changes font name of cell
def change_font_name(new_font_name = 'Verdana')
validate_worksheet
font = get_cell_font.dup
font.set_name(new_font_name)
update_font_references(font)
end
# Changes font size of cell
# Changes font color of cell
def change_font_color(font_color = '000000')
validate_worksheet
Color.validate_color(font_color)
font = get_cell_font.dup
font.set_rgb_color(font_color)
update_font_references(font)
end
# Changes font italics settings of cell
def change_font_italics(italicized = false)
validate_worksheet
font = get_cell_font.dup
font.set_italic(italicized)
update_font_references(font)
end
# Changes font bold settings of cell
def change_font_bold(bolded = false)
validate_worksheet
font = get_cell_font.dup
font.set_bold(bolded)
update_font_references(font)
end
# Changes font underline settings of cell
def change_font_underline(underlined = false)
validate_worksheet
font = get_cell_font.dup
font.set_underline(underlined)
update_font_references(font)
end
def change_font_strikethrough(struckthrough = false)
validate_worksheet
font = get_cell_font.dup
font.set_strikethrough(struckthrough)
update_font_references(font)
end
# Helper method to update the font array and xf array
def update_font_references(modified_font)
xf = workbook.register_new_font(modified_font, get_cell_xf)
self.style_index = workbook.register_new_xf(xf)
end
private :update_font_references
# Performs correct modification based on what type of change_type is specified
def font_switch(change_type, arg)
case change_type
when Worksheet::NAME then change_font_name(arg)
when Worksheet::SIZE then change_font_size(arg)
when Worksheet::COLOR then change_font_color(arg)
when Worksheet::ITALICS then change_font_italics(arg)
when Worksheet::BOLD then change_font_bold(arg)
when Worksheet::UNDERLINE then change_font_underline(arg)
when Worksheet::STRIKETHROUGH then change_font_strikethrough(arg)
else raise 'Invalid change_type'
end
end
=begin
def add_hyperlink(l)
worksheet.hyperlinks ||= RubyXL::Hyperlinks.new
worksheet.hyperlinks << RubyXL::Hyperlink.new(:ref => self.r, :location => l)
# define_attribute(:'r:id', :string)
# define_attribute(:location, :string)
# define_attribute(:tooltip, :string)
# define_attribute(:display, :string)
end
def add_shared_string(str)
self.datatype = RubyXL::DataType::SHARED_STRING
self.raw_value = @workbook.shared_strings_container.add(str)
end
=end
end
|
projectcypress/health-data-standards | lib/hqmf-parser/2.0/types.rb | HQMF2.Value.to_model | ruby | def to_model
HQMF::Value.new(type, unit, value, inclusive?, derived?, expression)
end | Generates this classes hqmf-model equivalent | train | https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/types.rb#L106-L108 | class Value
include HQMF2::Utilities
attr_reader :type, :unit, :value
def initialize(entry, default_type = 'PQ', force_inclusive = false, _parent = nil)
@entry = entry
@type = attr_val('./@xsi:type') || default_type
@unit = attr_val('./@unit')
@value = attr_val('./@value')
@force_inclusive = force_inclusive
# FIXME: Remove below when lengthOfStayQuantity unit is fixed
@unit = 'd' if @unit == 'days'
end
def inclusive?
# If the high and low value are at any time the same, then it must be an inclusive value.
equivalent = attr_val('../cda:low/@value') == attr_val('../cda:high/@value')
# If and inclusivity value is set for any specific value, then mark the value as inclusive.
# IDEA: This could be limited in future iterations by including the parent type (temporal reference, subset code,
# etc.)
inclusive_temporal_ref? || inclusive_length_of_stay? || inclusive_basic_values? || inclusive_subsets? ||
equivalent || @force_inclusive
end
# Check whether the temporal reference should be marked as inclusive
def inclusive_temporal_ref?
# FIXME: NINF is used instead of 0 sometimes...? (not in the IG)
# FIXME: Given nullFlavor, but IG uses it and nullValue everywhere...
less_than_equal_tr = attr_val('../@highClosed') == 'true' &&
(attr_val('../cda:low/@value') == '0' || attr_val('../cda:low/@nullFlavor') == 'NINF')
greater_than_equal_tr = attr_val('../cda:high/@nullFlavor') == 'PINF' &&
attr_val('../cda:low/@value')
# Both less and greater require lowClosed to be set to true
(less_than_equal_tr || greater_than_equal_tr) && attr_val('../@lowClosed') == 'true'
end
# Check whether the length of stay should be inclusive.
def inclusive_length_of_stay?
# lengthOfStay - EH111, EH108
less_than_equal_los = attr_val('../cda:low/@nullFlavor') == 'NINF' &&
attr_val('../@highClosed') != 'false'
greater_than_equal_los = attr_val('../cda:high/@nullFlavor') == 'PINF' &&
attr_val('../@lowClosed') != 'false'
# Both less and greater require that the type is PQ
(less_than_equal_los || greater_than_equal_los) && attr_val('@xsi:type') == 'PQ'
end
# Check is the basic values should be marked as inclusive, currently only checks for greater than case
def inclusive_basic_values?
# Basic values - EP65, EP9, and more
attr_val('../cda:high/@nullFlavor') == 'PINF' &&
attr_val('../cda:low/@value') &&
attr_val('../@lowClosed') != 'false' &&
attr_val('../@xsi:type') == 'IVL_PQ'
end
# Check if subset values should be marked as inclusive. Currently only handles greater than
def inclusive_subsets?
# subset - EP128, EH108
attr_val('../cda:low/@value') != '0' &&
!attr_val('../cda:high/@value') &&
attr_val('../@lowClosed') != 'false' &&
!attr_val('../../../../../qdm:subsetCode/@code').nil?
end
def derived?
case attr_val('./@nullFlavor')
when 'DER'
true
else
false
end
end
def expression
if !derived?
nil
else
attr_val('./cda:expression/@value')
end
end
# Generates this classes hqmf-model equivalent
end
|
Falkor/falkorlib | lib/falkorlib/common.rb | FalkorLib.Common.normalized_path | ruby | def normalized_path(dir = Dir.pwd, options = {})
rootdir = (FalkorLib::Git.init?(dir)) ? FalkorLib::Git.rootdir(dir) : dir
path = dir
path = Dir.pwd if dir == '.'
path = File.join(Dir.pwd, dir) unless (dir =~ /^\// || (dir == '.'))
if (options[:relative] || options[:relative_to])
root = (options[:relative_to]) ? options[:relative_to] : rootdir
relative_path_to_root = Pathname.new( File.realpath(path) ).relative_path_from Pathname.new(root)
path = relative_path_to_root.to_s
end
path
end | normalize_path
Normalize a path and return the absolute path foreseen
Ex: '.' return Dir.pwd
Supported options:
* :relative [boolean] return relative path to the root dir | train | https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/common.rb#L479-L490 | module Common
module_function
##################################
### Default printing functions ###
##################################
# Print a text in bold
def bold(str)
(COLOR == true) ? Term::ANSIColor.bold(str) : str
end
# Print a text in green
def green(str)
(COLOR == true) ? Term::ANSIColor.green(str) : str
end
# Print a text in red
def red(str)
(COLOR == true) ? Term::ANSIColor.red(str) : str
end
# Print a text in cyan
def cyan(str)
(COLOR == true) ? Term::ANSIColor.cyan(str) : str
end
# Print an info message
def info(str)
puts green("[INFO] " + str)
end
# Print an warning message
def warning(str)
puts cyan("/!\\ WARNING: " + str)
end
alias_method :warn, :warning
## Print an error message and abort
def error(str)
#abort red("*** ERROR *** " + str)
$stderr.puts red("*** ERROR *** " + str)
exit 1
end
## simple helper text to mention a non-implemented feature
def not_implemented
error("NOT YET IMPLEMENTED")
end
##############################
### Interaction functions ###
##############################
## Ask a question
def ask(question, default_answer = '')
return default_answer if FalkorLib.config[:no_interaction]
print "#{question} "
print "[Default: #{default_answer}]" unless default_answer == ''
print ": "
STDOUT.flush
answer = STDIN.gets.chomp
(answer.empty?) ? default_answer : answer
end
## Ask whether or not to really continue
def really_continue?(default_answer = 'Yes')
return if FalkorLib.config[:no_interaction]
pattern = (default_answer =~ /yes/i) ? '(Y|n)' : '(y|N)'
answer = ask( cyan("=> Do you really want to continue #{pattern}?"), default_answer)
exit 0 if answer =~ /n.*/i
end
############################
### Execution functions ###
############################
## Check for the presence of a given command
def command?(name)
`which #{name}`
$?.success?
end
## Execute a given command, return exit code and print nicely stdout and stderr
def nice_execute(cmd)
puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}")
stdout, stderr, exit_status = Open3.capture3( cmd )
unless stdout.empty?
stdout.each_line do |line|
print "** [out] #{line}"
$stdout.flush
end
end
unless stderr.empty?
stderr.each_line do |line|
$stderr.print red("** [err] #{line}")
$stderr.flush
end
end
exit_status
end
# Simpler version that use the system call
def execute(cmd)
puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}")
system(cmd)
$?.exitstatus
end
## Execute in a given directory
def execute_in_dir(path, cmd)
exit_status = 0
Dir.chdir(path) do
exit_status = run %( #{cmd} )
end
exit_status
end # execute_in_dir
## Execute a given command - exit if status != 0
def exec_or_exit(cmd)
status = execute(cmd)
if (status.to_i.nonzero?)
error("The command '#{cmd}' failed with exit status #{status.to_i}")
end
status
end
## "Nice" way to present run commands
## Ex: run %{ hostname -f }
def run(cmds)
exit_status = 0
puts bold("[Running]\n#{cmds.gsub(/^\s*/, ' ')}")
$stdout.flush
#puts cmds.split(/\n */).inspect
cmds.split(/\n */).each do |cmd|
next if cmd.empty?
system(cmd.to_s) unless FalkorLib.config.debug
exit_status = $?.exitstatus
end
exit_status
end
## List items from a glob pattern to ask for a unique choice
# Supported options:
# :only_files [boolean]: list only files in the glob
# :only_dirs [boolean]: list only directories in the glob
# :pattern_include [array of strings]: pattern(s) to include for listing
# :pattern_exclude [array of strings]: pattern(s) to exclude for listing
# :text [string]: text to put
def list_items(glob_pattern, options = {})
list = { 0 => 'Exit' }
index = 1
raw_list = { 0 => 'Exit' }
Dir[glob_pattern.to_s].each do |elem|
#puts "=> element '#{elem}' - dir = #{File.directory?(elem)}; file = #{File.file?(elem)}"
next if (!options[:only_files].nil?) && options[:only_files] && File.directory?(elem)
next if (!options[:only_dirs].nil?) && options[:only_dirs] && File.file?(elem)
entry = File.basename(elem)
# unless options[:pattern_include].nil?
# select_entry = false
# options[:pattern_include].each do |pattern|
# #puts "considering pattern '#{pattern}' on entry '#{entry}'"
# select_entry |= entry =~ /#{pattern}/
# end
# next unless select_entry
# end
unless options[:pattern_exclude].nil?
select_entry = false
options[:pattern_exclude].each do |pattern|
#puts "considering pattern '#{pattern}' on entry '#{entry}'"
select_entry |= entry =~ /#{pattern}/
end
next if select_entry
end
#puts "selected entry = '#{entry}'"
list[index] = entry
raw_list[index] = elem
index += 1
end
text = (options[:text].nil?) ? "select the index" : options[:text]
default_idx = (options[:default].nil?) ? 0 : options[:default]
raise SystemExit, 'Empty list' if index == 1
#ap list
#ap raw_list
# puts list.to_yaml
# answer = ask("=> #{text}", "#{default_idx}")
# raise SystemExit.new('exiting selection') if answer == '0'
# raise RangeError.new('Undefined index') if Integer(answer) >= list.length
# raw_list[Integer(answer)]
select_from(list, text, default_idx, raw_list)
end
## Display a indexed list to select an i
def select_from(list, text = 'Select the index', default_idx = 0, raw_list = list)
error "list and raw_list differs in size" if list.size != raw_list.size
l = list
raw_l = raw_list
if list.is_a?(Array)
l = raw_l = { 0 => 'Exit' }
list.each_with_index do |e, idx|
l[idx + 1] = e
raw_l[idx + 1] = raw_list[idx]
end
end
puts l.to_yaml
answer = ask("=> #{text}", default_idx.to_s)
raise SystemExit, 'exiting selection' if answer == '0'
raise RangeError, 'Undefined index' if Integer(answer) >= l.length
raw_l[Integer(answer)]
end # select_from
## Display a indexed list to select multiple indexes
def select_multiple_from(list, text = 'Select the index', default_idx = 1, raw_list = list)
error "list and raw_list differs in size" if list.size != raw_list.size
l = list
raw_l = raw_list
if list.is_a?(Array)
l = raw_l = { 0 => 'Exit', 1 => 'End of selection' }
list.each_with_index do |e, idx|
l[idx + 2] = e
raw_l[idx + 2] = raw_list[idx]
end
end
puts l.to_yaml
choices = Array.new
answer = 0
begin
choices.push(raw_l[Integer(answer)]) if Integer(answer) > 1
answer = ask("=> #{text}", default_idx.to_s)
raise SystemExit, 'exiting selection' if answer == '0'
raise RangeError, 'Undefined index' if Integer(answer) >= l.length
end while Integer(answer) != 1
choices
end # select_multiple_from
###############################
### YAML File loading/store ###
###############################
# Return the yaml content as a Hash object
def load_config(file)
unless File.exist?(file)
raise FalkorLib::Error, "Unable to find the YAML file '#{file}'"
end
loaded = YAML.load_file(file)
unless loaded.is_a?(Hash)
raise FalkorLib::Error, "Corrupted or invalid YAML file '#{file}'"
end
loaded
end
# Store the Hash object as a Yaml file
# Supported options:
# :header [string]: additional info to place in the header of the (stored) file
# :no_interaction [boolean]: do not interact
def store_config(filepath, hash, options = {})
content = "# " + File.basename(filepath) + "\n"
content += "# /!\\ DO NOT EDIT THIS FILE: it has been automatically generated\n"
if options[:header]
options[:header].split("\n").each { |line| content += "# #{line}" }
end
content += hash.to_yaml
show_diff_and_write(content, filepath, options)
# File.open( filepath, 'w') do |f|
# f.print "# ", File.basename(filepath), "\n"
# f.puts "# /!\\ DO NOT EDIT THIS FILE: it has been automatically generated"
# if options[:header]
# options[:header].split("\n").each do |line|
# f.puts "# #{line}"
# end
# end
# f.puts hash.to_yaml
# end
end
#################################
### [ERB] template generation ###
#################################
# Bootstrap the destination directory `rootdir` using the template
# directory `templatedir`. the hash table `config` hosts the elements to
# feed ERB files which **should** have the extension .erb.
# The initialization is performed as follows:
# * a rsync process is initiated to duplicate the directory structure
# and the symlinks, and exclude .erb files
# * each erb files (thus with extension .erb) is interpreted, the
# corresponding file is generated without the .erb extension
# Supported options:
# :erb_exclude [array of strings]: pattern(s) to exclude from erb file
# interpretation and thus to copy 'as is'
# :no_interaction [boolean]: do not interact
def init_from_template(templatedir, rootdir, config = {},
options = {
:erb_exclude => [],
:no_interaction => false
})
error "Unable to find the template directory" unless File.directory?(templatedir)
warning "about to initialize/update the directory #{rootdir}"
really_continue? unless options[:no_interaction]
run %( mkdir -p #{rootdir} ) unless File.directory?( rootdir )
run %( rsync --exclude '*.erb' --exclude '.texinfo*' -avzu #{templatedir}/ #{rootdir}/ )
Dir["#{templatedir}/**/*.erb"].each do |erbfile|
relative_outdir = Pathname.new( File.realpath( File.dirname(erbfile) )).relative_path_from Pathname.new(templatedir)
filename = File.basename(erbfile, '.erb')
outdir = File.realpath( File.join(rootdir, relative_outdir.to_s) )
outfile = File.join(outdir, filename)
unless options[:erb_exclude].nil?
exclude_entry = false
options[:erb_exclude].each do |pattern|
exclude_entry |= erbfile =~ /#{pattern}/
end
if exclude_entry
info "copying non-interpreted ERB file"
# copy this file since it has been probably excluded from teh rsync process
run %( cp #{erbfile} #{outdir}/ )
next
end
end
# Let's go
info "updating '#{relative_outdir}/#{filename}'"
puts " using ERB template '#{erbfile}'"
write_from_erb_template(erbfile, outfile, config, options)
end
end
###
# ERB generation of the file `outfile` using the source template file `erbfile`
# Supported options:
# :no_interaction [boolean]: do not interact
# :srcdir [string]: source dir for all considered ERB files
def write_from_erb_template(erbfile, outfile, config = {},
options = {
:no_interaction => false
})
erbfiles = (erbfile.is_a?(Array)) ? erbfile : [ erbfile ]
content = ""
erbfiles.each do |f|
erb = (options[:srcdir].nil?) ? f : File.join(options[:srcdir], f)
unless File.exist?(erb)
warning "Unable to find the template ERBfile '#{erb}'"
really_continue? unless options[:no_interaction]
next
end
content += ERB.new(File.read(erb.to_s), nil, '<>').result(binding)
end
# error "Unable to find the template file #{erbfile}" unless File.exists? (erbfile )
# template = File.read("#{erbfile}")
# output = ERB.new(template, nil, '<>')
# content = output.result(binding)
show_diff_and_write(content, outfile, options)
end
## Show the difference between a `content` string and an destination file (using Diff algorithm).
# Obviosuly, if the outfile does not exists, no difference is proposed.
# Supported options:
# :no_interaction [boolean]: do not interact
# :json_pretty_format [boolean]: write a json content, in pretty format
# :no_commit [boolean]: do not (offer to) commit the changes
# return 0 if nothing happened, 1 if a write has been done
def show_diff_and_write(content, outfile, options = {
:no_interaction => false,
:json_pretty_format => false,
:no_commit => false
})
if File.exist?( outfile )
ref = File.read( outfile )
if options[:json_pretty_format]
ref = JSON.pretty_generate(JSON.parse( IO.read( outfile ) ))
end
if ref == content
warn "Nothing to update"
return 0
end
warn "the file '#{outfile}' already exists and will be overwritten."
warn "Expected difference: \n------"
Diffy::Diff.default_format = :color
puts Diffy::Diff.new(ref, content, :context => 1)
else
watch = (options[:no_interaction]) ? 'no' : ask( cyan(" ==> Do you want to see the generated file before commiting the writing (y|N)"), 'No')
puts content if watch =~ /y.*/i
end
proceed = (options[:no_interaction]) ? 'yes' : ask( cyan(" ==> proceed with the writing (Y|n)"), 'Yes')
return 0 if proceed =~ /n.*/i
info("=> writing #{outfile}")
File.open(outfile.to_s, "w+") do |f|
f.write content
end
if FalkorLib::Git.init?(File.dirname(outfile)) && !options[:no_commit]
do_commit = (options[:no_interaction]) ? 'yes' : ask( cyan(" ==> commit the changes (Y|n)"), 'Yes')
FalkorLib::Git.add(outfile, "update content of '#{File.basename(outfile)}'") if do_commit =~ /y.*/i
end
1
end
## Blind copy of a source file `src` into its destination directory `dstdir`
# Supported options:
# :no_interaction [boolean]: do not interact
# :srcdir [string]: source directory, make the `src` file relative to that directory
# :outfile [string]: alter the outfile name (File.basename(src) by default)
# :no_commit [boolean]: do not (offer to) commit the changes
def write_from_template(src, dstdir, options = {
:no_interaction => false,
:no_commit => false,
:srcdir => '',
:outfile => ''
})
srcfile = (options[:srcdir].nil?) ? src : File.join(options[:srcdir], src)
error "Unable to find the source file #{srcfile}" unless File.exist?( srcfile )
error "The destination directory '#{dstdir}' do not exist" unless File.directory?( dstdir )
dstfile = (options[:outfile].nil?) ? File.basename(srcfile) : options[:outfile]
outfile = File.join(dstdir, dstfile)
content = File.read( srcfile )
show_diff_and_write(content, outfile, options)
end # copy_from_template
### RVM init
def init_rvm(rootdir = Dir.pwd, gemset = '')
rvm_files = {
:version => File.join(rootdir, '.ruby-version'),
:gemset => File.join(rootdir, '.ruby-gemset')
}
unless File.exist?( (rvm_files[:version]).to_s)
v = select_from(FalkorLib.config[:rvm][:rubies],
"Select RVM ruby to configure for this directory",
3)
File.open( rvm_files[:version], 'w') do |f|
f.puts v
end
end
unless File.exist?( (rvm_files[:gemset]).to_s)
g = (gemset.empty?) ? ask("Enter RVM gemset name for this directory", File.basename(rootdir)) : gemset
File.open( rvm_files[:gemset], 'w') do |f|
f.puts g
end
end
end
###### normalize_path ######
# Normalize a path and return the absolute path foreseen
# Ex: '.' return Dir.pwd
# Supported options:
# * :relative [boolean] return relative path to the root dir
##
# normalize_path
end
|
hashicorp/vault-ruby | lib/vault/api/auth_token.rb | Vault.AuthToken.lookup_accessor | ruby | def lookup_accessor(accessor, options = {})
headers = extract_headers!(options)
json = client.post("/v1/auth/token/lookup-accessor", JSON.fast_generate(
accessor: accessor,
), headers)
return Secret.decode(json)
end | Lookup information about the given token accessor.
@example
Vault.auth_token.lookup_accessor("acbd-...") #=> #<Vault::Secret lease_id="">
@param [String] accessor
@param [Hash] options | train | https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/auth_token.rb#L126-L132 | class AuthToken < Request
# Lists all token accessors.
#
# @example Listing token accessors
# result = Vault.auth_token.accessors #=> #<Vault::Secret>
# result.data[:keys] #=> ["476ea048-ded5-4d07-eeea-938c6b4e43ec", "bb00c093-b7d3-b0e9-69cc-c4d85081165b"]
#
# @return [Array<Secret>]
def accessors(options = {})
headers = extract_headers!(options)
json = client.list("/v1/auth/token/accessors", options, headers)
return Secret.decode(json)
end
# Create an authentication token. Note that the parameters specified below
# are not validated and passed directly to the Vault server. Depending on
# the version of Vault in operation, some of these options may not work, and
# newer options may be available that are not listed here.
#
# @example Creating a token
# Vault.auth_token.create #=> #<Vault::Secret lease_id="">
#
# @example Creating a token assigned to policies with a wrap TTL
# Vault.auth_token.create(
# policies: ["myapp"],
# wrap_ttl: 500,
# )
#
# @param [Hash] options
# @option options [String] :id
# The ID of the client token - this can only be specified for root tokens
# @option options [Array<String>] :policies
# List of policies to apply to the token
# @option options [Fixnum, String] :wrap_ttl
# The number of seconds or a golang-formatted timestamp like "5s" or "10m"
# for the TTL on the wrapped response
# @option options [Hash<String, String>] :meta
# A map of metadata that is passed to audit backends
# @option options [Boolean] :no_parent
# Create a token without a parent - see also {#create_orphan}
# @option options [Boolean] :no_default_policy
# Create a token without the default policy attached
# @option options [Boolean] :renewable
# Set whether this token is renewable or not
# @option options [String] :display_name
# Name of the token
# @option options [Fixnum] :num_uses
# Maximum number of uses for the token
#
# @return [Secret]
def create(options = {})
headers = extract_headers!(options)
json = client.post("/v1/auth/token/create", JSON.fast_generate(options), headers)
return Secret.decode(json)
end
# Create an orphaned authentication token.
#
# @example
# Vault.auth_token.create_orphan #=> #<Vault::Secret lease_id="">
#
# @param (see #create)
# @option (see #create)
#
# @return [Secret]
def create_orphan(options = {})
headers = extract_headers!(options)
json = client.post("/v1/auth/token/create-orphan", JSON.fast_generate(options), headers)
return Secret.decode(json)
end
# Create an orphaned authentication token.
#
# @example
# Vault.auth_token.create_with_role("developer") #=> #<Vault::Secret lease_id="">
#
# @param [Hash] options
#
# @return [Secret]
def create_with_role(name, options = {})
headers = extract_headers!(options)
json = client.post("/v1/auth/token/create/#{encode_path(name)}", JSON.fast_generate(options), headers)
return Secret.decode(json)
end
# Lookup information about the current token.
#
# @example
# Vault.auth_token.lookup("abcd-...") #=> #<Vault::Secret lease_id="">
#
# @param [String] token
# @param [Hash] options
#
# @return [Secret]
def lookup(token, options = {})
headers = extract_headers!(options)
json = client.post("/v1/auth/token/lookup", JSON.fast_generate(
token: token,
), headers)
return Secret.decode(json)
end
# Lookup information about the given token accessor.
#
# @example
# Vault.auth_token.lookup_accessor("acbd-...") #=> #<Vault::Secret lease_id="">
#
# @param [String] accessor
# @param [Hash] options
# Lookup information about the given token.
#
# @example
# Vault.auth_token.lookup_self #=> #<Vault::Secret lease_id="">
#
# @return [Secret]
def lookup_self
json = client.get("/v1/auth/token/lookup-self")
return Secret.decode(json)
end
# Renew the given authentication token.
#
# @example
# Vault.auth_token.renew("abcd-1234") #=> #<Vault::Secret lease_id="">
#
# @param [String] token
# the auth token
# @param [Fixnum] increment
#
# @return [Secret]
def renew(token, increment = 0, options = {})
headers = extract_headers!(options)
json = client.put("/v1/auth/token/renew", JSON.fast_generate(
token: token,
increment: increment,
), headers)
return Secret.decode(json)
end
# Renews a lease associated with the calling token.
#
# @example
# Vault.auth_token.renew_self #=> #<Vault::Secret lease_id="">
#
# @param [Fixnum] increment
#
# @return [Secret]
def renew_self(increment = 0, options = {})
headers = extract_headers!(options)
json = client.put("/v1/auth/token/renew-self", JSON.fast_generate(
increment: increment,
), headers)
return Secret.decode(json)
end
# Revokes the token used to call it.
#
# @example
# Vault.auth_token.revoke_self #=> 204
#
# @return response code.
def revoke_self
client.post("/v1/auth/token/revoke-self")
end
# Revoke exactly the orphans at the id.
#
# @example
# Vault.auth_token.revoke_orphan("abcd-1234") #=> true
#
# @param [String] token
# the token to revoke
#
# @return [true]
def revoke_orphan(token, options = {})
headers = extract_headers!(options)
client.put("/v1/auth/token/revoke-orphan", JSON.fast_generate(
token: token,
), headers)
return true
end
# Revoke exactly the orphans at the id.
#
# @example
# Vault.auth_token.revoke_accessor("abcd-1234") #=> true
#
# @param [String] accessor
# the accessor to revoke
#
# @return [true]
def revoke_accessor(accessor, options = {})
headers = extract_headers!(options)
client.put("/v1/auth/token/revoke-accessor", JSON.fast_generate(
accessor: accessor,
), headers)
return true
end
# Revoke the token and all its children.
#
# @example
# Vault.auth_token.revoke("abcd-1234") #=> true
#
# @param [String] token
# the auth token
#
# @return [true]
def revoke(token, options = {})
headers = extract_headers!(options)
client.put("/v1/auth/token/revoke", JSON.fast_generate(
token: token,
), headers)
return true
end
alias_method :revoke_tree, :revoke
end
|
ikayzo/SDL.rb | lib/sdl4r/tag.rb | SDL4R.Tag.remove_attribute | ruby | def remove_attribute(namespace, key = nil)
namespace, key = to_nns namespace, key
attributes = @attributesByNamespace[namespace]
return attributes.nil? ? nil : attributes.delete(key)
end | remove_attribute(key)
remove_attribute(namespace, key)
Removes the attribute, whose name and namespace are specified.
_key_:: name of the removed atribute
_namespace_:: namespace of the removed attribute (equal to "", default namespace, by default)
Returns the value of the removed attribute or +nil+ if it didn't exist. | train | https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/tag.rb#L615-L619 | class Tag
# the name of this Tag
#
attr_reader :name
# the namespace of this Tag or an empty string when there is no namespace (i.e. default
# namespace).
#
attr_reader :namespace
# Convenient method to check and handle a pair of parameters namespace/name where, in some
# cases, only one is specified (i.e. the name only).
#
# Use at the beginning of a method in order to have correctly defined parameters:
# def foo(namespace, name = nil)
# namespace, name = to_nns namespace, name
# end
#
def to_nns(namespace, name)
if name.nil? and not namespace.nil?
name = namespace
namespace = ""
end
return namespace, name
end
private :to_nns
# Creates an empty tag in the given namespace. If the +namespace+ is nil
# it will be coerced to an empty String.
#
# tag = Tag.new("name")
# tag = Tag.new("namespace", "name")
#
# tag = Tag.new("fruit") do
# add_value 2
# new_child("orange") do
# set_attribute("quantity", 2)
# end
# end
#
# which builds the following SDL structure
#
# fruit 2 {
# orange quantity=2
# }
#
# If you provide a block that takes an argument, you will write the same example, as follows:
#
# tag = Tag.new("fruit") do |t|
# t.add_value 2
# t.new_child("orange") do
# set_attribute("quantity", 2)
# end
# end
#
# In this case, the current context is not the new Tag anymore but the context of your code.
#
# === Raises
# ArgumentError if the name is not a legal SDL identifier
# (see SDL4R#validate_identifier) or the namespace is non-blank
# and is not a legal SDL identifier.
#
def initialize(namespace, name = nil, &block)
namespace, name = to_nns namespace, name
raise ArgumentError, "tag namespace must be a String" unless namespace.is_a? String
raise ArgumentError, "tag name must be a String" unless name.is_a? String
SDL4R.validate_identifier(namespace) unless namespace.empty?
@namespace = namespace
name = name.to_s.strip
raise ArgumentError, "Tag name cannot be nil or empty" if name.empty?
SDL4R.validate_identifier(name)
@name = name
@children = []
@values = []
# a Hash of Hash : {namespace => {name => value}}
# The default namespace is represented by an empty string.
@attributesByNamespace = {}
if block_given?
if block.arity > 0
block[self]
else
instance_eval(&block)
end
end
end
# Creates a new child tag.
# Can take a block so that you can write something like:
#
# car = Tag.new("car") do
# new_child("wheels") do
# self << 4
# end
# end
#
# The context of execution of the given block is the child instance.
# If you provide a block that takes a parameter (see below), the context is the context of your
# code:
#
# car = Tag.new("car") do |child|
# child.new_child("wheels") do |grandchild|
# grandchild << 4
# end
# end
#
# Returns the created child Tag.
#
def new_child(*args, &block)
return add_child Tag.new(*args, &block)
end
# Add a child to this Tag.
#
# _child_:: The child to add
#
# Returns the added child.
#
def add_child(child)
@children.push(child)
return child
end
# Adds the given object as a child if it is a +Tag+, as an attribute if it is a Hash
# {key => value} (supports namespaces), or as a value otherwise.
# If it is an Enumerable (e.g. Array), each of its elements is added to this Tag via this
# operator. If any of its elements is itself an Enumerable, then an anonymous tag is created and
# the Enumerable is passed to it via this operator (see the examples below).
#
# tag << Tag.new("child")
# tag << 123 # new integer value
# tag << "islamabad" # new string value
# tag << { "metric:length" => 1027 } # new attribute (with namespace)
# tag << [nil, 456, "abc"] # several values added
#
# tag = Tag.new("tag")
# tag << [[1, 2, 3], [4, 5, 6]] # tag {
# # 1 2 3
# # 4 5 6
# # }
#
# Of course, despite the fact that String is an Enumerable, it is considered as the type of
# values.
#
# Returns +self+.
#
# Use other accessors (#add_child, #add_value, #attributes, etc) for a stricter and less
# "magical" behavior.
#
def <<(o)
if o.is_a?(Tag)
add_child(o)
elsif o.is_a?(Hash)
o.each_pair { |key, value|
namespace, key = key.split(/:/) if key.match(/:/)
namespace ||= ""
set_attribute(namespace, key, value)
}
elsif o.is_a? String
add_value(o)
elsif o.is_a? Enumerable
o.each { |item|
if item.is_a? Enumerable and not item.is_a? String
anonymous = new_child("content")
anonymous << item
else
self << item
end
}
else
add_value(o)
end
return self
end
# Remove a child from this Tag
#
# _child_:: the child to remove
#
# Returns true if the child exists and is removed
#
def remove_child(child)
return !@children.delete(child).nil?
end
# Removes all children.
#
def clear_children
@children = []
nil
end
#
# A convenience method that sets the first value in the value list.
# See # #add_value for legal types.
#
# _value_:: The value to be set.
#
# === Raises
#
# _ArgumentError_:: if the value is not a legal SDL type
#
def value=(value)
@values[0] = SDL4R.coerce_or_fail(value)
nil
end
#
# A convenience method that returns the first value.
#
def value
@values[0]
end
# Returns the number of children Tag.
#
def child_count
@children.size
end
# children(recursive)
# children(recursive, name)
# children(recursive, namespace, name)
#
# children(recursive) { |child| ... }
# children(recursive, name) { |child| ... }
# children(recursive, namespace, name) { |child| ... }
#
# Returns an Array of the children Tags of this Tag or enumerates them.
#
# _recursive_:: if true children and all descendants will be returned. False by default.
# _name_:: if not nil, only children having this name will be returned. Nil by default.
# _namespace_:: use nil for all namespaces and "" for the default one. Nil by default.
#
# tag.children # => array of the children
# tag.children(true) { |descendant| ... }
#
# tag.children(false, "name") # => children of name "name"
# tag.children(false, "ns", nil) # => children of namespace "ns"
#
def children(recursive = false, namespace = nil, name = :DEFAULT, &block) # :yields: child
if name == :DEFAULT
name = namespace
namespace = nil
end
if block_given?
each_child(recursive, namespace, name, &block)
return nil
else
unless recursive or name or namespace
return @children
else
result = []
each_child(recursive, namespace, name) { |child|
result << child
}
return result
end
end
end
# Returns the values of all the children with the given +name+. If the child has
# more than one value, all the values will be added as an array. If the child
# has no value, +nil+ will be added. The search is not recursive.
#
# _name_:: if nil, all children are considered (nil by default).
def children_values(name = nil)
children_values = []
each_child(false, name) { |child|
case child.values.size
when 0
children_values << nil
when 1
children_values << child.value
else
children_values << child.values
end
}
return children_values
end
# child
# child(name)
# child(recursive, name)
#
# Get the first child with the given name, optionally using a recursive search.
#
# _name_:: the name of the child Tag. If +nil+, the first child is returned (+nil+ if there are
# no children at all).
#
# Returns the first child tag having the given name or +nil+ if no such child exists
#
def child(recursive = false, name = nil)
if name.nil?
name = recursive
recursive = false
end
unless name
return @children.first
else
each_child(recursive, name) { |child| return child }
end
end
# Indicates whether the child Tag of given name exists.
#
# _name_:: name of the searched child Tag
#
def has_child?(name)
!child(name).nil?
end
# Indicates whether there are children Tag.
#
def has_children?
!@children.empty?
end
# Enumerates the children +Tag+s of this Tag and calls the given block
# providing it the child as parameter.
#
# _recursive_:: if true, enumerate grand-children, etc, recursively
# _namespace_:: if not nil, indicates the namespace of the children to enumerate
# _name_:: if not nil, indicates the name of the children to enumerate
#
def each_child(recursive = false, namespace = nil, name = :DEFAULT, &block)
if name == :DEFAULT
name = namespace
namespace = nil
end
@children.each do |child|
if (name.nil? or child.name == name) and
(namespace.nil? or child.namespace == namespace)
yield child
end
child.children(recursive, namespace, name, &block) if recursive
end
return nil
end
private :each_child
# Returns a new Hash where the children's names as keys and their values as the key's value.
# Example:
#
# child1 "toto"
# child2 2
#
# would give
#
# { "child1" => "toto", "child2" => 2 }
#
def to_child_hash
hash = {}
children { |child| hash[child.name] = child.value }
return hash
end
# Returns a new Hash where the children's names as keys and their values as the key's value.
# Values are converted to Strings. +nil+ values become empty Strings.
# Example:
#
# child1 "toto"
# child2 2
# child3 null
#
# would give
#
# { "child1" => "toto", "child2" => "2", "child3" => "" }
#
def to_child_string_hash
hash = {}
children do |child|
# FIXME: it is quite hard to be sure whether we should mimic the Java version
# as there might be a lot of values that don't translate nicely to Strings.
hash[child.name] = child.value.to_s
end
return hash
end
# Adds a value to this Tag. See SDL4R#coerce_or_fail to know about the allowable types.
#
# _v_:: The value to add
#
# Raises an +ArgumentError+ if the value is not a legal SDL type
#
def add_value(v)
@values.push(SDL4R::coerce_or_fail(v))
return nil
end
# Returns true if +v+ is a value of this Tag's.
#
def has_value?(v)
@values.include?(v)
end
# Removes the first occurence of the specified value from this Tag.
#
# _v_:: The value to remove
#
# Returns true If the value exists and is removed
#
def remove_value(v)
index = @values.index(v)
if index
return !@values.delete_at(index).nil?
else
return false
end
end
# Removes all values.
#
def clear_values
@values = []
nil
end
# Returns an Array of the values of this Tag or enumerates them.
#
# tag.values # => [123, "spices"]
# tag.values { |value| puts value }
#
def values # :yields: value
if block_given?
@values.each { |v| yield v }
nil
else
return @values
end
end
# Set the values for this tag. See #add_value for legal value types.
#
# _values_:: The new values
#
# Raises an +ArgumentError+ if the collection contains any values which are not legal SDL types.
#
def values=(someValues)
@values.clear()
someValues.to_a.each { |v|
# this is required to ensure validation of types
add_value(v)
}
nil
end
# set_attribute(key, value)
# set_attribute(namespace, key, value)
#
# Set an attribute in the given namespace for this tag. The allowable
# attribute value types are the same as those allowed for #add_value.
#
# _namespace_:: The namespace for this attribute
# _key_:: The attribute key
# _value_:: The attribute value
#
# Raises +ArgumentError+ if the key is not a legal SDL identifier (see
# SDL4R#validate_identifier), or the namespace is non-blank and is not a legal SDL identifier,
# or thevalue is not a legal SDL type
#
def set_attribute(namespace, key, value = :default)
if value == :default
value = key
key = namespace
namespace = ""
end
raise ArgumentError, "attribute namespace must be a String" unless namespace.is_a? String
raise ArgumentError, "attribute key must be a String" unless key.is_a? String
raise ArgumentError, "attribute key cannot be empty" if key.empty?
SDL4R.validate_identifier(namespace) unless namespace.empty?
SDL4R.validate_identifier(key)
attributes = @attributesByNamespace[namespace]
if attributes.nil?
attributes = {}
@attributesByNamespace[namespace] = attributes
end
attributes[key] = SDL4R.coerce_or_fail(value)
end
# attribute(key)
# attribute(namespace, key)
#
# Returns the attribute of the specified +namespace+ of specified +key+ or +nil+ if not found.
#
#
def attribute(namespace, key = nil)
namespace, key = to_nns namespace, key
attributes = @attributesByNamespace[namespace]
return attributes.nil? ? nil : attributes[key]
end
# Indicates whether there is at least an attribute in this Tag.
# has_attribute?
#
# Indicates whether there is the specified attribute exists in this Tag.
# has_attribute?(key)
# has_attribute?(namespace, key)
#
def has_attribute?(namespace = nil, key = nil)
namespace, key = to_nns namespace, key
if namespace or key
attributes = @attributesByNamespace[namespace]
return attributes.nil? ? false : attributes.has_key?(key)
else
attributes { return true }
return false
end
end
# Returns a Hash of the attributes of the specified +namespace+ (default is all) or enumerates
# them.
#
# tag.attributes # => { "length" => 123, "width" = 25.4, "orig:color" => "gray" }
# tag.attributes("orig") do |namespace, key, value|
# p "#{namespace}:#{key} = #{value}"
# end
#
# _namespace_::
# namespace of the returned attributes. If nil, all attributes are returned with
# qualified names (e.g. "meat:color"). If "", attributes of the default namespace are returned.
#
def attributes(namespace = nil, &block) # :yields: namespace, key, value
if block_given?
each_attribute(namespace, &block)
else
if namespace.nil?
hash = {}
each_attribute do | namespace, key, value |
qualified_name = namespace.empty? ? key : namespace + ':' + key
hash[qualified_name] = value
end
return hash
else
return @attributesByNamespace[namespace]
end
end
end
# remove_attribute(key)
# remove_attribute(namespace, key)
#
# Removes the attribute, whose name and namespace are specified.
#
# _key_:: name of the removed atribute
# _namespace_:: namespace of the removed attribute (equal to "", default namespace, by default)
#
# Returns the value of the removed attribute or +nil+ if it didn't exist.
#
# Clears the attributes of the specified namespace or all the attributes if +namespace+ is
# +nil+.
#
def clear_attributes(namespace = nil)
if namespace.nil?
@attributesByNamespace.clear
else
@attributesByNamespace.delete(namespace)
end
end
# Enumerates the attributes for the specified +namespace+.
# Enumerates all the attributes by default.
#
def each_attribute(namespace = nil, &block) # :yields: namespace, key, value
if namespace.nil?
@attributesByNamespace.each_key { |a_namespace| each_attribute(a_namespace, &block) }
else
attributes = @attributesByNamespace[namespace]
unless attributes.nil?
attributes.each_pair do |key, value|
yield namespace, key, value
end
end
end
end
private :each_attribute
# set_attributes(attribute_hash)
# set_attributes(namespace, attribute_hash)
#
# Sets the attributes specified by a Hash in the given +namespace+ in one operation. The
# previous attributes of the specified +namespace+ are removed.
# See #set_attribute for allowable attribute value types.
#
# _attributes_:: a Hash where keys are attribute keys
# _namespace_:: "" (default namespace) by default
#
# Raises an +ArgumentError+ if any key in the map is not a legal SDL identifier
# (see SDL4R#validate_identifier), or any value is not a legal SDL type.
#
def set_attributes(namespace, attribute_hash = nil)
if attribute_hash.nil?
attribute_hash = namespace
namespace = ""
end
raise ArgumentError, "namespace can't be nil" if namespace.nil?
raise ArgumentError, "attribute_hash should be a Hash" unless attribute_hash.is_a? Hash
namespace_attributes = @attributesByNamespace[namespace]
namespace_attributes.clear if namespace_attributes
attribute_hash.each_pair do |key, value|
# Calling set_attribute() is required to ensure validations
set_attribute(namespace, key, value)
end
end
# Sets all the attributes of the default namespace for this Tag in one
# operation.
#
# See #set_attributes.
#
def attributes=(attribute_hash)
set_attributes(attribute_hash)
end
# Sets the name of this Tag.
#
# Raises +ArgumentError+ if the name is not a legal SDL identifier
# (see SDL4R#validate_identifier).
#
def name=(a_name)
a_name = a_name.to_s
SDL4R.validate_identifier(a_name)
@name = a_name
end
# The namespace to set. +nil+ will be coerced to the empty string.
#
# Raises +ArgumentError+ if the namespace is non-blank and is not
# a legal SDL identifier (see SDL4R#validate_identifier)
#
def namespace=(a_namespace)
a_namespace = a_namespace.to_s
SDL4R.validate_identifier(a_namespace) unless a_namespace.empty?
@namespace = a_namespace
end
# Adds all the tags specified in the given IO, String, Pathname or URI to this Tag.
#
# Returns this Tag after adding all the children read from +input+.
#
def read(input)
if input.is_a? String
read_from_io(true) { StringIO.new(input) }
elsif input.is_a? Pathname
read_from_io(true) { input.open("r:UTF-8") }
elsif input.is_a? URI
read_from_io(true) { input.open }
else
read_from_io(false) { input }
end
return self
end
# Reads and parses the +io+ returned by the specified block and closes this +io+ if +close_io+
# is true.
def read_from_io(close_io)
io = yield
begin
Parser.new(io).parse.each do |tag|
add_child(tag)
end
ensure
if close_io
io.close rescue IOError
end
end
end
private_methods :read_io
# Write this tag out to the given IO or StringIO or String (optionally clipping the root.)
# Returns +output+.
#
# _output_:: an IO or StringIO or a String to write to
# +include_root+:: if true this tag will be written out as the root element, if false only the
# children will be written. False by default.
#
def write(output, include_root = false)
if output.is_a? String
io = StringIO.new(output)
close_io = true # indicates we close the IO ourselves
elsif output.is_a? IO or output.is_a? StringIO
io = output
close_io = false # let the caller close the IO
else
raise ArgumentError, "'output' should be a String or an IO but was #{output.class}"
end
if include_root
io << to_s
else
first = true
children do |child|
io << $/ unless first
first = false
io << child.to_s
end
end
io.close() if close_io
output
end
# Get a String representation of this SDL Tag. This method returns a
# complete description of the Tag's state using SDL (i.e. the output can
# be parsed by #read)
#
# Returns A string representation of this tag using SDL
#
def to_s
to_string
end
# _linePrefix_:: A prefix to insert before every line.
# Returns A string representation of this tag using SDL
#
# TODO: break up long lines using the backslash
#
def to_string(line_prefix = "", indent = "\t")
line_prefix = "" if line_prefix.nil?
s = ""
s << line_prefix
if name == "content" && namespace.empty?
skip_value_space = true
else
skip_value_space = false
s << "#{namespace}:" unless namespace.empty?
s << name
end
# output values
values do |value|
if skip_value_space
skip_value_space = false
else
s << " "
end
s << SDL4R.format(value, true, line_prefix, indent)
end
# output attributes
unless @attributesByNamespace.empty?
all_attributes_hash = attributes
all_attributes_array = all_attributes_hash.sort { |a, b|
namespace1, name1 = a[0].split(':')
namespace1, name1 = "", namespace1 if name1.nil?
namespace2, name2 = b[0].split(':')
namespace2, name2 = "", namespace2 if name2.nil?
diff = namespace1 <=> namespace2
diff == 0 ? name1 <=> name2 : diff
}
all_attributes_array.each do |attribute_name, attribute_value|
s << " " << attribute_name << '=' << SDL4R.format(attribute_value, true)
end
end
# output children
unless @children.empty?
s << " {#{$/}"
children_to_string(line_prefix + indent, s)
s << line_prefix << ?}
end
return s
end
# Returns a string representation of the children tags.
#
# _linePrefix_:: A prefix to insert before every line.
# _s_:: a String that receives the string representation
#
# TODO: break up long lines using the backslash
#
def children_to_string(line_prefix = "", s = "")
@children.each do |child|
s << child.to_string(line_prefix) << $/
end
return s
end
# Returns true if this tag (including all of its values, attributes, and
# children) is equivalent to the given tag.
#
# Returns true if the tags are equivalet
#
def eql?(o)
# this is safe because to_string() dumps the full state
return o.is_a?(Tag) && o.to_string == to_string;
end
alias_method :==, :eql?
# Returns The hash (based on the output from toString())
#
def hash
return to_string.hash
end
# Returns a string containing an XML representation of this tag. Values
# will be represented using _val0, _val1, etc.
#
# _options_:: a hash of the options
#
# === options:
#
# [:line_prefix] a text prefixing each line (default: "")
# [:uri_by_namespace] a Hash giving the URIs for the namespaces
# [:indent] text specifying one indentation (default: "\t")
# [:eol] end of line expression (default: "\n")
# [:omit_null_attributes]
# if true, null/nil attributes are not exported (default: false). Otherwise, they are exported
# as follows:
# tag attr="null"
#
def to_xml_string(options = {})
options = {
:uri_by_namespace => nil,
:indent => "\t",
:line_prefix => "",
:eol => "\n",
:omit_null_attributes => false
}.merge(options)
_to_xml_string(options[:line_prefix], options)
end
protected
# Implementation of #to_xml_string but without the extra-treatment on parameters for default
# values.
def _to_xml_string(line_prefix, options)
eol = options[:eol]
s = ""
s << line_prefix << ?<
s << "#{namespace}:" unless namespace.empty?
s << name
# output namespace declarations
uri_by_namespace = options[:uri_by_namespace]
if uri_by_namespace
uri_by_namespace.each_pair do |namespace, uri|
if namespace
s << " xmlns:#{namespace}=\"#{uri}\""
else
s << " xmlns=\"#{uri}\""
end
end
end
# output values
unless @values.empty?
i = 0
@values.each do |value|
s << " _val" << i.to_s << "=\"" << SDL4R.format(value, false) << "\""
i += 1
end
end
# output attributes
if has_attribute?
omit_null_attributes = options[:omit_null_attributes]
attributes do |attribute_namespace, attribute_name, attribute_value|
unless omit_null_attributes and attribute_value.nil?
s << " "
s << "#{attribute_namespace}:" unless attribute_namespace.empty?
s << attribute_name << "=\"" << SDL4R.format(attribute_value, false) << ?"
end
end
end
if @children.empty?
s << "/>"
else
s << ">" << eol
@children.each do |child|
s << child._to_xml_string(line_prefix + options[:indent], options) << eol
end
s << line_prefix << "</"
s << "#{namespace}:" unless namespace.empty?
s << name << ?>
end
return s
end
end
|
lostisland/faraday | lib/faraday/encoders/nested_params_encoder.rb | Faraday.DecodeMethods.dehash | ruby | def dehash(hash, depth)
hash.each do |key, value|
hash[key] = dehash(value, depth + 1) if value.is_a?(Hash)
end
if depth.positive? && !hash.empty? && hash.keys.all? { |k| k =~ /^\d+$/ }
hash.sort.map(&:last)
else
hash
end
end | Internal: convert a nested hash with purely numeric keys into an array.
FIXME: this is not compatible with Rack::Utils.parse_nested_query
@!visibility private | train | https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/encoders/nested_params_encoder.rb#L145-L155 | module DecodeMethods
# @param query [nil, String]
#
# @return [Array<Array, String>] the decoded params
#
# @raise [TypeError] if the nesting is incorrect
def decode(query)
return nil if query.nil?
params = {}
query.split('&').each do |pair|
next if pair.empty?
key, value = pair.split('=', 2)
key = unescape(key)
value = unescape(value.tr('+', ' ')) if value
decode_pair(key, value, params)
end
dehash(params, 0)
end
protected
SUBKEYS_REGEX = /[^\[\]]+(?:\]?\[\])?/.freeze
def decode_pair(key, value, context)
subkeys = key.scan(SUBKEYS_REGEX)
subkeys.each_with_index do |subkey, i|
is_array = subkey =~ /[\[\]]+\Z/
subkey = $` if is_array
last_subkey = i == subkeys.length - 1
context = prepare_context(context, subkey, is_array, last_subkey)
add_to_context(is_array, context, value, subkey) if last_subkey
end
end
def prepare_context(context, subkey, is_array, last_subkey)
if !last_subkey || is_array
context = new_context(subkey, is_array, context)
end
if context.is_a?(Array) && !is_array
context = match_context(context, subkey)
end
context
end
def new_context(subkey, is_array, context)
value_type = is_array ? Array : Hash
if context[subkey] && !context[subkey].is_a?(value_type)
raise TypeError, "expected #{value_type.name} " \
"(got #{context[subkey].class.name}) for param `#{subkey}'"
end
context[subkey] ||= value_type.new
end
def match_context(context, subkey)
context << {} if !context.last.is_a?(Hash) || context.last.key?(subkey)
context.last
end
def add_to_context(is_array, context, value, subkey)
is_array ? context << value : context[subkey] = value
end
# Internal: convert a nested hash with purely numeric keys into an array.
# FIXME: this is not compatible with Rack::Utils.parse_nested_query
# @!visibility private
end
|
alexreisner/geocoder | lib/geocoder/lookups/latlon.rb | Geocoder::Lookup.Latlon.query_url_params | ruby | def query_url_params(query)
if query.reverse_geocode?
{
:token => configuration.api_key,
:lat => query.coordinates[0],
:lon => query.coordinates[1]
}.merge(super)
else
{
:token => configuration.api_key,
:address => query.sanitized_text
}.merge(super)
end
end | --------------------------------------------------------------- | train | https://github.com/alexreisner/geocoder/blob/e087dc2759264ee6f307b926bb2de4ec2406859e/lib/geocoder/lookups/latlon.rb#L43-L56 | class Latlon < Base
def name
"LatLon.io"
end
def required_api_key_parts
["api_key"]
end
private # ---------------------------------------------------------------
def base_query_url(query)
"#{protocol}://latlon.io/api/v1/#{'reverse_' if query.reverse_geocode?}geocode?"
end
def results(query)
return [] unless doc = fetch_data(query)
if doc['error'].nil?
[doc]
# The API returned a 404 response, which indicates no results found
elsif doc['error']['type'] == 'api_error'
[]
elsif
doc['error']['type'] == 'authentication_error'
raise_error(Geocoder::InvalidApiKey) ||
Geocoder.log(:warn, "LatLon.io service error: invalid API key.")
else
[]
end
end
def supported_protocols
[:https]
end
private # ---------------------------------------------------------------
end
|
sds/haml-lint | lib/haml_lint/document.rb | HamlLint.Document.convert_tree | ruby | def convert_tree(haml_node, parent = nil)
new_node = @node_transformer.transform(haml_node)
new_node.parent = parent
new_node.children = haml_node.children.map do |child|
convert_tree(child, new_node)
end
new_node
end | Converts a HAML parse tree to a tree of {HamlLint::Tree::Node} objects.
This provides a cleaner interface with which the linters can interact with
the parse tree.
@param haml_node [Haml::Parser::ParseNode]
@param parent [Haml::Tree::Node]
@return [Haml::Tree::Node] | train | https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/document.rb#L78-L87 | class Document
# File name given to source code parsed from just a string.
STRING_SOURCE = '(string)'
# @return [HamlLint::Configuration] Configuration used to parse template
attr_reader :config
# @return [String] Haml template file path
attr_reader :file
# @return [HamlLint::Tree::Node] Root of the parse tree
attr_reader :tree
# @return [String] original source code
attr_reader :source
# @return [Array<String>] original source code as an array of lines
attr_reader :source_lines
# Parses the specified Haml code into a {Document}.
#
# @param source [String] Haml code to parse
# @param options [Hash]
# @option options :file [String] file name of document that was parsed
# @raise [Haml::Parser::Error] if there was a problem parsing the document
def initialize(source, options)
@config = options[:config]
@file = options.fetch(:file, STRING_SOURCE)
process_source(source)
end
private
# @param source [String] Haml code to parse
# @raise [HamlLint::Exceptions::ParseError] if there was a problem parsing
def process_source(source)
@source = process_encoding(source)
@source = strip_frontmatter(source)
@source_lines = @source.split(/\r\n|\r|\n/)
@tree = process_tree(HamlLint::Adapter.detect_class.new(@source).parse)
rescue Haml::Error => e
error = HamlLint::Exceptions::ParseError.new(e.message, e.line)
raise error
end
# Processes the {Haml::Parser::ParseNode} tree and returns a tree composed
# of friendlier {HamlLint::Tree::Node}s.
#
# @param original_tree [Haml::Parser::ParseNode]
# @return [Haml::Tree::Node]
def process_tree(original_tree)
# Remove the trailing empty HAML comment that the parser creates to signal
# the end of the HAML document
if Gem::Requirement.new('~> 4.0.0').satisfied_by?(Gem.loaded_specs['haml'].version)
original_tree.children.pop
end
@node_transformer = HamlLint::NodeTransformer.new(self)
convert_tree(original_tree)
end
# Converts a HAML parse tree to a tree of {HamlLint::Tree::Node} objects.
#
# This provides a cleaner interface with which the linters can interact with
# the parse tree.
#
# @param haml_node [Haml::Parser::ParseNode]
# @param parent [Haml::Tree::Node]
# @return [Haml::Tree::Node]
# Ensures source code is interpreted as UTF-8.
#
# This is necessary as sometimes Ruby guesses the encoding of a file
# incorrectly, for example if the LC_ALL environment variable is set to "C".
# @see http://unix.stackexchange.com/a/87763
#
# @param source [String]
# @return [String] source encoded with UTF-8 encoding
def process_encoding(source)
source.force_encoding(Encoding::UTF_8)
end
# Removes YAML frontmatter
def strip_frontmatter(source)
frontmatter = /
# From the start of the string
\A
# First-capture match --- followed by optional whitespace up
# to a newline then 0 or more chars followed by an optional newline.
# This matches the --- and the contents of the frontmatter
(---\s*\n.*?\n?)
# From the start of the line
^
# Second capture match --- or ... followed by optional whitespace
# and newline. This matches the closing --- for the frontmatter.
(---|\.\.\.)\s*$\n?/mx
if config['skip_frontmatter'] && match = source.match(frontmatter)
newlines = match[0].count("\n")
source.sub!(frontmatter, "\n" * newlines)
end
source
end
end
|
amatsuda/active_decorator | lib/active_decorator/decorator.rb | ActiveDecorator.Decorator.decorator_for | ruby | def decorator_for(model_class)
return @@decorators[model_class] if @@decorators.key? model_class
decorator_name = "#{model_class.name}#{ActiveDecorator.config.decorator_suffix}"
d = Object.const_get decorator_name, false
unless Class === d
d.send :include, ActiveDecorator::Helpers
@@decorators[model_class] = d
else
# Cache nil results
@@decorators[model_class] = nil
end
rescue NameError
if model_class.respond_to?(:base_class) && (model_class.base_class != model_class)
@@decorators[model_class] = decorator_for model_class.base_class
else
# Cache nil results
@@decorators[model_class] = nil
end
end | Returns a decorator module for the given class.
Returns `nil` if no decorator module was found. | train | https://github.com/amatsuda/active_decorator/blob/e7cfa764e657ea8bbb4cbe92cb220ee67ebae58e/lib/active_decorator/decorator.rb#L68-L87 | class Decorator
include Singleton
def initialize
@@decorators = {}
end
# Decorates the given object.
# Plus, performs special decoration for the classes below:
# Array: decorates its each element
# Hash: decorates its each value
# AR::Relation: decorates its each record lazily
# AR model: decorates its associations on the fly
#
# Always returns the object, regardless of whether decorated or not decorated.
#
# This method can be publicly called from anywhere by `ActiveDecorator::Decorator.instance.decorate(obj)`.
def decorate(obj)
return if defined?(Jbuilder) && (Jbuilder === obj)
return if obj.nil?
if obj.is_a?(Array)
obj.each do |r|
decorate r
end
elsif obj.is_a?(Hash)
obj.each_value do |v|
decorate v
end
elsif defined?(ActiveRecord) && obj.is_a?(ActiveRecord::Relation)
# don't call each nor to_a immediately
if obj.respond_to?(:records)
# Rails 5.0
obj.extend ActiveDecorator::RelationDecorator unless obj.is_a? ActiveDecorator::RelationDecorator
else
# Rails 3.x and 4.x
obj.extend ActiveDecorator::RelationDecoratorLegacy unless obj.is_a? ActiveDecorator::RelationDecoratorLegacy
end
else
if defined?(ActiveRecord) && obj.is_a?(ActiveRecord::Base) && !obj.is_a?(ActiveDecorator::Decorated)
obj.extend ActiveDecorator::Decorated
end
d = decorator_for obj.class
return obj unless d
obj.extend d unless obj.is_a? d
end
obj
end
# Decorates AR model object's association only when the object was decorated.
# Returns the association instance.
def decorate_association(owner, target)
owner.is_a?(ActiveDecorator::Decorated) ? decorate(target) : target
end
private
# Returns a decorator module for the given class.
# Returns `nil` if no decorator module was found.
end
|
giraffi/zcloudjp | lib/zcloudjp/client.rb | Zcloudjp.Client.method_missing | ruby | def method_missing(method, *args, &block)
self.class.class_eval do
attr_accessor method.to_sym
# Defined a method according to the given method name
define_method method.to_sym do
obj = OpenStruct.new(request_options: @request_options)
obj.extend Zcloudjp.const_get(method.capitalize.to_sym)
instance_variable_set(:"@#{method}", obj)
end
end
# Sends to the now-defined method.
self.__send__(method.to_sym)
end | Defines the method if not defined yet. | train | https://github.com/giraffi/zcloudjp/blob/0ee8dd49cf469fd182a48856fae63f606a959de5/lib/zcloudjp/client.rb#L33-L47 | class Client
include HTTParty
format :json
attr_reader :base_uri, :api_key
def initialize(options={})
@api_key = options.delete(:api_key) || ENV['ZCLOUDJP_API_KEY']
@base_uri = options[:endpoint] || "https://my.z-cloud.jp"
unless @api_key; raise ArgumentError, "options[:api_key] required"; end
request_options
end
def request_options
@request_options = {
:base_uri => @base_uri,
:headers => {
"X-API-KEY" => @api_key,
"Content-Type" => "application/json; charset=utf-8",
"Accept" => "application/json",
"User-Agent" => Zcloudjp::USER_AGENT
}
}
end
# Defines the method if not defined yet.
end
|
rossf7/elasticrawl | lib/elasticrawl/cluster.rb | Elasticrawl.Cluster.create_job_flow | ruby | def create_job_flow(job, emr_config = nil)
config = Config.new
Elasticity.configure do |c|
c.access_key = config.access_key_id
c.secret_key = config.secret_access_key
end
job_flow = Elasticity::JobFlow.new
job_flow.name = "Job: #{job.job_name} #{job.job_desc}"
job_flow.log_uri = job.log_uri
configure_job_flow(job_flow)
configure_instances(job_flow)
configure_bootstrap_actions(job_flow, emr_config)
job_flow
end | Returns a configured job flow to the calling job. | train | https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/cluster.rb#L12-L29 | class Cluster
def initialize
@master_group = instance_group('master')
@core_group = instance_group('core')
@task_group = instance_group('task') if has_task_group?
end
# Returns a configured job flow to the calling job.
# Describes the instances that will be launched. This is used by the
# job confirmation messages.
def cluster_desc
cluster_desc = <<-HERE
Cluster configuration
Master: #{instance_group_desc(@master_group)}
Core: #{instance_group_desc(@core_group)}
Task: #{instance_group_desc(@task_group)}
HERE
end
private
# Set job flow properties from settings in cluster.yml.
def configure_job_flow(job_flow)
ec2_key_name = config_setting('ec2_key_name')
placement = config_setting('placement')
emr_ami_version = config_setting('emr_ami_version')
job_flow_role = config_setting('job_flow_role')
service_role = config_setting('service_role')
ec2_subnet_id = config_setting('ec2_subnet_id')
job_flow.ec2_subnet_id = ec2_subnet_id if ec2_subnet_id.present?
job_flow.ec2_key_name = ec2_key_name if ec2_key_name.present?
job_flow.placement = placement if placement.present?
job_flow.ami_version = emr_ami_version if emr_ami_version.present?
job_flow.job_flow_role = job_flow_role if job_flow_role.present?
job_flow.service_role = service_role if service_role.present?
end
# Configures the instances that will be launched. The master group has
# a single node. The task group is optional.
def configure_instances(job_flow)
job_flow.set_master_instance_group(@master_group)
job_flow.set_core_instance_group(@core_group)
job_flow.set_task_instance_group(@task_group) if @task_group.present?
end
# Configures bootstrap actions that will be run when each instance is
# launched. EMR config is an XML file of Hadoop settings stored on S3.
# There are applied to each node by a bootstrap action.
def configure_bootstrap_actions(job_flow, emr_config = nil)
bootstrap_scripts = config_setting('bootstrap_scripts')
if bootstrap_scripts.present?
bootstrap_scripts.each do |script_uri|
action = Elasticity::BootstrapAction.new(script_uri, '', '')
job_flow.add_bootstrap_action(action)
end
end
if emr_config.present?
action = Elasticity::HadoopFileBootstrapAction.new(emr_config)
job_flow.add_bootstrap_action(action)
end
end
# Returns whether cluster.yml specifies a task group.
def has_task_group?
task_config = config_for_group('task')
task_config.has_key?('instance_count') && task_config['instance_count'] > 0
end
# Describes an instance group.
def instance_group_desc(group)
if group.present?
if group.market == 'SPOT'
price = "(Spot: #{group.bid_price})"
else
price = '(On Demand)'
end
"#{group.count} #{group.type} #{price}"
else
'--'
end
end
# Configures an instance group with the instance type, # of instances and
# the bid price if spot instances are to be used.
def instance_group(group_name)
config = config_for_group(group_name)
instance_group = Elasticity::InstanceGroup.new
instance_group.role = group_name.upcase
instance_group.type = config['instance_type']
if config.has_key?('instance_count') && config['instance_count'] > 0
instance_group.count = config['instance_count']
end
if config['use_spot_instances'] == true
instance_group.set_spot_instances(config['bid_price'])
end
instance_group
end
# Returns the config settings for an instance group.
def config_for_group(group_name)
config_setting("#{group_name}_instance_group")
end
# Returns a config setting from cluster.yml.
def config_setting(key_name)
config = Config.new
config.load_config('cluster')[key_name]
end
end
|
zed-0xff/zpng | lib/zpng/color.rb | ZPNG.Color.to_ansi | ruby | def to_ansi
return to_depth(8).to_ansi if depth != 8
a = ANSI_COLORS.map{|c| self.class.const_get(c.to_s.upcase) }
a.map!{ |c| self.euclidian(c) }
ANSI_COLORS[a.index(a.min)]
end | convert to ANSI color name | train | https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L142-L147 | class Color
attr_accessor :r, :g, :b
attr_reader :a
attr_accessor :depth
include DeepCopyable
def initialize *a
h = a.last.is_a?(Hash) ? a.pop : {}
@r,@g,@b,@a = *a
# default sample depth for r,g,b and alpha = 8 bits
@depth = h[:depth] || 8
# default ALPHA = 0xff - opaque
@a ||= h[:alpha] || h[:a] || (2**@depth-1)
end
def a= a
@a = a || (2**@depth-1) # NULL alpha means fully opaque
end
alias :alpha :a
alias :alpha= :a=
BLACK = Color.new(0 , 0, 0)
WHITE = Color.new(255,255,255)
RED = Color.new(255, 0, 0)
GREEN = Color.new(0 ,255, 0)
BLUE = Color.new(0 , 0,255)
YELLOW= Color.new(255,255, 0)
CYAN = Color.new( 0,255,255)
PURPLE= MAGENTA =
Color.new(255, 0,255)
TRANSPARENT = Color.new(0,0,0,0)
ANSI_COLORS = [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white]
#ASCII_MAP = %q_ .`,-:;~"!<+*^(LJ=?vctsxj12FuoCeyPSah5wVmXA4G9$OR0MQNW#&%@_
#ASCII_MAP = %q_ .`,-:;~"!<+*^=VXMQNW#&%@_
#ASCII_MAP = %q_ .,:"!*=7FZVXM#%@_
# see misc/gen_ascii_map.rb
ASCII_MAP =
[" '''''''```,,",
",,---:::::;;;;~~\"\"\"\"",
"\"!!!!!!<++*^^^(((LLJ",
"=??vvv]ts[j1122FFuoo",
"CeyyPEah55333VVmmXA4",
"G9$666666RRRRRR00MQQ",
"NNW####&&&&&%%%%%%%%",
"@@@@@@@"].join
# euclidian distance - http://en.wikipedia.org/wiki/Euclidean_distance
def euclidian other_color
# TODO: different depths
r = (self.r.to_i - other_color.r.to_i)**2
r += (self.g.to_i - other_color.g.to_i)**2
r += (self.b.to_i - other_color.b.to_i)**2
Math.sqrt r
end
def white?
max = 2**depth-1
r == max && g == max && b == max
end
def black?
r == 0 && g == 0 && b == 0
end
def transparent?
a == 0
end
def opaque?
a.nil? || a == 2**depth-1
end
def to_grayscale
(r+g+b)/3
end
def to_gray_alpha
[to_grayscale, alpha]
end
class << self
# from_grayscale level
# from_grayscale level, :depth => 16
# from_grayscale level, alpha
# from_grayscale level, alpha, :depth => 16
def from_grayscale value, *args
Color.new value,value,value, *args
end
# value: (String) "#ff00ff", "#f0f", "f0f", "eebbcc"
# alpha can be set via :alpha => N optional hash argument
def from_html value, *args
s = value.tr('#','')
case s.size
when 3
r,g,b = s.split('').map{ |x| x.to_i(16)*17 }
when 6
r,g,b = s.scan(/../).map{ |x| x.to_i(16) }
else
raise ArgumentError, "invalid HTML color #{s}"
end
Color.new r,g,b, *args
end
alias :from_css :from_html
end
########################################################
# simple conversions
def to_i
((a||0) << 24) + ((r||0) << 16) + ((g||0) << 8) + (b||0)
end
def to_s
"%02X%02X%02X" % [r,g,b]
end
def to_a
[r, g, b, a]
end
########################################################
# complex conversions
# try to convert to one pseudographics ASCII character
def to_ascii map=ASCII_MAP
#p self
map[self.to_grayscale*(map.size-1)/(2**@depth-1), 1]
end
# convert to ANSI color name
# HTML/CSS color in notation like #33aa88
def to_css
return to_depth(8).to_css if depth != 8
"#%02X%02X%02X" % [r,g,b]
end
alias :to_html :to_css
########################################################
# change bit depth, return new Color
def to_depth new_depth
return self if depth == new_depth
color = Color.new :depth => new_depth
if new_depth > self.depth
%w'r g b a'.each do |part|
color.send("#{part}=", (2**new_depth-1)/(2**depth-1)*self.send(part))
end
else
# new_depth < self.depth
%w'r g b a'.each do |part|
color.send("#{part}=", self.send(part)>>(self.depth-new_depth))
end
end
color
end
def inspect
s = "#<ZPNG::Color"
if depth == 16
s << " r=" + (r ? "%04x" % r : "????")
s << " g=" + (g ? "%04x" % g : "????")
s << " b=" + (b ? "%04x" % b : "????")
s << " alpha=%04x" % alpha if alpha && alpha != 0xffff
else
s << " #"
s << (r ? "%02x" % r : "??")
s << (g ? "%02x" % g : "??")
s << (b ? "%02x" % b : "??")
s << " alpha=%02x" % alpha if alpha && alpha != 0xff
end
s << " depth=#{depth}" if depth != 8
s << ">"
end
# compare with other color
def == c
return false unless c.is_a?(Color)
c1,c2 =
if self.depth > c.depth
[self, c.to_depth(self.depth)]
else
[self.to_depth(c.depth), c]
end
c1.r == c2.r && c1.g == c2.g && c1.b == c2.b && c1.a == c2.a
end
alias :eql? :==
# compare with other color
def <=> c
c1,c2 =
if self.depth > c.depth
[self, c.to_depth(self.depth)]
else
[self.to_depth(c.depth), c]
end
r = c1.to_grayscale <=> c2.to_grayscale
r == 0 ? (c1.to_a <=> c2.to_a) : r
end
# subtract other color from this one, returns new Color
def - c
op :-, c
end
# add other color to this one, returns new Color
def + c
op :+, c
end
# XOR this color with other one, returns new Color
def ^ c
op :^, c
end
# AND this color with other one, returns new Color
def & c
op :&, c
end
# OR this color with other one, returns new Color
def | c
op :|, c
end
# Op! op! op! Op!! Oppan Gangnam Style!!
def op op, c=nil
# XXX what to do with alpha?
max = 2**depth-1
if c
c = c.to_depth(depth)
Color.new(
@r.send(op, c.r) & max,
@g.send(op, c.g) & max,
@b.send(op, c.b) & max,
:depth => self.depth
)
else
Color.new(
@r.send(op) & max,
@g.send(op) & max,
@b.send(op) & max,
:depth => self.depth
)
end
end
# for Array.uniq()
def hash
self.to_i
end
end
|
forward3d/rbhive | lib/rbhive/t_c_l_i_connection.rb | RBHive.TCLIConnection.fetch_rows | ruby | def fetch_rows(op_handle, orientation = :first, max_rows = 1000)
fetch_req = prepare_fetch_results(op_handle, orientation, max_rows)
fetch_results = @client.FetchResults(fetch_req)
raise_error_if_failed!(fetch_results)
rows = fetch_results.results.rows
TCLIResultSet.new(rows, TCLISchemaDefinition.new(get_schema_for(op_handle), rows.first))
end | Pull rows from the query result | train | https://github.com/forward3d/rbhive/blob/a630b57332f2face03501da3ecad2905c78056fa/lib/rbhive/t_c_l_i_connection.rb#L300-L306 | class TCLIConnection
attr_reader :client
def initialize(server, port = 10_000, options = {}, logger = StdOutLogger.new)
options ||= {} # backwards compatibility
raise "'options' parameter must be a hash" unless options.is_a?(Hash)
if options[:transport] == :sasl and options[:sasl_params].nil?
raise ":transport is set to :sasl, but no :sasl_params option was supplied"
end
# Defaults to buffered transport, Hive 0.10, 1800 second timeout
options[:transport] ||= :buffered
options[:hive_version] ||= 10
options[:timeout] ||= 1800
@options = options
# Look up the appropriate Thrift protocol version for the supplied Hive version
@thrift_protocol_version = thrift_hive_protocol(options[:hive_version])
@logger = logger
@transport = thrift_transport(server, port)
@protocol = Thrift::BinaryProtocol.new(@transport)
@client = Hive2::Thrift::TCLIService::Client.new(@protocol)
@session = nil
@logger.info("Connecting to HiveServer2 #{server} on port #{port}")
end
def thrift_hive_protocol(version)
HIVE_THRIFT_MAPPING[version] || raise("Invalid Hive version")
end
def thrift_transport(server, port)
@logger.info("Initializing transport #{@options[:transport]}")
case @options[:transport]
when :buffered
return Thrift::BufferedTransport.new(thrift_socket(server, port, @options[:timeout]))
when :sasl
return Thrift::SaslClientTransport.new(thrift_socket(server, port, @options[:timeout]),
parse_sasl_params(@options[:sasl_params]))
when :http
return Thrift::HTTPClientTransport.new("http://#{server}:#{port}/cliservice")
else
raise "Unrecognised transport type '#{transport}'"
end
end
def thrift_socket(server, port, timeout)
socket = Thrift::Socket.new(server, port)
socket.timeout = timeout
socket
end
# Processes SASL connection params and returns a hash with symbol keys or a nil
def parse_sasl_params(sasl_params)
# Symbilize keys in a hash
if sasl_params.kind_of?(Hash)
return sasl_params.inject({}) do |memo,(k,v)|
memo[k.to_sym] = v;
memo
end
end
return nil
end
def open
@transport.open
end
def close
@transport.close
end
def open_session
@session = @client.OpenSession(prepare_open_session(@thrift_protocol_version))
end
def close_session
@client.CloseSession prepare_close_session
@session = nil
end
def session
@session && @session.sessionHandle
end
def client
@client
end
def execute(query)
@logger.info("Executing Hive Query: #{query}")
req = prepare_execute_statement(query)
exec_result = client.ExecuteStatement(req)
raise_error_if_failed!(exec_result)
exec_result
end
def priority=(priority)
set("mapred.job.priority", priority)
end
def queue=(queue)
set("mapred.job.queue.name", queue)
end
def set(name,value)
@logger.info("Setting #{name}=#{value}")
self.execute("SET #{name}=#{value}")
end
# Async execute
def async_execute(query)
@logger.info("Executing query asynchronously: #{query}")
exec_result = @client.ExecuteStatement(
Hive2::Thrift::TExecuteStatementReq.new(
sessionHandle: @session.sessionHandle,
statement: query,
runAsync: true
)
)
raise_error_if_failed!(exec_result)
op_handle = exec_result.operationHandle
# Return handles to get hold of this query / session again
{
session: @session.sessionHandle,
guid: op_handle.operationId.guid,
secret: op_handle.operationId.secret
}
end
# Is the query complete?
def async_is_complete?(handles)
async_state(handles) == :finished
end
# Is the query actually running?
def async_is_running?(handles)
async_state(handles) == :running
end
# Has the query failed?
def async_is_failed?(handles)
async_state(handles) == :error
end
def async_is_cancelled?(handles)
async_state(handles) == :cancelled
end
def async_cancel(handles)
@client.CancelOperation(prepare_cancel_request(handles))
end
# Map states to symbols
def async_state(handles)
response = @client.GetOperationStatus(
Hive2::Thrift::TGetOperationStatusReq.new(operationHandle: prepare_operation_handle(handles))
)
case response.operationState
when Hive2::Thrift::TOperationState::FINISHED_STATE
return :finished
when Hive2::Thrift::TOperationState::INITIALIZED_STATE
return :initialized
when Hive2::Thrift::TOperationState::RUNNING_STATE
return :running
when Hive2::Thrift::TOperationState::CANCELED_STATE
return :cancelled
when Hive2::Thrift::TOperationState::CLOSED_STATE
return :closed
when Hive2::Thrift::TOperationState::ERROR_STATE
return :error
when Hive2::Thrift::TOperationState::UKNOWN_STATE
return :unknown
when Hive2::Thrift::TOperationState::PENDING_STATE
return :pending
when nil
raise "No operation state found for handles - has the session been closed?"
else
return :state_not_in_protocol
end
end
# Async fetch results from an async execute
def async_fetch(handles, max_rows = 100)
# Can't get data from an unfinished query
unless async_is_complete?(handles)
raise "Can't perform fetch on a query in state: #{async_state(handles)}"
end
# Fetch and
fetch_rows(prepare_operation_handle(handles), :first, max_rows)
end
# Performs a query on the server, fetches the results in batches of *batch_size* rows
# and yields the result batches to a given block as arrays of rows.
def async_fetch_in_batch(handles, batch_size = 1000, &block)
raise "No block given for the batch fetch request!" unless block_given?
# Can't get data from an unfinished query
unless async_is_complete?(handles)
raise "Can't perform fetch on a query in state: #{async_state(handles)}"
end
# Now let's iterate over the results
loop do
rows = fetch_rows(prepare_operation_handle(handles), :next, batch_size)
break if rows.empty?
yield rows
end
end
def async_close_session(handles)
validate_handles!(handles)
@client.CloseSession(Hive2::Thrift::TCloseSessionReq.new( sessionHandle: handles[:session] ))
end
# Pull rows from the query result
# Performs a explain on the supplied query on the server, returns it as a ExplainResult.
# (Only works on 0.12 if you have this patch - https://issues.apache.org/jira/browse/HIVE-5492)
def explain(query)
rows = []
fetch_in_batch("EXPLAIN " + query) do |batch|
rows << batch.map { |b| b[:Explain] }
end
ExplainResult.new(rows.flatten)
end
# Performs a query on the server, fetches up to *max_rows* rows and returns them as an array.
def fetch(query, max_rows = 100)
# Execute the query and check the result
exec_result = execute(query)
raise_error_if_failed!(exec_result)
# Get search operation handle to fetch the results
op_handle = exec_result.operationHandle
# Fetch the rows
fetch_rows(op_handle, :first, max_rows)
end
# Performs a query on the server, fetches the results in batches of *batch_size* rows
# and yields the result batches to a given block as arrays of rows.
def fetch_in_batch(query, batch_size = 1000, &block)
raise "No block given for the batch fetch request!" unless block_given?
# Execute the query and check the result
exec_result = execute(query)
raise_error_if_failed!(exec_result)
# Get search operation handle to fetch the results
op_handle = exec_result.operationHandle
# Prepare fetch results request
fetch_req = prepare_fetch_results(op_handle, :next, batch_size)
# Now let's iterate over the results
loop do
rows = fetch_rows(op_handle, :next, batch_size)
break if rows.empty?
yield rows
end
end
def create_table(schema)
execute(schema.create_table_statement)
end
def drop_table(name)
name = name.name if name.is_a?(TableSchema)
execute("DROP TABLE `#{name}`")
end
def replace_columns(schema)
execute(schema.replace_columns_statement)
end
def add_columns(schema)
execute(schema.add_columns_statement)
end
def method_missing(meth, *args)
client.send(meth, *args)
end
private
def prepare_open_session(client_protocol)
req = ::Hive2::Thrift::TOpenSessionReq.new( @options[:sasl_params].nil? ? [] : @options[:sasl_params] )
req.client_protocol = client_protocol
req
end
def prepare_close_session
::Hive2::Thrift::TCloseSessionReq.new( sessionHandle: self.session )
end
def prepare_execute_statement(query)
::Hive2::Thrift::TExecuteStatementReq.new( sessionHandle: self.session, statement: query.to_s, confOverlay: {} )
end
def prepare_fetch_results(handle, orientation=:first, rows=100)
orientation_value = "FETCH_#{orientation.to_s.upcase}"
valid_orientations = ::Hive2::Thrift::TFetchOrientation::VALUE_MAP.values
unless valid_orientations.include?(orientation_value)
raise ArgumentError, "Invalid orientation: #{orientation.inspect}"
end
orientation_const = eval("::Hive2::Thrift::TFetchOrientation::#{orientation_value}")
::Hive2::Thrift::TFetchResultsReq.new(
operationHandle: handle,
orientation: orientation_const,
maxRows: rows
)
end
def prepare_operation_handle(handles)
validate_handles!(handles)
Hive2::Thrift::TOperationHandle.new(
operationId: Hive2::Thrift::THandleIdentifier.new(guid: handles[:guid], secret: handles[:secret]),
operationType: Hive2::Thrift::TOperationType::EXECUTE_STATEMENT,
hasResultSet: false
)
end
def prepare_cancel_request(handles)
Hive2::Thrift::TCancelOperationReq.new(
operationHandle: prepare_operation_handle(handles)
)
end
def validate_handles!(handles)
unless handles.has_key?(:guid) and handles.has_key?(:secret) and handles.has_key?(:session)
raise "Invalid handles hash: #{handles.inspect}"
end
end
def get_schema_for(handle)
req = ::Hive2::Thrift::TGetResultSetMetadataReq.new( operationHandle: handle )
metadata = client.GetResultSetMetadata( req )
metadata.schema
end
# Raises an exception if given operation result is a failure
def raise_error_if_failed!(result)
return if result.status.statusCode == 0
error_message = result.status.errorMessage || 'Execution failed!'
raise RBHive::TCLIConnectionError.new(error_message)
end
end
|
sosedoff/lxc-ruby | lib/lxc/container.rb | LXC.Container.clone_to | ruby | def clone_to(target)
raise ContainerError, "Container does not exist." unless exists?
if LXC.container(target).exists?
raise ContainerError, "New container already exists."
end
LXC.run("clone", "-o", name, "-n", target)
LXC.container(target)
end | Clone to a new container from self
@param [String] target name of new container
@return [LXC::Container] new container instance | train | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/container.rb#L187-L196 | class Container
attr_accessor :name
# Initialize a new LXC::Container instance
# @param [String] name container name
# @return [LXC::Container] container instance
def initialize(name)
@name = name
end
# Get container attributes hash
# @return [Hash]
def to_hash
status.to_hash.merge("name" => name)
end
# Get current status of container
# @return [Hash] hash with :state and :pid attributes
def status
output = run("info")
result = output.scan(/^state:\s+([\w]+)|pid:\s+(-?[\d]+)$/).flatten
LXC::Status.new(result.first, result.last)
end
# Get state of the container
# @return [String]
def state
status.state
end
# Get PID of the container
# @return [Integer]
def pid
status.pid
end
# Check if container exists
# @return [Boolean]
def exists?
LXC.run("ls").split("\n").uniq.include?(name)
end
# Check if container is running
# @return [Boolean]
def running?
status.state == "running"
end
# Check if container is frozen
# @return [Boolean]
def frozen?
status.state == "frozen"
end
# Check if container is stopped
# @return [Boolean]
def stopped?
exists? && status.state == "stopped"
end
# Start container
# @return [Hash] container status hash
def start
run("start", "-d")
status
end
# Stop container
# @return [Hash] container status hash
def stop
run("stop")
status
end
# Restart container
# @return [Hash] container status hash
def restart
stop ; start
status
end
# Freeze container
# @return [Hash] container status hash
def freeze
run("freeze")
status
end
# Unfreeze container
# @return [Hash] container status hash
def unfreeze
run("unfreeze")
status
end
# Wait for container to change status
# @param [String] state name
def wait(state)
if !LXC::Shell.valid_state?(status.state)
raise ArgumentError, "Invalid container state: #{state}"
end
run("wait", "-s", state)
end
# Get container memory usage in bytes
# @return [Integer]
def memory_usage
run("cgroup", "memory.usage_in_bytes").strip.to_i
end
# Get container memory limit in bytes
# @return [Integer]
def memory_limit
run("cgroup", "memory.limit_in_bytes").strip.to_i
end
# Get container cpu shares
# @return [Integer]
def cpu_shares
result = run("cgroup", "cpu.shares").to_s.strip
result.empty? ? nil : result.to_i
end
# Get container cpu usage in seconds
# @return [Float]
def cpu_usage
result = run("cgroup", "cpuacct.usage").to_s.strip
result.empty? ? nil : Float("%.4f" % (result.to_i / 1E9))
end
# Get container processes
# @return [Array] list of all processes
def processes
raise ContainerError, "Container is not running" if !running?
str = run("ps", "--", "-eo pid,user,%cpu,%mem,args").strip
lines = str.split("\n") ; lines.delete_at(0)
lines.map { |l| parse_process_line(l) }
end
# Create a new container
# @param [String] path path to container config file or [Hash] options
# @return [Boolean]
def create(path)
raise ContainerError, "Container already exists." if exists?
if path.is_a?(Hash)
args = "-n #{name}"
if !!path[:config_file]
unless File.exists?(path[:config_file])
raise ArgumentError, "File #{path[:config_file]} does not exist."
end
args += " -f #{path[:config_file]}"
end
if !!path[:template]
template_dir = path[:template_dir] || "/usr/lib/lxc/templates"
template_path = File.join(template_dir,"lxc-#{path[:template]}")
unless File.exists?(template_path)
raise ArgumentError, "Template #{path[:template]} does not exist."
end
args += " -t #{path[:template]} "
end
args += " -B #{path[:backingstore]}" if !!path[:backingstore]
args += " -- #{path[:template_options].join(" ")}".strip if !!path[:template_options]
LXC.run("create", args)
exists?
else
unless File.exists?(path)
raise ArgumentError, "File #{path} does not exist."
end
LXC.run("create", "-n", name, "-f", path)
exists?
end
end
# Clone to a new container from self
# @param [String] target name of new container
# @return [LXC::Container] new container instance
# Create a new container from an existing container
# @param [String] source name of existing container
# @return [Boolean]
def clone_from(source)
raise ContainerError, "Container already exists." if exists?
unless LXC.container(source).exists?
raise ContainerError, "Source container does not exist."
end
run("clone", "-o", source)
exists?
end
# Destroy the container
# @param [Boolean] force force destruction
# @return [Boolean] true if container was destroyed
#
# If container is running and `force` parameter is true
# it will be stopped first. Otherwise it will raise exception.
#
def destroy(force=false)
unless exists?
raise ContainerError, "Container does not exist."
end
if running?
if force == true
stop
else
raise ContainerError, "Container is running. Stop it first or use force=true"
end
end
run("destroy")
!exists?
end
private
def run(command, *args)
LXC.run(command, "-n", name, *args)
end
def parse_process_line(line)
chunks = line.split(" ")
chunks.delete_at(0)
{
"pid" => chunks.shift,
"user" => chunks.shift,
"cpu" => chunks.shift,
"memory" => chunks.shift,
"command" => chunks.shift,
"args" => chunks.join(" ")
}
end
end
|
charypar/cyclical | lib/cyclical/rules/monthly_rule.rb | Cyclical.MonthlyRule.aligned? | ruby | def aligned?(time, base)
return false unless ((12 * base.year + base.mon) - (12 * time.year + time.mon)) % @interval == 0
return false unless [time.hour, time.min, time.sec] == [base.hour, base.min, base.sec] # the shortest filter we support is for days
return false unless base.day == time.day || monthday_filters
true
end | check if time is aligned to a base time, including interval check | train | https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/rules/monthly_rule.rb#L8-L14 | class MonthlyRule < Rule
# check if time is aligned to a base time, including interval check
# default step of the rule
def step
@interval.months
end
protected
def potential_next(current, base)
candidate = super(current, base)
rem = ((12 * base.year + base.mon) - (12 * candidate.year + candidate.mon)) % @interval
return candidate if rem == 0
(candidate + rem.months).beginning_of_month
end
def potential_previous(current, base)
candidate = super(current, base)
rem = ((12 * base.year + base.mon) - (12 * candidate.year + candidate.mon)) % @interval
return candidate if rem == 0
(candidate + rem.months - step).end_of_month
end
def align(time, base)
time = time.beginning_of_month + (base.day - 1).days unless time.day == base.day || monthday_filters
# compensate crossing DST barrier (oh my...)
offset = time.beginning_of_day.utc_offset
time = time.beginning_of_day + base.hour.hours + base.min.minutes + base.sec.seconds
time += (offset - time.utc_offset)
time
end
def monthday_filters
filters(:weekdays) || filters(:monthdays) || filters(:yeardays) || filters(:weeks) || filters(:months)
end
end
|
altabyte/ebay_trader | lib/ebay_trader/xml_builder.rb | EbayTrader.XMLBuilder.node | ruby | def node(name, args, &block)
content = get_node_content(args)
options = format_node_attributes(get_node_attributes(args))
@_segments ||= []
@_segments << "#{indent_new_line}<#{name}#{options}>#{content}"
if block_given?
@depth += 1
instance_eval(&block)
@depth -= 1
@_segments << indent_new_line
end
@_segments << "</#{name}>"
@xml = @_segments.join('').strip
end | Create an XML node
@param [String|Symbol] name the name of the XML element (ul, li, strong, etc...)
@param [Array] args Can contain a String of text or a Hash of attributes
@param [Block] block An optional block which will further nest XML | train | https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L54-L68 | class XMLBuilder
attr_reader :context, :xml, :depth, :tab_width
def initialize(args = {})
@xml = ''
@depth = 0
@tab_width = (args[:tab_width] || 0).to_i
end
# Catch-all method to avoid having to create individual methods for each XML tag name.
def method_missing(method_name, *args, &block)
if @context && @context.respond_to?(method_name)
@context.send(method_name, *args, &block)
else
node(method_name, args, &block)
end
end
# Only respond to method names with only numbers and letters.
# Do not respond to names with underscores.
def respond_to_missing?(method_name, include_private = false)
super || method_name.to_s =~ /^[a-z0-9]+$/i
end
# Begin creating an XML string by specifying the root node.
# This also sets the context scope, allowing methods and variables
# outside the block to be accessed.
# @param [String] name the name of the root node element.
# @param [Array] args the data for this element.
# @param [Block] block an optional block of sub-elements to be nested
# within the root node.
def root(name, *args, &block)
set_context(&block)
node(name, args, &block)
end
#---------------------------------------------------------------------------
private
# @see https://github.com/sparklemotion/nokogiri/blob/master/lib/nokogiri/xml/builder.rb
def set_context(&block)
@context = block_given? ? eval('self', block.binding) : nil
@context = nil if @context.is_a?(XMLBuilder)
end
# Create an XML node
# @param [String|Symbol] name the name of the XML element (ul, li, strong, etc...)
# @param [Array] args Can contain a String of text or a Hash of attributes
# @param [Block] block An optional block which will further nest XML
# Return the first Hash in the list of arguments to #node
# as this defines the attributes for the XML node.
# @return [Hash] the hash of attributes for this node.
#
def get_node_attributes(args)
args.detect { |arg| arg.is_a? Hash } || {}
end
# Return the node content as a String, unless a block is given.
# @return [String] the node data.
#
def get_node_content(args)
return nil if block_given?
content = nil
args.each do |arg|
case arg
when Hash
next
when Time
# eBay official TimeStamp format YYYY-MM-DDTHH:MM:SS.SSSZ
content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z')
when DateTime
content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z')
break
else
content = arg.to_s
break
end
end
content
end
# Convert the given Hash of options into a string of XML element attributes.
#
def format_node_attributes(options)
options.collect { |key, value|
value = value.to_s.gsub('"', '\"')
" #{key}=\"#{value}\""
}.join('')
end
# Add a new line to the XML and indent with the appropriate number of spaces.
def indent_new_line
tab_width > 0 ? ("\n" + (' ' * tab_width * depth)) : ''
end
end
|
couchrest/couchrest_extended_document | lib/couchrest/extended_document.rb | CouchRest.ExtendedDocument.destroy | ruby | def destroy(bulk=false)
caught = catch(:halt) do
_run_destroy_callbacks do
result = database.delete_doc(self, bulk)
if result['ok']
self.delete('_rev')
self.delete('_id')
end
result['ok']
end
end
end | Deletes the document from the database. Runs the :destroy callbacks.
Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
document to be saved to a new <tt>_id</tt>. | train | https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/extended_document.rb#L247-L258 | class ExtendedDocument < Document
VERSION = "1.0.0"
include CouchRest::Mixins::Callbacks
include CouchRest::Mixins::DocumentQueries
include CouchRest::Mixins::Views
include CouchRest::Mixins::DesignDoc
include CouchRest::Mixins::ExtendedAttachments
include CouchRest::Mixins::ClassProxy
include CouchRest::Mixins::Collection
include CouchRest::Mixins::AttributeProtection
include CouchRest::Mixins::Attributes
# Including validation here does not work due to the way inheritance is handled.
#include CouchRest::Validation
def self.subclasses
@subclasses ||= []
end
def self.inherited(subklass)
super
subklass.send(:include, CouchRest::Mixins::Properties)
subklass.class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.inherited(subklass)
super
subklass.properties = self.properties.dup
end
EOS
subclasses << subklass
end
# Accessors
attr_accessor :casted_by
# Callbacks
define_callbacks :create, "result == :halt"
define_callbacks :save, "result == :halt"
define_callbacks :update, "result == :halt"
define_callbacks :destroy, "result == :halt"
# Creates a new instance, bypassing attribute protection
#
#
# ==== Returns
# a document instance
def self.create_from_database(doc = {})
base = (doc['couchrest-type'].blank? || doc['couchrest-type'] == self.to_s) ? self : doc['couchrest-type'].constantize
base.new(doc, :directly_set_attributes => true)
end
# Instantiate a new ExtendedDocument by preparing all properties
# using the provided document hash.
#
# Options supported:
#
# * :directly_set_attributes: true when data comes directly from database
#
def initialize(doc = {}, options = {})
prepare_all_attributes(doc, options) # defined in CouchRest::Mixins::Attributes
super(doc)
unless self['_id'] && self['_rev']
self['couchrest-type'] = self.class.to_s
end
after_initialize if respond_to?(:after_initialize)
end
# Defines an instance and save it directly to the database
#
# ==== Returns
# returns the reloaded document
def self.create(options)
instance = new(options)
instance.create
instance
end
# Defines an instance and save it directly to the database
#
# ==== Returns
# returns the reloaded document or raises an exception
def self.create!(options)
instance = new(options)
instance.create!
instance
end
# Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
# on the document whenever saving occurs. CouchRest uses a pretty
# decent time format by default. See Time#to_json
def self.timestamps!
class_eval <<-EOS, __FILE__, __LINE__
property(:updated_at, Time, :read_only => true, :protected => true, :auto_validation => false)
property(:created_at, Time, :read_only => true, :protected => true, :auto_validation => false)
set_callback :save, :before do |object|
write_attribute('updated_at', Time.now)
write_attribute('created_at', Time.now) if object.new?
end
EOS
end
# Name a method that will be called before the document is first saved,
# which returns a string to be used for the document's <tt>_id</tt>.
# Because CouchDB enforces a constraint that each id must be unique,
# this can be used to enforce eg: uniq usernames. Note that this id
# must be globally unique across all document types which share a
# database, so if you'd like to scope uniqueness to this class, you
# should use the class name as part of the unique id.
def self.unique_id method = nil, &block
if method
define_method :set_unique_id do
self['_id'] ||= self.send(method)
end
elsif block
define_method :set_unique_id do
uniqid = block.call(self)
raise ArgumentError, "unique_id block must not return nil" if uniqid.nil?
self['_id'] ||= uniqid
end
end
end
# Temp solution to make the view_by methods available
def self.method_missing(m, *args, &block)
if has_view?(m)
query = args.shift || {}
return view(m, query, *args, &block)
elsif m.to_s =~ /^find_(by_.+)/
view_name = $1
if has_view?(view_name)
query = {:key => args.first, :limit => 1}
return view(view_name, query).first
end
end
super
end
### instance methods
# Gets a reference to the actual document in the DB
# Calls up to the next document if there is one,
# Otherwise we're at the top and we return self
def base_doc
return self if base_doc?
@casted_by.base_doc
end
# Checks if we're the top document
def base_doc?
!@casted_by
end
# for compatibility with old-school frameworks
alias :new_record? :new?
alias :new_document? :new?
# Trigger the callbacks (before, after, around)
# and create the document
# It's important to have a create callback since you can't check if a document
# was new after you saved it
#
# When creating a document, both the create and the save callbacks will be triggered.
def create(bulk = false)
caught = catch(:halt) do
_run_create_callbacks do
_run_save_callbacks do
create_without_callbacks(bulk)
end
end
end
end
# unlike save, create returns the newly created document
def create_without_callbacks(bulk =false)
raise ArgumentError, "a document requires a database to be created to (The document or the #{self.class} default database were not set)" unless database
set_unique_id if new? && self.respond_to?(:set_unique_id)
result = database.save_doc(self, bulk)
(result["ok"] == true) ? self : false
end
# Creates the document in the db. Raises an exception
# if the document is not created properly.
def create!
raise "#{self.inspect} failed to save" unless self.create
end
# Trigger the callbacks (before, after, around)
# only if the document isn't new
def update(bulk = false)
caught = catch(:halt) do
if self.new?
save(bulk)
else
_run_update_callbacks do
_run_save_callbacks do
save_without_callbacks(bulk)
end
end
end
end
end
# Trigger the callbacks (before, after, around)
# and save the document
def save(bulk = false)
caught = catch(:halt) do
if self.new?
_run_save_callbacks do
save_without_callbacks(bulk)
end
else
update(bulk)
end
end
end
# Overridden to set the unique ID.
# Returns a boolean value
def save_without_callbacks(bulk = false)
raise ArgumentError, "a document requires a database to be saved to (The document or the #{self.class} default database were not set)" unless database
set_unique_id if new? && self.respond_to?(:set_unique_id)
result = database.save_doc(self, bulk)
result["ok"] == true
end
# Saves the document to the db using save. Raises an exception
# if the document is not saved properly.
def save!
raise "#{self.inspect} failed to save" unless self.save
true
end
# Deletes the document from the database. Runs the :destroy callbacks.
# Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
# document to be saved to a new <tt>_id</tt>.
end
|
rjoberon/bibsonomy-ruby | lib/bibsonomy/api.rb | BibSonomy.API.get_post | ruby | def get_post(user_name, intra_hash)
response = @conn.get @url_post.expand({
:user_name => user_name,
:intra_hash => intra_hash,
:format => @format
})
if @parse
attributes = JSON.parse(response.body)
return Post.new(attributes["post"])
end
return response.body
end | Initializes the client with the given credentials.
@param user_name [String] the name of the user account used for accessing the API
@param api_key [String] the API key corresponding to the user account - can be obtained from http://www.bibsonomy.org/settings?selTab=1
@param format [String] The requested return format. One of:
'xml', 'json', 'ruby', 'csl', 'bibtex'. The default is 'ruby'
which returns Ruby objects defined by this library. Currently,
'csl' and 'bibtex' are only available for publications.
Get a single post
@param user_name [String] the name of the post's owner
@param intra_hash [String] the intrag hash of the post
@return [BibSonomy::Post, String] the requested post | train | https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L78-L90 | class API
# Initializes the client with the given credentials.
#
# @param user_name [String] the name of the user account used for accessing the API
# @param api_key [String] the API key corresponding to the user account - can be obtained from http://www.bibsonomy.org/settings?selTab=1
#
# @param format [String] The requested return format. One of:
# 'xml', 'json', 'ruby', 'csl', 'bibtex'. The default is 'ruby'
# which returns Ruby objects defined by this library. Currently,
# 'csl' and 'bibtex' are only available for publications.
#
def initialize(user_name, api_key, format = 'ruby')
# configure output format
if format == 'ruby'
@format = 'json'
@parse = true
else
@format = format
@parse = false
end
@conn = Faraday.new(:url => $API_URL) do |faraday|
faraday.request :url_encoded # form-encode POST params
#faraday.response :logger
faraday.adapter Faraday.default_adapter # make requests with
# Net::HTTP
end
@conn.basic_auth(user_name, api_key)
# initialise URLs
@url_post = Addressable::Template.new("/api/users/{user_name}/posts/{intra_hash}?format={format}")
@url_posts = Addressable::Template.new("/api/posts{?format,resourcetype,start,end,user,group,tags}")
@url_doc = Addressable::Template.new("/api/users/{user_name}/posts/{intra_hash}/documents/{file_name}")
end
#
# Get a single post
#
# @param user_name [String] the name of the post's owner
# @param intra_hash [String] the intrag hash of the post
# @return [BibSonomy::Post, String] the requested post
#
# Get posts owned by a user, optionally filtered by tags.
#
# @param user_name [String] the name of the posts' owner
# @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'.
# @param tags [Array<String>] the tags that all posts must contain (can be empty)
# @param start [Integer] number of first post to download
# @param endc [Integer] number of last post to download
# @return [Array<BibSonomy::Post>, String] the requested posts
def get_posts_for_user(user_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST)
return get_posts("user", user_name, resource_type, tags, start, endc)
end
#
# Get the posts of the users of a group, optionally filtered by tags.
#
# @param group_name [String] the name of the group
# @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'.
# @param tags [Array<String>] the tags that all posts must contain (can be empty)
# @param start [Integer] number of first post to download
# @param endc [Integer] number of last post to download
# @return [Array<BibSonomy::Post>, String] the requested posts
def get_posts_for_group(group_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST)
return get_posts("group", group_name, resource_type, tags, start, endc)
end
#
# Get posts for a user or group, optionally filtered by tags.
#
# @param grouping [String] the type of the name (either "user" or "group")
# @param name [String] the name of the group or user
# @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'.
# @param tags [Array<String>] the tags that all posts must contain (can be empty)
# @param start [Integer] number of first post to download
# @param endc [Integer] number of last post to download
# @return [Array<BibSonomy::Post>, String] the requested posts
def get_posts(grouping, name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST)
url = @url_posts.partial_expand({
:format => @format,
:resourcetype => get_resource_type(resource_type),
:start => start,
:end => endc
})
# decide what to get
if grouping == "user"
url = url.partial_expand({:user => name})
elsif grouping == "group"
url = url.partial_expand({:group => name})
end
# add tags, if requested
if tags != nil
url = url.partial_expand({:tags => tags.join(" ")})
end
response = @conn.get url.expand({})
if @parse
posts = JSON.parse(response.body)["posts"]["post"]
return posts.map { |attributes| Post.new(attributes) }
end
return response.body
end
def get_document_href(user_name, intra_hash, file_name)
return @url_doc.expand({
:user_name => user_name,
:intra_hash => intra_hash,
:file_name => file_name
})
end
#
# Get a document belonging to a post.
#
# @param user_name
# @param intra_hash
# @param file_name
# @return the document and the content type
def get_document(user_name, intra_hash, file_name)
response = @conn.get get_document_href(user_name, intra_hash, file_name)
if response.status == 200
return [response.body, response.headers['content-type']]
end
return nil, nil
end
#
# Get the preview for a document belonging to a post.
#
# @param user_name
# @param intra_hash
# @param file_name
# @param size [String] requested preview size (allowed values: SMALL, MEDIUM, LARGE)
# @return the preview image and the content type `image/jpeg`
def get_document_preview(user_name, intra_hash, file_name, size)
response = @conn.get get_document_href(user_name, intra_hash, file_name), { :preview => size }
if response.status == 200
return [response.body, 'image/jpeg']
end
return nil, nil
end
private
#
# Convenience method to allow sloppy specification of the resource
# type.
#
def get_resource_type(resource_type)
if $resource_types_bookmark.include? resource_type.downcase()
return "bookmark"
end
if $resource_types_bibtex.include? resource_type.downcase()
return "bibtex"
end
raise ArgumentError.new("Unknown resource type: #{resource_type}. Supported resource types are ")
end
end
|