Skip to content

Instantly share code, notes, and snippets.

@bkeepers
Last active February 4, 2024 10:46
Show Gist options
  • Save bkeepers/58a2cc23ac14f9ccc900429b747fbcfc to your computer and use it in GitHub Desktop.
Save bkeepers/58a2cc23ac14f9ccc900429b747fbcfc to your computer and use it in GitHub Desktop.
Simple Flipper API for your app
// Plain ol' JavaScript module for fetching feature flags from the server
//
// import { isEnabled } from './flipper.js'
//
// if (await isEnabled("new_feature")) {
// // render new feature
// } else {
// // render old feature
// }
//
const features = fetch("/flipper.json").then(response => response.json());
export async function isEnabled(key) {
return await features.then(features => features[key]);
};
class FlipperController < ApplicationController
# Returns the value of all feature flags for the current user
def index
features = Flipper.features.map do |feature|
[feature.name, Flipper.enabled?(feature.key, current_user)]
end
render json: features.to_h
end
end
Rails.application.routes.draw do
resources :flipper, controller: "flipper", only: [:index]
end
// Vue composable to fetch feature flags from the server
//
// import { useFlipper } from "@/composables/useFlipper.js"
// const { isEnabled } = useFlipper('featurename')
//
// // template
// <div v-if="isEnabled">…</div>
//
import { useFetch } from '@vueuse/core'
import { reactive, computed } from 'vue'
const fetch = reactive(useFetch('flipper', { immediate: false }).get().json())
export function useFlipper (feature, defaultValue = false) {
// Fetch flipper data if it hasn't been fetched yet
if (!fetch.isFetching && !fetch.isFinished) fetch.execute()
return {
isEnabled: computed(() => fetch.data?.[feature] ?? defaultValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment