Module: Constantine

Defined in:
lib/constantine.rb,
lib/constantine/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.constantize(word) ⇒ Object



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

def constantize(word)
  modules = []
  variations(split(word)) { |m| modules << m }
  modules.uniq!
  modules.each do |potential_name|
    names = potential_name.split('::')
    names.shift if names.empty? || names.first.empty?
    constant = Object
    names.each do |name|
      constant = constant.const_get(name) if constant.const_defined?(name)
      return constant if constant.name == potential_name
    end
  end
  Object.const_missing(word)
end

.split(word) ⇒ Object



32
33
34
35
36
37
# File 'lib/constantine.rb', line 32

def split(word)
  word = word.dup
  word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1 \2')
  word.gsub!(/([a-z\d])([A-Z])/, '\1 \2')
  word.split(" ")
end

.variations(words, prefix = [], &block) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/constantine.rb', line 23

def variations(words, prefix = [], &block)
  (words.length-1).downto(0).each do |count|
    pre = words[0..count].join("")
    post = words[count+1..words.length-1]
    yield [prefix + [pre], post].reject(&:empty?).join("::")
    variations(post, prefix + [pre], &block)
  end
end