Module: Kantox::Helpers

Defined in:
lib/kantox/roles/logger.rb,
lib/kantox/roles/helpers.rb

Constant Summary collapse

BACKTRACE_LENGTH =
12
SEV_COLORS =
{
  'INFO'    => ['01;38;05;21', '00;38;05;152'],
  'WARN'    => ['01;38;05;226', '00;38;05;222'],
  'ERROR'   => ['01;38;05;196', '01;38;05;174'],
  'DEBUG'   => ['01;38;05;242', '00;38;05;246'],
  'ANY'     => ['01;38;05;222;48;05;238', '01;38;05;253;48;05;238']
}
SEV_SYMBOLS =
{
  'INFO'    => '',
  'WARN'    => '',
  'ERROR'   => '',
  'DEBUG'   => '',
  'ANY'     => ''
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.catched(message, e) ⇒ Object



82
83
84
85
86
87
88
# File 'lib/kantox/roles/logger.rb', line 82

def catched message, e
  bt = e.backtrace.is_a?(Array) ? e.backtrace : caller(1)
  msg = "#{message}\nOriginal exception «#{e.class}»: #{e.message}\n" \
       "Stacktrace: #{bt.take(BACKTRACE_LENGTH).join($/)}\n" \
       "[...#{bt.length - BACKTRACE_LENGTH} more]"
  warn msg
end

.clrz(txt, clr) ⇒ Object



32
33
34
35
36
# File 'lib/kantox/roles/logger.rb', line 32

def self.clrz txt, clr
  return txt unless @tty

  "\e[#{clr}m#{txt.gsub(/«(.*?)»/, "\e[01;38;05;51m\\1\e[#{clr}m")}\e[0m"
end

.errObject



99
# File 'lib/kantox/roles/logger.rb', line 99

alias_method :err, :error

.fake_array(array) ⇒ Object



25
26
27
# File 'lib/kantox/roles/helpers.rb', line 25

def fake_array array
  array.zip(fake_data(array, false).values).to_h
end

.fake_data(hash_or_array_or_json, deep = true) ⇒ Hash

Fakes hash values

Parameters:

  • hash (Hash)

    to fake

Returns:

  • (Hash)

    faked hash



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/kantox/roles/helpers.rb', line 6

def fake_data hash_or_array_or_json, deep = true
  (hash_or_array_or_json.is_a?(String) ? JSON.parse(hash_or_array_or_json) : hash_or_array_or_json).each_with_index.map do |kv, index|
    case kv
    when Array # we iterate hash
      [ kv.first.respond_to?(:to_sym) ? kv.first.to_sym : kv.first,
        deep ?  case kv.last
                when Array then fake_data(kv.last).values
                when Hash then fake_hash kv.last
                else Kantox::LOCK_EMOJI
                end
             : Kantox::LOCK_EMOJI
      ]
    else [index, Kantox::LOCK_EMOJI]
    end
  end.to_h
end

.fake_hash(hash_or_array_or_json, deep = true) ⇒ Object



22
23
24
# File 'lib/kantox/roles/helpers.rb', line 22

def fake_hash hash_or_array_or_json, deep = true
  fake_data(hash_or_array_or_json, deep).merge({ Kantox::LOCK_EMOJI => true })
end

.get_instance_method(name) ⇒ Hash|nil

Returns class, method and parameters as s string.

Returns:

  • (Hash|nil)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/kantox/roles/helpers.rb', line 33

def get_instance_method name
  k, m = name.split('#')

  unless Kernel.const_defined? k
    Kantox::Helpers.debug "Bad handler: «#{k}##{m}» not found. Error message: “#{e}”.\nUsually it’s OK meaning that the respective class is not yet initialized."
    return nil
  end

  klazz = Kernel.const_get(k)

  meth = (
    klazz.private_method_defined?(m) ||
    klazz.protected_method_defined?(m) ||
    klazz.public_method_defined?(m)
  ) && klazz.instance_method(m)

  unless meth
    Kantox::Helpers.err "Class [#{klazz}] has no instance method [#{m}]."
    return nil
  end

  params_arr = meth.parameters
  params_str = [
    params_arr.select { |tv| tv.first == :req }.map(&:last).map(&:to_s),
    params_arr.select { |tv| tv.first == :rest }.map(&:last).map { |m| "*#{m}"},
    params_arr.select { |tv| tv.first == :block }.map(&:last).map { |m| "&#{m}"}
  ].flatten.join(', ')

  Hashie::Mash.new(
    class: klazz,
    method: { name: m, instance: meth },
    params: { string: params_str }
  )
end

.log(message) ⇒ Object



77
78
79
80
# File 'lib/kantox/roles/logger.rb', line 77

def log message
  logger.unknown { message }
  nil
end

.loggerObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/kantox/roles/logger.rb', line 38

def logger
  unless @logger
    @logger, @logdevice = if Kernel.const_defined? 'Rails'
                            [
                              ::Rails.logger,
                              ::Rails.logger
                                     .instance_variable_get(:@logger)
                                     .instance_variable_get(:@log)
                            ]
                          else
                            l = Logger.new($stdout)
                            [l, l]
                          end
    @tty = @logdevice.instance_variable_get(:@logdev).instance_variable_get(:@dev).tty? ||
           Kernel.const_defined?('Rails') && ::Rails.env.development?

    unless Kernel.const_defined?('Rails') && ::Rails.env.production? || ENV['RAILS_PRETTY_LOG'] != '42'
      @logdevice.formatter = proc { |severity, datetime, progname, message|
        message = message.join($/) if message[0] == '[' && message[-1] == ']' && (arr_msg = JSON.parse(message)).is_a?(Array) rescue message

        message.strip!                       # strip
        message.gsub! "\n", "\n⮩#{' ' * 29}" # align
        if message.empty? || @stopwords.any? { |sw| sw =~ message }
          nil
        else
        '' << clrz("#{SEV_SYMBOLS[severity]} ", SEV_COLORS[severity].first)\
           << clrz(severity[0..2], SEV_COLORS[severity].first)             \
           << ' | '                                                        \
           << clrz(datetime.strftime('%Y%m%d-%H%M%S.%3N'), '01;38;05;238') \
           << ' | '                                                        \
           << clrz(message, SEV_COLORS[severity].last)                     \
           << "\n"
        end
      }
    end
  end
  @logger
end

.logger_stopwords(file) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/kantox/roles/logger.rb', line 23

def logger_stopwords file
  if File.exist?(file)
    @stopwords += File.read(file).split($/).map { |l| Regexp.new l }
  else
    Kantox::Helpers.warn "Bad stopwords file: [#{file}]."
  end
end

.merge_hash_or_string(mash, hos) ⇒ Object

Parameters:

  • mash (Hash|Hashie::Mash|NilClass)

    hash to merge ‘hos` into

  • hos (Hash|Hashie::Mash|String)

    the new values taken from hash, mash or string (when string, should be either valid YAML file name or string with valid YAML)



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/kantox/roles/helpers.rb', line 72

def merge_hash_or_string mash, hos
  case mash
  when Hashie::Mash then mash
  when Hash then Hashie::Mash.new(mash)
  when NilClass then Hashie::Mash.new
  else
    fail ArgumentError.new "#{__callee__} expects [Hash|Hashie::Mash|NilClass] as first parameter"
  end.deep_merge  case hos
                  when NilClass then {} # aka skip
                  when Hash then hos
                  when String
                    begin
                      File.exists?(hos) ? Hashie::Mash.load(hos) : Hashie::Mash.new(YAML.load(hos))
                    rescue ArgumentError => ae
                      fail ArgumentError.new "#{__callee__} expects valid YAML configuration file. [#{hos}] contains invalid syntax."
                    rescue Psych::SyntaxError => pse
                      fail ArgumentError.new "#{__callee__} expects valid YAML configuration string. Got:\n#{hos}"
                    end
                  else
                    Kantox::Helpers.warn 'Kantox::Roles#configure accepts either String or Hash as parameter.'
                  end
end

Instance Method Details

#get_lambda_strategy(lmbd) ⇒ Proc

Returns:

  • (Proc)


107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/kantox/roles/helpers.rb', line 107

def get_lambda_strategy lmbd
  begin
    eval(lmbd)
  rescue LocalJumpError => lje
    Kantox::Helpers.err "Lambda strategy failed: «return» is not allowed from this lambda.\n#{lmbd}\nOriginal error: #{lje}"
  rescue NameError => ne
    Kantox::Helpers.err "Lambda strategy failed: syntax error in lambda.\n#{lmbd}\nOriginal error: #{ne}"
  rescue SyntaxError => se
    Kantox::Helpers.err "Lambda strategy failed: syntax error in lambda.\n#{lmbd}\nOriginal error: #{se}"
  rescue RuntimeError => re
    Kantox::Helpers.err "Lambda strategy failed: undetermined error in lambda.\n#{lmbd}\nOriginal error: #{re}"
  end
end

#get_object_strategy(name, mash) ⇒ Object

Returns:

  • (Object)


122
123
124
125
126
127
128
# File 'lib/kantox/roles/helpers.rb', line 122

def get_object_strategy name, mash
  klazz = name.split('_').map { |n| n.capitalize }.join('::')
  return nil unless Module.const_defined?(klazz)
  klazz = Module.const_get(klazz)
  return nil unless klazz.is_a?(Class) && klazz.instance_methods(false).include?(:to_proc)
  klazz.new(mash)
end

#get_runner_strategy(name) ⇒ Method|nil

Returns:

  • (Method|nil)


96
97
98
99
# File 'lib/kantox/roles/helpers.rb', line 96

def get_runner_strategy name
  im = get_instance_method(name)
  im.nil? ? im : im[:method][:instance].bind(im[:class])
end

#get_simple_strategy(name) ⇒ Method|nil

Returns:

  • (Method|nil)


102
103
104
# File 'lib/kantox/roles/helpers.rb', line 102

def get_simple_strategy name
  get_runner_strategy("Kantox::Strategies##{name}")
end