Sha256: c94a237f75db20b96c9392e6f9a3e53bf366c2120f6e84b6d78969cca0e14169

Contents?: true

Size: 1.91 KB

Versions: 3

Compression:

Stored size: 1.91 KB

Contents

module UnitTests
  module ClassBuilder
    def self.parse_constant_name(name)
      namespace = Shoulda::Matchers::Util.deconstantize(name)
      qualified_namespace = (namespace.presence || 'Object').constantize
      name_without_namespace = name.to_s.demodulize
      [qualified_namespace, name_without_namespace]
    end

    def self.configure_example_group(example_group)
      example_group.include(self)

      example_group.after do
        teardown_defined_constants
      end
    end

    def define_module(module_name, &block)
      module_name = module_name.to_s.camelize

      namespace, name_without_namespace =
        ClassBuilder.parse_constant_name(module_name)

      if namespace.const_defined?(name_without_namespace, false)
        namespace.__send__(:remove_const, name_without_namespace)
      end

      eval <<-RUBY
        module #{namespace}::#{name_without_namespace}
        end
      RUBY

      namespace.const_get(name_without_namespace).tap do |constant|
        constant.unloadable

        if block
          constant.module_eval(&block)
        end
      end
    end

    def define_class(class_name, parent_class = Object, &block)
      class_name = class_name.to_s.camelize

      namespace, name_without_namespace =
        ClassBuilder.parse_constant_name(class_name)

      if namespace.const_defined?(name_without_namespace, false)
        namespace.__send__(:remove_const, name_without_namespace)
      end

      eval <<-RUBY
        class #{namespace}::#{name_without_namespace} < #{parent_class}
        end
      RUBY

      namespace.const_get(name_without_namespace).tap do |constant|
        constant.unloadable

        if block
          if block.arity == 0
            constant.class_eval(&block)
          else
            block.call(constant)
          end
        end
      end
    end

    private

    def teardown_defined_constants
      ActiveSupport::Dependencies.clear
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
shoulda-matchers-3.0.1 spec/support/unit/helpers/class_builder.rb
shoulda-matchers-3.0.0 spec/support/unit/helpers/class_builder.rb
shoulda-matchers-3.0.0.rc1 spec/support/unit/helpers/class_builder.rb