Module: Alias::Util

Extended by:
Util
Included in:
Util
Defined in:
lib/alias/util.rb

Overview

A collection of utility functions used throughout.

Instance Method Summary collapse

Instance Method Details

#any_const_get(name) ⇒ Object



29
30
31
# File 'lib/alias/util.rb', line 29

def any_const_get(name)
  Util.const_cache[name] ||= Util.uncached_any_const_get(name)
end

#camelize(string) ⇒ Object

simplified version from ActiveSupport



50
51
52
# File 'lib/alias/util.rb', line 50

def camelize(string)
  string.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
end

#const_cacheObject



33
34
35
# File 'lib/alias/util.rb', line 33

def const_cache
  @const_cache ||= {}
end

#make_shortest_aliases(unaliased_strings) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/alias/util.rb', line 63

def make_shortest_aliases(unaliased_strings)
  shortest_aliases = {}
  possible_alias = ''
  unaliased_strings.each {|s|
    possible_alias = ''
    s.split('').each { |e|
      possible_alias += e
      if ! shortest_aliases.values.include?(possible_alias)
        shortest_aliases[s] = possible_alias
        break
      end
    }
  }
  shortest_aliases
end

#recursive_hash_merge(hash1, hash2) ⇒ Object

Recursively merge hash1 with hash2.



25
26
27
# File 'lib/alias/util.rb', line 25

def recursive_hash_merge(hash1, hash2)
  hash1.merge(hash2) {|k,o,n| (o.is_a?(Hash)) ? recursive_hash_merge(o,n) : n}
end

#silence_warningsObject



79
80
81
82
83
84
# File 'lib/alias/util.rb', line 79

def silence_warnings
  old_verbose, $VERBOSE = $VERBOSE, nil
  yield
ensure
  $VERBOSE = old_verbose
end

#slice(hash, *keys) ⇒ Object

simplified from ActiveSupport



6
7
8
# File 'lib/alias/util.rb', line 6

def slice(hash, *keys)
  hash.reject {|key,| !keys.include?(key) }
end

#slice_off!(hash, *keys) ⇒ Object

:nod



10
11
12
13
14
# File 'lib/alias/util.rb', line 10

def slice_off!(hash, *keys) #:nod
  new_hash = slice(hash,*keys)
  keys.each {|e| hash.delete(e)}
  new_hash
end

#symbolize_keys(hash) ⇒ Object

from ActiveSupport



17
18
19
20
21
22
# File 'lib/alias/util.rb', line 17

def symbolize_keys(hash)
  hash.inject({}) do |options, (key, value)|
    options[key.to_sym] = value
    options
  end
end

#uncached_any_const_get(name) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/alias/util.rb', line 37

def uncached_any_const_get(name)
  begin
    klass = Object
    name.split('::').each {|e|
      klass = klass.const_get(e)
    }
    klass
  rescue
    nil
  end
end

#underscore(camel_cased_word) ⇒ Object

from ActiveSupport



55
56
57
58
59
60
61
# File 'lib/alias/util.rb', line 55

def underscore(camel_cased_word)
  camel_cased_word.to_s.gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
end