Skip to content

Commit

Permalink
fix: check database and table's existence before getting the metadata. (
Browse files Browse the repository at this point in the history
#8)

* chore: no need to rescue

* chore: add a bit comments

* chore: fix rubocop issue
  • Loading branch information
tian-im authored Mar 15, 2020
1 parent 38f7481 commit af79292
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
16 changes: 8 additions & 8 deletions lib/adapters/wallaby/active_record/model_decorator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@ class ModelDecorator < ::Wallaby::ModelDecorator
# @return [ActiveSupport::HashWithIndifferentAccess] metadata
def fields
@fields ||= ::ActiveSupport::HashWithIndifferentAccess.new.tap do |hash|
# NOTE: There is a chance that people create ActiveRecord class
# before they do the migration, so initialising the fields will raise
# all kinds of error. Therefore, we need to check the table existence
if @model_class.table_exists?
hash.merge! general_fields
hash.merge! association_fields
hash.except!(*foreign_keys_from_associations)
end
# NOTE: Need to check database and table's existence
# before pulling out the metadata from model.
# So that the database and migration related task can be executed.
next unless ::ActiveRecord::Base.connected? && @model_class.table_exists?

hash.merge! general_fields
hash.merge! association_fields
hash.except!(*foreign_keys_from_associations)
end.freeze
end

Expand Down
23 changes: 23 additions & 0 deletions spec/features/database_active_check_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
require 'rails_helper'

describe 'Database active check' do
let(:model_class) { Blog }
let(:model_decorator) { Wallaby::ActiveRecord::ModelDecorator.new model_class }

context 'when database does not exist' do
it 'returns empty hash' do
expect(::ActiveRecord::Base).to receive(:connected?).and_return(false)
expect(model_decorator.fields).to eq({})
end
end

context 'when table does not exist' do
let(:model_class) { stub_const 'NotFoundTable', Class.new(ActiveRecord::Base) }

it 'returns empty hash' do
expect(::ActiveRecord::Base).to be_connected
expect(model_class).not_to be_table_exists
expect(model_decorator.fields).to eq({})
end
end
end

0 comments on commit af79292

Please sign in to comment.