Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Created May 29, 2021 22:48
Show Gist options
  • Save stevepolitodesign/0c6fb54a174a9e01505ad363504477c0 to your computer and use it in GitHub Desktop.
Save stevepolitodesign/0c6fb54a174a9e01505ad363504477c0 to your computer and use it in GitHub Desktop.
Use Pundit as a Feature Flag System
# app/models/user.rb
class User < ApplicationRecord  
  FEATURES = %i[enable_post_meta_description].freeze
  store :features, accessors: User::FEATURES
end
# app/policies/feature/enable_post_meta_description_policy.rb
class Feature::EnablePostMetaDescriptionPolicy < ApplicationPolicy
  def create?
    user.present? && (user.enable_post_meta_description == true)
  end

  def permitted_attributes
    if user.enable_post_meta_description == true
      [:title, :user_id, :meta_description]
    else
      [:title, :user_id]
    end
  end
end
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  ...
  private
    ...
    def post_params
      params.require(:post).permit(
        Feature::EnablePostMetaDescriptionPolicy.new(current_user, Post).permitted_attributes
      )
    end
end
<%= form_with(model: post) do |form| %>
  ...
  <% if Feature::EnablePostMetaDescriptionPolicy.new(current_user, post).create? %>
    <div class="field">
      <%= form.label :meta_description %>
      <%= form.text_area :meta_description %>
    </div> 
  <% end %>
  ...
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment