Skip to content

Instantly share code, notes, and snippets.

@ryenski
Last active June 28, 2019 17:08
Show Gist options
  • Save ryenski/be59ab97df591b317799b495cfc798c9 to your computer and use it in GitHub Desktop.
Save ryenski/be59ab97df591b317799b495cfc798c9 to your computer and use it in GitHub Desktop.
Feature Flags with Pundit
# Migration...
class AddFeatureFlagsToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :feature_flags, :string, array: true, default: []
end
end
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