Module: Croesus::Utils

Included in:
Croesus, ModFactory, WebRequest, WebResponse
Defined in:
lib/croesus/utils.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#callable(call_her) ⇒ Object

module ClassMethods



98
99
100
# File 'lib/croesus/utils.rb', line 98

def callable(call_her)
  call_her.respond_to?(:call) ? call_her : lambda { call_her }
end

#caller_nameObject



114
115
116
# File 'lib/croesus/utils.rb', line 114

def caller_name
  caller_locations(2, 1).first.label
end

#camelize(underscored_word) ⇒ Object



102
103
104
# File 'lib/croesus/utils.rb', line 102

def camelize(underscored_word)
  underscored_word.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }
end

#class_nameObject



110
111
112
# File 'lib/croesus/utils.rb', line 110

def class_name
  demodulize(self.class)
end

#classify(table_name) ⇒ Object



106
107
108
# File 'lib/croesus/utils.rb', line 106

def classify(table_name)
  camelize singularize(table_name.to_s.sub(/.*\./, ''))
end

#command_in_path?(command) ⇒ Boolean

Checks in PATH returns true if the command is found

Returns:



189
190
191
192
193
194
# 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) ⇒ Object



118
119
120
# File 'lib/croesus/utils.rb', line 118

def demodulize(class_name_in_module)
  class_name_in_module.to_s.sub(/^.*::/, '')
end

#pluralize(word) ⇒ Object



122
123
124
# File 'lib/croesus/utils.rb', line 122

def pluralize(word)
  word.to_s.sub(/([^s])$/, '\1s')
end

#request_idObject



147
148
149
# File 'lib/croesus/utils.rb', line 147

def request_id
  SecureRandom.uuid
end

#retrier(opts = {}, &block) ⇒ Block

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.

Parameters:

  • opts (Hash{Symbol => Value}) (defaults to: {})

Options Hash (opts):

  • :tries (Fixnum)

    number of attempts to retry before raising the last exception

  • :sleep (Fixnum)

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

  • :on (Array(Exception))

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

  • :matching (Regex)

    match based on the exception message

  • :ensure (Block)

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

Returns:

  • (Block)


216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# 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) ⇒ Object



126
127
128
# File 'lib/croesus/utils.rb', line 126

def singularize(word)
  word.to_s.sub(/s$/, '').sub(/ie$/, 'y')
end

#terminal_dimensionsInteger

Returns the columns and lines of the current tty.

Returns:

  • (Integer)

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



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# 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_agoObject



151
152
153
# File 'lib/croesus/utils.rb', line 151

def twenty_four_hours_ago
  Time.now - ( 60 * 60 * 24)
end

#underscore(camel_cased_word) ⇒ Object



130
131
132
133
134
135
136
137
138
# 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_httpdateDate, Time

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

Returns:

  • (Date, Time)

    in “HTTP-date” format



143
144
145
# File 'lib/croesus/utils.rb', line 143

def utc_httpdate
  Time.now.utc.httpdate
end

#verify_options(accepted, actual) ⇒ Object



155
156
157
158
159
160
161
162
163
# 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