module Croesus::Utils

Private Class Methods

included(base) click to toggle source
# File lib/croesus/utils.rb, line 24
def self.included(base)
  base.extend(ClassMethods)
end

Public Instance Methods

callable(call_her) click to toggle source
# File lib/croesus/utils.rb, line 98
def callable(call_her)
  call_her.respond_to?(:call) ? call_her : lambda { call_her }
end
caller_name() click to toggle source
# File lib/croesus/utils.rb, line 114
def caller_name
  caller_locations(2, 1).first.label
end
camelize(underscored_word) click to toggle source
# File lib/croesus/utils.rb, line 102
def camelize(underscored_word)
  underscored_word.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }
end
class_name() click to toggle source
# File lib/croesus/utils.rb, line 110
def class_name
  demodulize(self.class)
end
classify(table_name) click to toggle source
# File lib/croesus/utils.rb, line 106
def classify(table_name)
  camelize singularize(table_name.to_s.sub(/.*\./, ''))
end
command_in_path?(command) click to toggle source

Checks in PATH returns true if the command is found

# File lib/croesus/utils.rb, line 189
def command_in_path?(command)
  found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p|
    File.exist?(File.join(p, command))
  end
  found.include?(true)
end
demodulize(class_name_in_module) click to toggle source
# File lib/croesus/utils.rb, line 118
def demodulize(class_name_in_module)
  class_name_in_module.to_s.sub(/^.*::/, '')
end
pluralize(word) click to toggle source
# File lib/croesus/utils.rb, line 122
def pluralize(word)
  word.to_s.sub(/([^s])$/, '\1s')
end
request_id() click to toggle source
# File lib/croesus/utils.rb, line 147
def request_id
  SecureRandom.uuid
end
retrier(opts = {}) { |retries, retry_exception| ... } click to toggle source

Runs a code block, and retries it when an exception occurs. Should the number of retries be reached without success, the last exception will be raised.

@param opts [Hash{Symbol => Value}] @option opts [Fixnum] :tries

number of attempts to retry before raising the last exception

@option opts [Fixnum] :sleep

number of seconds to wait between retries, use lambda to exponentially
increasing delay between retries

@option opts [Array(Exception)] :on

the type of exception(s) to catch and retry on

@option opts [Regex] :matching

match based on the exception message

@option opts [Block] :ensure

ensure a block of code is executed, regardless of whether an exception
is raised

@return [Block]

# File lib/croesus/utils.rb, line 216
def retrier(opts = {}, &block)
  defaults = {
    tries:    2,
    sleep:    1,
    on:       StandardError,
    matching: /.*/,
    :ensure => Proc.new {}
  }

  check_for_invalid_options(opts, defaults)
  defaults.merge!(opts)

  return if defaults[:tries] == 0

  on_exception, tries = [defaults[:on]].flatten, defaults[:tries]
  retries = 0
  retry_exception = nil

  begin
    yield retries, retry_exception
  rescue *on_exception => exception
    raise unless exception.message =~ defaults[:matching]
    raise if retries+1 >= defaults[:tries]

    # Interrupt Exception could be raised while sleeping
    begin
      sleep defaults[:sleep].respond_to?(:call) ?
        defaults[:sleep].call(retries) : defaults[:sleep]
    rescue *on_exception
    end

    retries += 1
    retry_exception = exception
    retry
  ensure
    defaults[:ensure].call(retries)
  end
end
singularize(word) click to toggle source
# File lib/croesus/utils.rb, line 126
def singularize(word)
  word.to_s.sub(/s$/, '').sub(/ie$/, 'y')
end
terminal_dimensions() click to toggle source

Returns the columns and lines of the current tty.

@return [Integer]

number of columns and lines of tty, returns [0, 0] if no tty is present.

@api public

# File lib/croesus/utils.rb, line 171
def terminal_dimensions
  [0, 0] unless  STDOUT.tty?
  [80, 40] if OS.windows?

  if ENV['COLUMNS'] && ENV['LINES']
    [ENV['COLUMNS'].to_i, ENV['LINES'].to_i]
  elsif ENV['TERM'] && command_in_path?('tput')
    [`tput cols`.to_i, `tput lines`.to_i]
  elsif command_in_path?('stty')
    `stty size`.scan(/\d+/).map {|s| s.to_i }
  else
    [0, 0]
  end
rescue
  [0, 0]
end
twenty_four_hours_ago() click to toggle source
# File lib/croesus/utils.rb, line 151
def twenty_four_hours_ago
  Time.now - ( 60 * 60 * 24)
end
underscore(camel_cased_word) click to toggle source
# File lib/croesus/utils.rb, line 130
def underscore(camel_cased_word)
  word = camel_cased_word.to_s.dup
  word.gsub!(/::/, '/')
  word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
  word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
  word.tr! '-', '_'
  word.downcase!
  word
end
utc_httpdate() click to toggle source

Return the date and time in “HTTP-date” format as defined by RFC 7231.

@return [Date,Time] in “HTTP-date” format

# File lib/croesus/utils.rb, line 143
def utc_httpdate
  Time.now.utc.httpdate
end
verify_options(accepted, actual) { || ... } click to toggle source
# File lib/croesus/utils.rb, line 155
def verify_options(accepted, actual) # @private
  return unless debug || $DEBUG
  unless (act=Set[*actual.keys]).subset?(acc=Set[*accepted])
    raise Croesus::Errors::UnknownOption,
      "\nDetected unknown option(s): #{(act - acc).to_a.inspect}\n" <<
      "Accepted options are: #{accepted.inspect}"
  end
  yield if block_given?
end