Sha256: f15af070f53e26ae5a1495eb11a92374b3e69eea420b1c71bfb3517d8dbca27c

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

module WithModel
  class Dsl
    attr_reader :model_initialization

    def initialize(name, example_group)
      dsl = self

      @example_group = example_group
      @table_name = table_name = "with_model_#{name}_#{$$}"
      @model_initialization = lambda {|*|}

      const_name = name.to_s.camelize.to_sym

      original_const_defined = Object.const_defined?(const_name)
      original_const_value = Object.const_get(const_name) if original_const_defined

      example_group.class_eval do
        attr_accessor name
      end

      example_group.before do
        model = Class.new(ActiveRecord::Base)
        silence_warnings { Object.const_set(const_name, model) }
        Object.const_get(const_name).class_eval do
          set_table_name table_name
          class << self
            def with_model?
              true
            end
          end
          self.class_eval(&dsl.model_initialization)
        end
        send("#{name}=", model)
      end

      example_group.after do
        Object.send(:remove_const, const_name)
        Object.const_set(const_name, original_const_value) if original_const_defined
      end
    end

    def table(&block)
      @example_group.with_table(@table_name, &block)
    end

    def model(&block)
      @model_initialization = block
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
with_model-0.1 lib/with_model/dsl.rb