Sha256: 3bcdd0e182e0e992e4d304ce7fec140214a1363f45ac41ec4cef6a6df1e13998

Contents?: true

Size: 1.26 KB

Versions: 2

Compression:

Stored size: 1.26 KB

Contents

module DefinedBy
  module MissingConstant
    class Definition
      class << self
        attr_accessor :definitions
        
        def for(const_name)
          definitions.detect do |definition|
            definition.match(const_name)
          end.constant rescue nil
        end
        
        def definitions
          @definitions ||= []
        end
        
        def define!(&block)
          DefinedBy::DSL(&block).each do |key, value, dsl_block|
            definitions << Definition.new(value.first, value.last)
          end
        end
      end
      
      attr_reader :pattern, :replacement, :constant
      def initialize(pattern, replacement)
        @pattern, @replacement = pattern, replacement
      end
      
      def match(const_name)
        if const_name.to_s.match(pattern)
          @constant = const_name.to_s.gsub(pattern, replacement).to_sym
        else
          @constant = nil
        end
      end
    end
    
#    def const_missing(const_name)
#      if new_constant = Definition.for(const_name)
#        super(new_constant)
#      end
#      super(const_name)
#    end
  end
  
  def self.MissingConstants(&block)
    DefinedBy::MissingConstant::Definition.define!(&block)
  end
end

#Class.instance_eval { include DefinedBy::MissingConstant }

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
defined-by-0.0.6 lib/defined-by/missing_constant.rb
defined-by-0.0.5 lib/defined-by/missing_constant.rb