Skip to content

Commit

Permalink
Add option for specifying parent class
Browse files Browse the repository at this point in the history
  • Loading branch information
nathanstitt committed Mar 15, 2017
1 parent f67c817 commit 0b12ba4
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
32 changes: 32 additions & 0 deletions README.md
Expand Up @@ -93,6 +93,38 @@ Dog.create
# => #<Dog id: d937951b-765c-4bc9-804e-3171d22117b0>
```

## 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:
Expand Down
4 changes: 2 additions & 2 deletions lib/temping.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down
23 changes: 23 additions & 0 deletions spec/temping_spec.rb
@@ -1,3 +1,4 @@
# coding: utf-8
require File.join(File.dirname(__FILE__), "/spec_helper")

describe Temping do
Expand Down Expand Up @@ -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"
Expand Down

0 comments on commit 0b12ba4

Please sign in to comment.