项目作者: voormedia

项目描述 :
Flipflop lets you declare and manage feature flags in your Rails application.
高级语言: Ruby
项目地址: git://github.com/voormedia/flipflop.git
创建时间: 2016-03-03T09:10:36Z
项目社区:https://github.com/voormedia/flipflop

开源协议:MIT License

下载


Build Status

Flipflop your features

Flipflop provides a declarative, layered way of enabling and disabling
application functionality at run-time. It is originally based on
Flip. Flipflop has the following features:

  • simple configuration
  • ease of use for developers
  • an improved dashboard
  • manage features via console (using rake tasks)
  • thread safety
  • better database performance due to per-request caching, enabled by default
  • optional eager loading (if you expect to use many features per request)
  • more strategies (Sequel, Redis, query strings, sessions, custom code)
  • more strategy options (cookie options, strategy names and descriptions, custom database models)
  • the ability to use the same strategy twice, with different options
  • configuration in a fixed location (config/features.rb) that is usable even if you don’t use the database strategy
  • dashboard is inaccessible in production by default, for safety in case of misconfiguration
  • removes controller filters and view helpers, to promote uniform semantics to check for features (facilitates project-wide searching)
  • support for API only Rails apps
  • support for loading features from Rails engines
  • support for feature groups

You can configure strategy layers that will evaluate if a feature is currently
enabled or disabled. Available strategies are:

  • a per-feature default setting
  • database (with Active Record, Sequel, or Redis), to flipflop features site-wide for all users
  • cookie or session, to flipflop features for single users
  • query string parameters, to flipflop features occasionally (in development mode for example)
  • custom strategy code

Flipflop has a dashboard interface that’s easy to understand and use.

Dashboard

If you prefer, you can use the included rake tasks to enable or disable features.

  1. rake flipflop:features # Shows features table
  2. rake flipflop:turn_on[feature,strategy] # Enables a feature with the specified strategy
  3. rake flipflop:turn_off[feature,strategy] # Disables a feature with the specified strategy
  4. rake flipflop:clear[feature,strategy] # Clears a feature with the specified strategy

Rails requirements

This gem requires Rails 4, 5, 6 or 7. Using an ORM layer is entirely optional.

Installation

Add the gem to your Gemfile:

  1. gem "flipflop"

Generate routes, feature settings and database migration:

  1. rails g flipflop:install

Run the migration to store feature settings in your database:

  1. rake db:migrate

Declaring features

Features and strategies are declared in config/features.rb:

  1. Flipflop.configure do
  2. # Strategies will be used in the order listed here.
  3. strategy :cookie
  4. strategy :active_record # or :sequel, :redis
  5. strategy :default
  6. # Basic feature declaration:
  7. feature :shiny_things
  8. # Enable features by default:
  9. feature :world_domination, default: true
  10. # Group features together:
  11. group :improved_design do
  12. feature :improved_navigation
  13. feature :improved_homepage
  14. end
  15. end

This file is automatically reloaded in development mode. No need to restart
your server after making changes.

Feature definitions support these options:

  • :default – The feature’s default value. This is the value of the feature if no strategy configures an explicit value. Defaults to false.
  • :description – An optional description of the feature. Displayed on the dashboard if present.
  • :title – An optional title of the feature. This defaults to a humanized version of the feature name. Displayed on the dashboard.

Strategies

The following strategies are provided:

  • :active_record/:sequel – Save feature settings in the database.
    • :class – Provide the feature model. Flipflop::Feature by default (which is defined automatically and uses the table flipflop_features). The ActiveRecord version honors default_scope when features are resolved or switched on/off.
    • :eager – Whether to eagerly fetch all features from the database when the first feature is resolved. Useful if you expect you’ll need more than 1 feature on average and you have a limited number of features. NOTE: When using outside Rails, make sure you use Flipflop::FeatureCache::Middleware or enable the feature cache manually. Default is false.
  • :cookie – Save feature settings in browser cookies for the current user.
    • :prefix – String prefix for all cookie names. Defaults to no prefix.
    • :path – The path for which the cookies apply. Defaults to the root of the application.
    • :domain – Cookie domain. Is nil by default (no specific domain). Can be :all to use the topmost domain. Can be an array of domains.
    • :secure – Only set cookies if the connection is secured with TLS. Default is false.
    • :httponly – Whether the cookies are accessible via scripting or only HTTP. Default is false.
  • :query_string – Interpret query string parameters as features. This strategy is only used for resolving. It does not allow switching features on/off.
    • :prefix – String prefix for all query string parameters. Defaults to no prefix.
  • :redis – Save feature settings in Redis.
    • :client – Use the specified Redis client instead of Redis.new.
    • :prefix – String prefix for all Redis keys. Defaults to no prefix.
  • :session – Save feature settings in the current user’s application session.
    • :prefix – String prefix for all session variables. Defaults to no prefix.
  • :default – Not strictly needed, all feature defaults will be applied if no strategies match a feature. Include this strategy to determine the order of using the default value, and to make it appear in the dashboard.
  • :test – Simple strategy that stores features in memory. Useful for testing. If you call Flipflop::FeatureSet.current.test! this strategy is enabled and replaces all configured strategies.

All strategies support these options, to change the appearance of the dashboard:

  • :name – The name of the strategy. Defaults to the name of the selected strategy.
  • :description – The description of the strategy. Every strategy has a default description.
  • :hidden – Optionally hides the strategy from the dashboard. Default is false.

The same strategy type can be used multiple times, as long as the options are
different. To prevent subtle bugs, an error is raised if two identical
strategies are configured.

Checking if a feature is enabled

Flipflop.enabled? or the dynamic predicate methods can be used to check
feature state:

  1. Flipflop.enabled?(:world_domination) # true
  2. Flipflop.world_domination? # true
  3. Flipflop.enabled?(:shiny_things) # false
  4. Flipflop.shiny_things? # false

This works everywhere. In your views:

  1. <div>
  2. <% if Flipflop.world_domination? %>
  3. <%= link_to "Dominate World", world_dominations_path %>
  4. <% end %>
  5. </div>

In your controllers:

  1. class ShinyThingsController < ApplicationController
  2. def index
  3. return head :forbidden unless Flipflop.shiny_things?
  4. # Proceed with shiny things...
  5. end
  6. end

In your models:

  1. class ShinyThing < ActiveRecord::Base
  2. after_initialize do
  3. if !Flipflop.shiny_things?
  4. raise ActiveRecord::RecordNotFound
  5. end
  6. end
  7. end

Custom strategies

Custom light-weight strategies can be defined with a block:

  1. Flipflop.configure do
  2. strategy :random do |feature|
  3. rand(2).zero?
  4. end
  5. # ...
  6. end

You can define your own custom strategies by inheriting from
Flipflop::Strategies::AbstractStrategy:

  1. class UserPreferenceStrategy < Flipflop::Strategies::AbstractStrategy
  2. class << self
  3. def default_description
  4. "Allows configuration of features per user."
  5. end
  6. end
  7. def switchable?
  8. # Can only switch features on/off if we have the user's session.
  9. # The `request` method is provided by AbstractStrategy.
  10. request?
  11. end
  12. def enabled?(feature)
  13. # Can only check features if we have the user's session.
  14. return unless request?
  15. find_current_user.enabled_features[feature]
  16. end
  17. def switch!(feature, enabled)
  18. user = find_current_user
  19. user.enabled_features[feature] = enabled
  20. user.save!
  21. end
  22. def clear!(feature)
  23. user = find_current_user
  24. user.enabled_features.delete(feature)
  25. user.save!
  26. end
  27. private
  28. def find_current_user
  29. # The `request` method is provided by AbstractStrategy.
  30. User.find_by_id(request.session[:user_id])
  31. end
  32. end

Use it in config/features.rb:

  1. Flipflop.configure do
  2. strategy UserPreferenceStrategy # name: "my strategy", description: "..."
  3. end

If you define your class inside Flipflop::Strategies, you can use the
shorthand name to refer to your strategy:

  1. module Flipflop::Strategies
  2. class UserPreferenceStrategy < AbstractStrategy
  3. # ...
  4. end
  5. end
  1. Flipflop.configure do
  2. strategy :user_preference
  3. end

Dashboard access control

The dashboard provides visibility and control over the features.

You don’t want the dashboard to be public. For that reason it is only available
in the development and test environments by default. Here’s one way of
implementing access control.

In app/config/application.rb:

  1. config.flipflop.dashboard_access_filter = :require_authenticated_user

In app/controllers/application_controller.rb:

  1. class ApplicationController < ActionController::Base
  2. def require_authenticated_user
  3. head :forbidden unless User.logged_in?
  4. end
  5. end

Or directly in app/config/application.rb:

  1. config.flipflop.dashboard_access_filter = -> {
  2. head :forbidden unless User.logged_in?
  3. }

Features in Rails engines

You can use features in Rails engines. Simply tell Flipflop to load files from
an additional file in an initializer. You can define features and strategies.
Both will be merged with application features. You’ll have to somewhat careful
with defining strategies in the engine to avoid conflicts.

  1. class MyEngine < Rails::Engine
  2. initializer "load_features" do
  3. # Features from config/features.rb in your engine are merged with
  4. # any application features.
  5. Flipflop::FeatureLoader.current.append(self)
  6. end
  7. end

Internationalization

The dashboard is translatable. Make sure I18n.locale is set to the correct
value in your ApplicationController or alternatively in
dashboard_access_filter.

Take a look at the English translations to see which
keys should be present and translated in your locale file.

Testing

In your test environment, you typically want to keep your features. But to make
testing easier, you may not want to use any of the strategies you use in
development and production. You can replace all strategies with a single
:test strategy by calling Flipflop::FeatureSet.current.test!. The test
strategy will be returned. You can use this strategy to enable and disable
features.

  1. describe WorldDomination do
  2. before do
  3. test_strategy = Flipflop::FeatureSet.current.test!
  4. test_strategy.switch!(:world_domination, true)
  5. end
  6. it "should dominate the world" do
  7. # ...
  8. end
  9. end

If you are not happy with the default test strategy (which is essentially a
simple thread-safe hash object), you can provide your own implementation as
argument to the test! method.

License

This software is licensed under the MIT License. View the license.