Module: Swarm::Support

Defined in:
lib/swarm/support.rb

Class Method Summary collapse

Class Method Details

.camelize(string) ⇒ Object



54
55
56
57
# File 'lib/swarm/support.rb', line 54

def camelize(string)
  string = string.sub(/^[a-z\d]*/) { $&.capitalize }
  string = string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub('/', '::')
end

.combine_arrays(v1, v2, method: :concat) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/swarm/support.rb', line 29

def combine_arrays(v1, v2, method: :concat)
  case method.to_s
  when "uniq"
    v1 | v2
  when "concat"
    v1.concat v2
  when "override"
    v2
  else
    raise ArgumentError, "unknown array combination method: #{method}"
  end
end

.constantize(string) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/swarm/support.rb', line 59

def constantize(string)
  name_parts = camelize(string).split('::')
  name_parts.shift if name_parts.first.empty?
  constant = Object

  name_parts.each do |name_part|
    const_defined_args = [name_part]
    const_defined_args << false unless Module.method(:const_defined?).arity == 1
    constant_defined = constant.const_defined?(*const_defined_args)
    constant = constant_defined ? constant.const_get(name_part) : constant.const_missing(name_part)
  end
  constant
end

.deep_merge(hsh1, hsh2, combine_arrays: :override) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/swarm/support.rb', line 6

def deep_merge(hsh1, hsh2, combine_arrays: :override)
  hsh1.merge(hsh2) { |key, v1, v2|
    if [v1, v2].all? { |v| v.is_a?(Array) }
      combine_arrays(v1, v2, method: combine_arrays)
    elsif [v1, v2].all? { |v| v.is_a?(Hash) }
      deep_merge(v1, v2)
    else
      v2
    end
  }
end

.slice(hash, *keys) ⇒ Object



73
74
75
76
77
78
79
# File 'lib/swarm/support.rb', line 73

def slice(hash, *keys)
  {}.tap { |h|
    keys.each { |k|
      h[k] = hash[k] if hash.has_key?(k)
    }
  }
end

.symbolize_keys(hsh) ⇒ Object



25
26
27
# File 'lib/swarm/support.rb', line 25

def symbolize_keys(hsh)
  symbolize_keys!(hsh.dup)
end

.symbolize_keys!(hsh) ⇒ Object



18
19
20
21
22
23
# File 'lib/swarm/support.rb', line 18

def symbolize_keys!(hsh)
  hsh.keys.each do |key|
    hsh[key.to_sym] = hsh.delete(key)
  end
  hsh
end

.tokenize(string) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/swarm/support.rb', line 46

def tokenize(string)
  return nil if string.nil?
  string = string.to_s.gsub(/&/, ' and ').
    gsub(/[ \/]+/, '_').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    downcase
end

.uuid_with_timestampObject



42
43
44
# File 'lib/swarm/support.rb', line 42

def uuid_with_timestamp
  "#{Time.now.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.uuid}"
end

.wait_until(timeout: 5, initial_delay: nil) ⇒ Object



81
82
83
84
85
86
# File 'lib/swarm/support.rb', line 81

def wait_until(timeout: 5, initial_delay: nil)
  sleep(initial_delay) if initial_delay.is_a?(Numeric)
  Timeout::timeout(timeout) do
    sleep 0.05 until yield
  end
end