Module: EcoRake::Default::Const::ClassMethods

Defined in:
lib/eco-rake/default/const.rb

Instance Method Summary collapse

Instance Method Details

#attr_const(*attrs, required: false, override: false, default: :not_used) ⇒ Object

Note:

this creates one method on the class and one on instances thereof.

Creates (overridable) method(s) that link to an expected constant with same name (in capitals).

Parameters:

  • required (Boolean) (defaults to: false)

    whether an exception should be raised if the constant does not exist when the created method is called.

  • override (Boolean) (defaults to: false)

    whether an exception should NOT be raised if the method exists.

  • default (Variant) (defaults to: :not_used)

    whether if this defaults to some value (won't raise NameError).



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/eco-rake/default/const.rb', line 19

def attr_const(*attrs, required: false, override: false, default: :not_used)
  attrs.each do |attr|
    attr = attr.to_s.freeze

    unless override
      msg  = "#{__method__} does not allow method override. Offending attr: #{attr}"
      raise ArgumentError, "#{msg} (class method)"    if methods.include?(attr)
      raise ArgumentError, "#{msg} (instance method)" if instance_methods.include?(attr)
    end

    define_singleton_method attr do
      value = resolve_const(attr)
      value = default if value.nil? && default != :not_used

      msg   = "Missing const '#{attr.to_s.upcase}' in #{self}"
      raise NameError, msg if value.nil? && required

      yield(value) if block_given?
      value
    end

    define_method attr do |&block|
      self.class.send(attr, &block)
    end
  end
end