From 0b12ba4397bd97dcb68bf291d3a0c3b6f5a056f5 Mon Sep 17 00:00:00 2001 From: Nathan Stitt Date: Wed, 15 Mar 2017 12:14:38 -0500 Subject: [PATCH] Add option for specifying parent class --- README.md | 32 ++++++++++++++++++++++++++++++++ lib/temping.rb | 4 ++-- spec/temping_spec.rb | 23 +++++++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 43777dd..d726dd4 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,38 @@ Dog.create # => # ``` +## Options + +An option to specify the parent class can be given as a second parameter to `Temping.create`. This allows testing in environments where models inherit from a common base class. + +```ruby +# A custom base model class +class Vehicle < ActiveRecord::Base + self.abstract_class = true + def navigate_to(destination) + # non-vehicle specific logic + end +end + +Temping.create :car, parent_class: Vehicle do + with_columns do |t| + t.string :name + t.integer :num_wheels + end +end +Temping.create :bus, parent_class: Vehicle do + with_columns do |t| + t.string :name + t.integer :num_wheels + end +end + +my_car = Car.create +my_car.navigate_to(:home) +``` + + + ## Installation In your Gemfile: diff --git a/lib/temping.rb b/lib/temping.rb index af64999..8d9ddc0 100644 --- a/lib/temping.rb +++ b/lib/temping.rb @@ -47,7 +47,7 @@ def klass private def build - Class.new(model_parent_class).tap do |klass| + Class.new(@options.fetch(:parent_class, default_parent_class)).tap do |klass| Object.const_set(@model_name, klass) klass.primary_key = @options[:primary_key] || :id @@ -56,7 +56,7 @@ def build end end - def model_parent_class + def default_parent_class if ActiveRecord::VERSION::MAJOR > 4 && defined?(ApplicationRecord) ApplicationRecord else diff --git a/spec/temping_spec.rb b/spec/temping_spec.rb index 1935870..264c286 100644 --- a/spec/temping_spec.rb +++ b/spec/temping_spec.rb @@ -1,3 +1,4 @@ +# coding: utf-8 require File.join(File.dirname(__FILE__), "/spec_helper") describe Temping do @@ -48,6 +49,28 @@ class ApplicationRecord < ActiveRecord::Base; end end end + context "with a custom parent class" do + before do + unless defined?(TestBaseClass) + class TestBaseClass < ActiveRecord::Base + self.abstract_class = true + end + end + end + after do + Object.send(:remove_const, :TestBaseClass) + end + it 'uses the provided parent class option' do + child_class = Temping.create(:test_child, parent_class: TestBaseClass) + expect(child_class.superclass).to eq(TestBaseClass) + expect(child_class.new).to be_an(TestBaseClass) + end + it 'doesn’t affect other types' do + gerbil_class = Temping.create(:gerbil) + expect(gerbil_class.superclass).to eq(ActiveRecord::Base) + end + end + it "creates table with given options" do mushroom_class = Temping.create(:mushroom, primary_key: :guid) expect(mushroom_class.table_name).to eq "mushrooms"