Skip to content

Commit

Permalink
Implement Alba.without_cache
Browse files Browse the repository at this point in the history
  • Loading branch information
okuramasafumi committed Mar 2, 2021
1 parent f483b15 commit e8e8dfb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/alba.rb
Expand Up @@ -12,7 +12,7 @@ class Error < StandardError; end
class UnsupportedBackend < Error; end

class << self
attr_reader :backend, :encoder, :cache
attr_reader :backend, :encoder, :cache, :cache_store
attr_accessor :default_serializer

# Set the backend, which actually serializes object into JSON
Expand All @@ -31,6 +31,7 @@ def backend=(backend)
# @params [Symbol] cache_store
# @raise [Alba::Error] if active_support is not installed or given cache_store is not supported
def cache_store=(cache_store = nil)
@cache_store = cache_store
@cache = NullCacheStore.new and return if cache_store.nil?

begin
Expand Down Expand Up @@ -66,6 +67,19 @@ def serialize(object, with: nil, &block)
resource.serialize(with: with)
end

# Low level API to disable cache temporarily.
#
# @params [Block]
def without_cache(&block)
original_cache_store = Alba.cache_store
raise ArgumentError, 'Block is required' unless block

Alba.cache_store = nil
yield
ensure
Alba.cache_store = original_cache_store
end

private

def set_encoder
Expand Down
7 changes: 7 additions & 0 deletions test/usecases/cache_test.rb
Expand Up @@ -45,6 +45,13 @@ def test_it_works_correctly_with_object_without_update_at_change
refute_equal before_update_result, after_update_result
end

def test_without_cache
Alba.without_cache do
assert_equal Alba::NullCacheStore, Alba.cache.class
end
assert_equal ActiveSupport::Cache::MemoryStore, Alba.cache.class
end

def teardown
Alba.cache_store = nil
end
Expand Down

0 comments on commit e8e8dfb

Please sign in to comment.