Sha256: b9b2767925b4f6968ce417e3e9fe3b5cae98bf3d6a37527d354d6be4294b9ba0

Contents?: true

Size: 1.8 KB

Versions: 13

Compression:

Stored size: 1.8 KB

Contents

class EcoRake
  module Default
    module Const
      class << self
        def included(base)
          super(base)
          base.extend EcoRake::Base::SymbolResolver
          base.extend ClassMethods
        end
      end

      module ClassMethods
        # Creates (overridable) method(s) that link to an expected constant with same name (in capitals).
        # @note this creates one method on the class and one on instances thereof.
        # @param required [Boolean] whether an exception should be raised if the constant does not exist
        #   when the created method is called.
        # @param override [Boolean] whether an exception should NOT be raised if the method exists.
        # @param default [Variant] whether if this defaults to some value (won't raise NameError).
        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
              msg   = "Missing const '#{attr.to_s.upcase}' in #{self}"
              value = resolve_const(attr)
              value = default      if value.nil? && default != :not_used
              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
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
eco-rake-0.2.6 lib/eco-rake/default/const.rb
eco-rake-0.2.5 lib/eco-rake/default/const.rb
eco-rake-0.2.4 lib/eco-rake/default/const.rb
eco-rake-0.2.3 lib/eco-rake/default/const.rb
eco-rake-0.2.2 lib/eco-rake/default/const.rb
eco-rake-0.2.1 lib/eco-rake/default/const.rb
eco-rake-0.2.0 lib/eco-rake/default/const.rb
eco-rake-0.1.6 lib/eco-rake/default/const.rb
eco-rake-0.1.5 lib/eco-rake/default/const.rb
eco-rake-0.1.4 lib/eco-rake/default/const.rb
eco-rake-0.1.3 lib/eco-rake/default/const.rb
eco-rake-0.1.2 lib/eco-rake/default/const.rb
eco-rake-0.1.1 lib/eco-rake/default/const.rb