Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify route reloader and ensure threadsafe #31

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions app/models/duckrails/application_state.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,14 @@ class ApplicationState < ActiveRecord::Base
def update_token(type)
case type
when :mock
self.mock_synchronization_token = Synchronizer.generate_token
after_save :save_timestamp
save
end
end

class << self
# @return [ApplicationState] the one and only application state
def instance
ApplicationState.first || ApplicationState.create(singleton_guard: 0,
mock_synchronization_token: Synchronizer.generate_token)
end
def save_timestamp
ts = Time.zone.now.to_i
Rails.cache.write(:routes_changed_timestamp, ts)
end
end
end
2 changes: 0 additions & 2 deletions lib/duckrails/router.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ class Router
class << self
def register_mock(mock)
REGISTERED_MOCKS << mock.id
Duckrails::ApplicationState.instance.update_token :mock
REGISTERED_MOCKS.uniq!
end

Expand All @@ -19,7 +18,6 @@ def register_current_mocks

def unregister_mock(mock)
REGISTERED_MOCKS.delete mock.id
Duckrails::ApplicationState.instance.update_token :mock
end

def reset!
Expand Down
9 changes: 3 additions & 6 deletions lib/duckrails/synchronizer.rb
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
module Duckrails
class Synchronizer
cattr_accessor :mock_synchronization_token

def initialize(app)
@app = app
end

def call(env)
application_state = Duckrails::ApplicationState.instance

if Duckrails::Synchronizer.mock_synchronization_token != application_state.mock_synchronization_token
timestamp = Rails.cache.read(:routes_changed_timestamp)
if Thread.current[:routes_changed_timestamp] != timestamp
Rails.logger.info 'Mock synchronization token missmatch. Syncronizing...'
Router.reset!
Duckrails::Synchronizer.mock_synchronization_token = application_state.mock_synchronization_token
Thread.current[:routes_changed_timestamp] = timestamp
Rails.logger.info 'Mock synchronization completed.'
end

Expand Down