Module: Linecook::Utils

Included in:
Commands::CompileHelper
Defined in:
lib/linecook/utils.rb

Class Method Summary collapse

Class Method Details

.camelize(str) ⇒ Object



18
19
20
# File 'lib/linecook/utils.rb', line 18

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

.constantize(const_name) ⇒ Object

Looks up the specified constant. A block may be given to look up missing constants; the last existing const and any non-existant constant names are yielded to the block, which is expected to return the desired constant. For instance:

module ConstName; end
Constant.constantize('ConstName')                     # => ConstName
Constant.constantize('Non::Existant') { ConstName }   # => ConstName

Raises a NameError for invalid/missing constants.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/linecook/utils.rb', line 40

def constantize(const_name) # :yields: const, missing_const_names
  unless  /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ const_name
    raise NameError, "#{const_name.inspect} is not a valid constant name!"
  end

  const = Object
  constants = $1.split(/::/)

  while name = constants.shift
    begin
      const = const.const_get(name)
    rescue NameError
      raise $! unless block_given?
      constants.unshift(name)
      return yield(const, constants)
    end
  end

  const
end

.deep_merge(a, b) ⇒ Object



5
6
7
8
9
10
11
12
# File 'lib/linecook/utils.rb', line 5

def deep_merge(a, b)
  b.each_pair do |key, current|
    previous = a[key]
    a[key] = deep_merge?(previous, current) ? deep_merge(previous, current) : current
  end

  a
end

.deep_merge?(previous, current) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/linecook/utils.rb', line 14

def deep_merge?(previous, current)
  current.kind_of?(Hash) && previous.kind_of?(Hash)
end

.underscore(str) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/linecook/utils.rb', line 22

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