Expressions
Enable features by defining rules that evaluate against properties of an actor and a feature context.
NOTE
Expressions are an experimental feature and are subject to change. Please provide feedback if you use them.
Flipper Expressions are a powerful new way to enable features that support complex logic. They are language-agnostic and are stored in JSON, so they can sync between your application and Flipper Cloud.
Enabling an expression
The simplest expression is a comparison of a property on the actor to a given value. For example, if we have a User
model with an age
property, we can enable a feature for users of a given age:
must_be_21 = Flipper.property(:age).gte(21)
Flipper.enable :night_club, must_be_21
Now we can test it for two actors of different ages:
# Under age
Flipper.enabled? :night_club, User.new(age: 18) #=> false
# Of age
Flipper.enabled? :night_club, User.new(age: 21) #=> true
The Property
expression extracts a property from the actor (by calling #flipper_properties
on it), and in this case we use the GreaterThanOrEqualTo
(aliased to gte
) expression to compares it to the constant 21.
You can compare any two values using eq
, gt
, lt
, gte
, lte
, or ne
.
Combining expressions
What if you want to enable a feature for users who are over 21 and have either paid or are a VIP? No problem, you can group expressions together using all
and any
, and even nest groups inside each other:
over_21 = Flipper.property(:age).gte(21)
paid = Flipper.property(:paid).eq(true)
vip = Flipper.property(:vip).eq(true)
Flipper.enable :night_club, Flipper.all(over_21, Flipper.any(paid, vip))
Now we can test it for three different actors:
# Unpaid
Flipper.enabled? :night_club, User.new(2, age: 18, paid: false) #=> false
# Paid
Flipper.enabled? :night_club, User.new(1, age: 18, paid: true) #=> true
# Unpaid, but VIP
Flipper.enabled? :night_club, User.new(3, age: 18, paid: false, vip: true) #=> true
These groups can take any number of sub-expressions, and can be nested in any number of ways to create complex rules.
flipper_properties
To use expressions, you'll need to ensure that actors respond to flipper_properties
and return a hash of properties that you want to use in expressions. This is defined on ActiveRecord models by default. If you want to use expressions with a different model, you can define a method that returns a hash of properties:
class User < Struct.new(:id, :flipper_properties)
include Flipper::Identifier
end
basic_user = User.new(1, {"plan" => "basic", "age" => 30})
premium_user = User.new(2, {"plan" => "premium", "age" => 40})
To learn more, check out the plethora of code samples in examples/expressions.rb.
Get audit history, rollbacks, advanced permissions, analytics, and all of your projects in one place.
You can choose from several tiers to sponsor Flipper on GitHub and get some great benefits!