Module: EcoRake::Base::SymbolResolver

Includes:
MethodHelpers
Defined in:
lib/eco-rake/base/symbol_resolver.rb

Instance Method Summary collapse

Methods included from MethodHelpers

#aux_curry, #safe_call

Instance Method Details

#constant_name(value) ⇒ Object

i.e. value = :default_value -> 'DEFAULT_VALUE'



7
8
9
10
11
12
13
14
# File 'lib/eco-rake/base/symbol_resolver.rb', line 7

def constant_name(value)
  case value
  when String
    value.strip.upcase
  when Symbol
    constant_name(value.to_s)
  end
end

#resolve_const(sym, source: self) ⇒ Value, NilClass



50
51
52
53
54
55
56
57
58
59
# File 'lib/eco-rake/base/symbol_resolver.rb', line 50

def resolve_const(sym, source: self)
  return nil unless sym.is_a?(Symbol) || sym.is_a?(String)
  sym = constant_name(sym)
  value   = nil
  value ||= safe_const_get(sym, klass: source)
  value ||= safe_const_get(sym, klass: Kernel)
  value
rescue NameError
  nil
end

#resolve_method(sym, source: self) ⇒ Method, NilClass



72
73
74
75
76
77
78
79
# File 'lib/eco-rake/base/symbol_resolver.rb', line 72

def resolve_method(sym, source: self)
  return nil unless sym.is_a?(Symbol) || sym.is_a?(String)
  meth = source.method(sym) if source.respond_to?(sym, true)
  return meth if meth
  return nil  if source.is_a?(Class)
  return nil  unless source.class.respond_to?(sym, true)
  source.class.method(sym)
end

#resolve_symbol(sym, source: self, as: %i[method const])) ⇒ Method, ...



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/eco-rake/base/symbol_resolver.rb', line 36

def resolve_symbol(sym, source: self, as: i[method const])
  as = [as].flatten.compact
  as.reduce(nil) do |value, type|
    case type
    when :const
      value || resolve_const(sym, source: source)
    when :method
      value || resolve_method(sym, source: source)
    end
  end
end

#safe_const_get(name, klass: self) ⇒ Value, NilClass

Note:

it does not raise ErrorName

Returns nil if const not defined or the value of the constant.



63
64
65
66
67
68
# File 'lib/eco-rake/base/symbol_resolver.rb', line 63

def safe_const_get(name, klass: self)
  klass = klass.class unless klass.is_a?(Class) || klass == Kernel
  klass.const_get(name) if klass.const_defined?(name)
rescue NameError
  nil
end

#symbol_resolver(sym, as: %i[method const])) ⇒ Proc

Note:

the resolution process goes in this order

  1. First try on the invoker and its class.
  2. Final on the definer and its class.

Wraps a symbol to be resolved lazyly.



21
22
23
24
25
26
27
28
29
30
# File 'lib/eco-rake/base/symbol_resolver.rb', line 21

def symbol_resolver(sym, as: i[method const])
  definer = self
  proc do |invoker|
    resolution = invoker.instance_eval do
      definer.resolve_symbol(sym, source: invoker, as: as)
    end
    resolution ||= definer.resolve_symbol(sym, source: definer, as: as)
    resolution
  end
end