Skip to content

Instantly share code, notes, and snippets.

@mikker
Last active April 1, 2025 20:22
Show Gist options
  • Save mikker/c435fc6bfcbdf67b60cd12ff96a45ee5 to your computer and use it in GitHub Desktop.
Save mikker/c435fc6bfcbdf67b60cd12ff96a45ee5 to your computer and use it in GitHub Desktop.
Using Bucket.co with Rails (+Stimulus)
<!doctype html>
<html>
<head>
<script>
window.BUCKET_OPTIONS = <%= bucket_options.to_json.html_safe %>
</script>
<%= javascript_include_tag :application %>
</head>
<body>
<!-- ... -->
</body>
</html>
class ApplicationController < ActionController::Base
# ...
helper_method :bucket_options
private
def bucket_options
{
publishable_key: Rails.application.credentials.bucket_publishable_key,
user: { id: current_user&.id },
company: { id: current_company&.id }, # or current_user.id again if you don't have companies
toolbar: Rails.env.development? || current_user&.admin?
}
end
end
import { Controller } from "@hotwired/stimulus";
import { BucketClient } from "@bucketco/browser-sdk";
const bucket = new BucketClient({
...window.BUCKET_OPTS,
host: "https://front-eu.bucket.co",
});
const prom = bucket.initialize();
export default class extends Controller {
static values = {
feature: String,
enabled: { type: Boolean, default: false },
hideIfDisabled: { type: Boolean, default: true },
};
async connect() {
this.initialDisplay = getComputedStyle(this.element).display
this.toggleVisibility()
await prom;
this.update();
addEventListener("turbo:load", this.update);
}
disconnect() {
removeEventListener("turbo:load", this.update);
}
update = () => {
this.enabledValue = bucket.getFeature(this.featureValue).isEnabled;
};
enabledValueChanged = () => {
// Skip initial toggle so we can get initial display value before hiding
if (!this.initialDisplay) return;
if (this.hideIfDisabledValue) {
this.toggleVisibility();
}
};
toggleVisibility = () => {
if (!this.hideIfDisabledValue) return;
if (this.enabledValue) {
this.element.style.display = this.initialDisplay
} else {
this.element.style.display = "none"
}
};
async track() {
await prom;
bucket.track(this.featureValue);
}
}
<!-- This will send a check event to Bucket -->
<div data-controller="bucket" data-bucket-feature-value="myFeature">
<!-- Clicking this will trigger will track as "trying" the feature "myFeature" -->
<a href="..." data-action="bucket#track">Try my feature!</a>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment