Sha256: e1dbe854dc500bdf917a2d3079100339d5d387472f4f454415e0d7190bf30f5d

Contents?: true

Size: 1.36 KB

Versions: 4

Compression:

Stored size: 1.36 KB

Contents

require "descendants_describable/version"

module DescendantsDescribable
  extend ActiveSupport::Concern

  module ClassMethods
    def describe_descendants_with(description_module, &block)
      DescendantsDescriptor.new(self, description_module).instance_exec &block
    end
  end


  class DescendantsDescriptor

    attr_accessor :new_class

    def initialize(parent, description_module)
      @common_modules = []
      @parent = parent
      @description_module = description_module
    end

    def add_module(mod)
      self.new_class.send(:include, mod)
    end

    def type(name)

      self.new_class = begin
        Object.const_get(name.to_s.camelize)
      rescue NameError
        new_class = Class.new(@parent)
        Object.const_set(name.to_s.camelize, new_class)
        new_class
      end

      @common_modules.each { |m| self.new_class.send(:include, m) } if @common_modules.any?

      yield if block_given?

      self.new_class = nil
    end

    def method_missing(method, *args)
      if self.new_class.present?
        add_module @description_module.const_get(method.to_s.camelize)
      else
        @common_modules << @description_module.const_get(method.to_s.camelize)
        yield if block_given?
        @common_modules.pop
      end
    end

    def respond_to?(method)
      @description_module.const_get(method.to_s.camelize) rescue false
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
descendants_describable-0.0.6 lib/descendants_describable.rb
descendants_describable-0.0.5 lib/descendants_describable.rb
descendants_describable-0.0.4 lib/descendants_describable.rb
descendants_describable-0.0.3 lib/descendants_describable.rb