Skip to content

Commit

Permalink
syntactic sugar for availability check [zendesk#14]
Browse files Browse the repository at this point in the history
  • Loading branch information
James A. Rosen committed Feb 14, 2011
1 parent 55253dd commit efb3698
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 11 deletions.
9 changes: 6 additions & 3 deletions README.md
Expand Up @@ -243,12 +243,15 @@ The latter can be used like so:

If you want to check availability outside of a controller or view (really
outside of something that has `Arturo::FeatureAvailability` mixed in), you
can do the following:
can ask either

Arturo.feature_enabled_for?(:foo, recipient)

This will check both whether the `:foo` feature exists and whether it is
enabled for `recipient`.
or the slightly fancier

Arturo.foo_enabled_for?(recipient)

Both check whether the `foo` feature exists and is enabled for `recipient`.

#### Caching

Expand Down
33 changes: 25 additions & 8 deletions lib/arturo.rb
Expand Up @@ -6,13 +6,30 @@ module Arturo
require 'arturo/controller_filters'
require 'arturo/engine' if defined?(Rails) && Rails::VERSION::MAJOR == 3

# Quick check for whether a feature is enabled for a recipient.
# @param [String, Symbol] feature_name
# @param [#id] recipient
# @return [true,false] whether the feature exists and is enabled for the recipient
def self.feature_enabled_for?(feature_name, recipient)
f = self::Feature.to_feature(feature_name)
f && f.enabled_for?(recipient)
end
class <<self

# Quick check for whether a feature is enabled for a recipient.
# @param [String, Symbol] feature_name
# @param [#id] recipient
# @return [true,false] whether the feature exists and is enabled for the recipient
def feature_enabled_for?(feature_name, recipient)
f = self::Feature.to_feature(feature_name)
f && f.enabled_for?(recipient)
end

ENABLED_FOR_METHOD_NAME = /^(\w+)_enabled_for\?$/

def respond_to?(symbol)
symbol.to_s =~ ENABLED_FOR_METHOD_NAME || super(symbol)
end

def method_missing(symbol, *args, &block)
if (args.length == 1 && match = ENABLED_FOR_METHOD_NAME.match(symbol.to_s))
feature_enabled_for?(match[1], args[0])
else
super(symbol, *args, &block)
end
end

end
end
6 changes: 6 additions & 0 deletions test/dummy_app/test/unit/feature_test.rb
Expand Up @@ -30,6 +30,12 @@ def test_feature_enabled_for_non_existent_feature
assert !::Arturo.feature_enabled_for?(:does_not_exist, 'Paula')
end

def test_x_enabled_for
@feature = Factory(:feature, :deployment_percentage => 100, :symbol => :foo)
recipient = stub('User', :to_s => 'Paula', :id => 12)
assert ::Arturo.foo_enabled_for?(recipient), "#{feature} should be enabled for #{recipient}"
end

def test_requires_a_symbol
feature.symbol = nil
assert !feature.valid?
Expand Down

0 comments on commit efb3698

Please sign in to comment.