Last active
June 28, 2019 17:08
-
-
Save ryenski/be59ab97df591b317799b495cfc798c9 to your computer and use it in GitHub Desktop.
Feature Flags with Pundit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Migration... | |
class AddFeatureFlagsToUsers < ActiveRecord::Migration[5.2] | |
def change | |
add_column :users, :feature_flags, :string, array: true, default: [] | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FeaturePolicy = Struct.new(:user, :feature) do | |
# Respond to any method ending with a question mark. | |
# Look for a feature flag with that name in that user's record. | |
# | |
# It looks for an array attribute called `feature_flags` in the user's record, and checks to see if the requested feature is | |
# included in the list of features. | |
# | |
# @example User can access accounting feature? | |
# policy(:feature).accounting? | |
# | |
# @return [Boolean] | |
def method_missing(method_name, *params, &block) | |
if respond_to_missing?(method_name) | |
feature = method_name.to_s.parameterize | |
user.feature_flags.include?(feature) | |
else | |
super | |
end | |
end | |
private | |
def respond_to_missing?(method_name, *) | |
/^\w+\?/.match?(method_name) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment