Skip to content

Commit

Permalink
Allow setting dynamic cache prefix
Browse files Browse the repository at this point in the history
So that settings can be arbitrarily scoped based on some
context (e.g. current tenant).
  • Loading branch information
artemave committed Oct 13, 2015
1 parent 0faecfc commit 82789e7
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Expand Up @@ -165,6 +165,15 @@ User.without_settings('color')
# returns a scope of users having no 'color' setting (means user.settings.color == nil)
```

Settings maybe dynamically scoped. For example, if you're using [apartment gem](https://github.com/influitive/apartment) for multitenancy, you may not want tenants to share settings:

```ruby
class Settings < RailsSettings::CachedSettings
cache_prefix { Apartment::Tenant.current }
...
end
```

-----

## How to create a list, form to manage Settings?
Expand Down
5 changes: 5 additions & 0 deletions lib/rails-settings/cached_settings.rb
Expand Up @@ -13,8 +13,13 @@ def cache_key
end

class << self
def cache_prefix(&block)
@cache_prefix = block
end

def cache_key(var_name, scope_object)
scope = "rails_settings_cached:"
scope << "#{@cache_prefix.call}:" if @cache_prefix
scope << "#{scope_object.class.name}-#{scope_object.id}:" if scope_object
scope << "#{var_name}"
end
Expand Down
7 changes: 7 additions & 0 deletions spec/rails-settings-cached/cached_setting_spec.rb
Expand Up @@ -17,6 +17,13 @@
end
end

describe '.cache_prefix' do
it 'sets cache key prefix' do
described_class.cache_prefix { "stuff" }
expect(described_class.cache_key('abc', nil)).to eql("rails_settings_cached:stuff:abc")
end
end

describe 'Unscoped' do
it 'should set a key and fetch with one query' do
expect(Setting.test_cache).to eq(nil)
Expand Down

0 comments on commit 82789e7

Please sign in to comment.