Skip to content

Commit

Permalink
Merge pull request #170 from watermarkchurch/fix-reloading-2
Browse files Browse the repository at this point in the history
Fix reloading issues
  • Loading branch information
gburgett committed May 22, 2019
2 parents c3c0c6f + 12cea23 commit 3c728a9
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 3 deletions.
9 changes: 7 additions & 2 deletions wcc-contentful/lib/wcc/contentful/model_singleton_methods.rb
Expand Up @@ -67,8 +67,13 @@ def find_by(filter = nil)
end

def inherited(subclass)
# only register if it's not already registered
return if WCC::Contentful::Model.registered?(content_type)
# When rails does auto-reloading, a new class is created with the same name.
# Let's re-register the new class for this content type.
# However, if another different class is registered for this content type,
# don't register it.
if WCC::Contentful::Model.registered?(content_type)
return if WCC::Contentful::Model.registry[content_type].name != subclass.name
end

WCC::Contentful::Model.register_for_content_type(content_type, klass: subclass)
end
Expand Down
63 changes: 62 additions & 1 deletion wcc-contentful/spec/wcc/contentful/model_builder_spec.rb
Expand Up @@ -5,7 +5,12 @@
WCC::Contentful::ModelBuilder.new(types)
}

let(:types) { load_indexed_types }
let(:types) {
types = load_indexed_types
allow(WCC::Contentful).to receive(:types)
.and_return(types)
types
}
let!(:store) {
load_store_from_sync
}
Expand Down Expand Up @@ -577,5 +582,61 @@ def initialize(raw, context)
WCC::Contentful::Model.find('5NBhDw3i2kUqSwqYok4YQO')
}.to raise_error(NameError)
end

it 'uses the newest constant when rails auto-loading happens' do
file = Tempfile.open(['my_menu_button', '.rb'])
begin
begin
file.write(<<~RUBY)
class MenuButton < WCC::Contentful::Model::MenuButton
end
RUBY
ensure
file.close
end
load(file.path)

item = WCC::Contentful::Model.find '3Jmk4yOwhOY0yKsI6mAQ2a'
expect(item).to be_a MenuButton

# act: reload the file
Object.send(:remove_const, :MenuButton)
load(file.path)

item2 = WCC::Contentful::Model.find '3Jmk4yOwhOY0yKsI6mAQ2a'
expect(item2).to be_a MenuButton
ensure
file.unlink
end
end

it 'uses the newest constant when it declares register_for_content_type' do
file = Tempfile.open(['my_menu_button', '.rb'])
begin
begin
file.write(<<~RUBY)
class MyButton < WCC::Contentful::Model::MenuButton
register_for_content_type 'menuButton'
end
RUBY
ensure
file.close
end
load(file.path)

item = WCC::Contentful::Model.find '3Jmk4yOwhOY0yKsI6mAQ2a'
expect(item).to be_a MyButton

# act: reload the file
Object.send(:remove_const, :MyButton)
load(file.path)

item2 = WCC::Contentful::Model.find '3Jmk4yOwhOY0yKsI6mAQ2a'
expect(item2).to be_a MyButton
ensure
Object.send(:remove_const, :MyButton)
file.unlink
end
end
end
end

0 comments on commit 3c728a9

Please sign in to comment.