Module: Dynflow::Utils

Defined in:
lib/dynflow/utils.rb,
lib/dynflow/utils/priority_queue.rb,
lib/dynflow/utils/indifferent_hash.rb

Defined Under Namespace

Classes: IndifferentHash, PriorityQueue

Class Method Summary collapse

Class Method Details

.constantize(string) ⇒ Object

Inspired by ActiveSupport::Inflector



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
# File 'lib/dynflow/utils.rb', line 33

def self.constantize(string)
  return string.constantize if string.respond_to?(:constantize)

  names = string.split('::')

  # Trigger a built-in NameError exception including the ill-formed constant in the message.
  Object.const_get(string) if names.empty?

  # Remove the first blank element in case of '::ClassName' notation.
  names.shift if names.size > 1 && names.first.empty?

  names.inject(Object) do |constant, name|
    if constant == Object
      constant.const_get(name)
    else
      candidate = constant.const_get(name)
      next candidate if constant.const_defined?(name, false)
      next candidate unless Object.const_defined?(name)

      # Go down the ancestors to check if it is owned directly. The check
      # stops when we reach Object or the end of ancestors tree.
      constant = constant.ancestors.inject do |const, ancestor|
        break const    if ancestor == Object
        break ancestor if ancestor.const_defined?(name, false)
        const
      end

      # owner is in Object, so raise
      constant.const_get(name, false)
    end
  end
end

.indifferent_hash(hash) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/dynflow/utils.rb', line 66

def self.indifferent_hash(hash)
  if defined? ::HashWithIndifferentAccess
    # the users already have it: lets give them what they are used to
    ::HashWithIndifferentAccess.new(hash)
  else
    if hash.is_a? IndifferentHash
      return hash
    else
      IndifferentHash.new(hash)
    end
  end
end

.stringify_keys(hash) ⇒ Object



25
26
27
28
29
30
# File 'lib/dynflow/utils.rb', line 25

def self.stringify_keys(hash)
  return hash.stringify_keys if hash.respond_to?(:stringify_keys)
  hash.reduce({}) do |new_hash, (key, value)|
    new_hash.update(key.to_s => value)
  end
end

.symbolize_keys(hash) ⇒ Object



18
19
20
21
22
23
# File 'lib/dynflow/utils.rb', line 18

def self.symbolize_keys(hash)
  return hash.symbolize_keys if hash.respond_to?(:symbolize_keys)
  hash.reduce({}) do |new_hash, (key, value)|
    new_hash.update(key.to_sym => value)
  end
end

.validate_keys!(hash, *valid_keys) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/dynflow/utils.rb', line 8

def self.validate_keys!(hash, *valid_keys)
  valid_keys.flatten!
  unexpected_options = hash.keys - valid_keys - valid_keys.map(&:to_s)
  unless unexpected_options.empty?
    raise ArgumentError, "Unexpected options #{unexpected_options.inspect}. "\
        "Valid keys are: #{valid_keys.map(&:inspect).join(', ')}"
  end
  hash
end