Introducing Rails Vault: simple to add settings to any ActiveRecord model
Rails Designer

Rails Designer @railsdesigner

About: I help teams around the world make their Rails apps a bit nicer to maintain and look at. 🎨 Also kickstart SaaS' in a month. 👷 And built a Rails UI Components library, used by 1000+ developers. 🚀

Location:
Amsterdam, The Netherlands
Joined:
Sep 29, 2023

Introducing Rails Vault: simple to add settings to any ActiveRecord model

Publish Date: Feb 20
2 0

This article was originally published on Rails Designer


When you build advanced UI's for your Saas there will be a point you need to store certain preferences of appearance settings, like:

  • synced light- and dark-theme;
  • expand/collapsed state for navigation items;
  • time zone.

And so on. I've come across this use cases in every app I built. For a long time I used a set up like described in this article. But ever since I published it, and even including a template to get the required code in your app, I got questions if it wasn't better as a gem.

So after about 10 months, here is: Rails Vault.

Rails Vault is a simple gem to add settings and preferences to any ActiveRecord model. The goal is to keep it simple and light-weight. Let's check out how it works.

Installation is just three lines:

bundle add rails_vault
rails generate rails_vault:install
rails db:migrate
Enter fullscreen mode Exit fullscreen mode

Then you can create a vault for any ActiveRecord model. The convention is the vaults are stored in the model's namespace. So when running:

rails generate rails_vault:add User::Preferences \
  time_zone:string \
  datetime_format:string \
  hotkeys_disabled:boolean
Enter fullscreen mode Exit fullscreen mode

This create the following class:

# app/models/user/preferences.rb
class User::Preferences < RailsVault::Base
  vault_attribute :time_zone, :string
  vault_attribute :datetime_format, :string
  vault_attribute :hotkeys_disabled, :boolean
end
Enter fullscreen mode Exit fullscreen mode

Preferences are created with User.first.create_preferences.

You can also set any default value as well:

# app/models/user/preferences.rb
class User::Preferences < RailsVault::Base
  vault_attribute :time_zone, :string, default: "UTC"
  vault_attribute :datetime_format, :string, default: "dd-mm-yyyy"
  vault_attribute :hotkeys_disabled, :boolean, default: false
end
Enter fullscreen mode Exit fullscreen mode

Have ideas or suggestions? Feel free to create a PR.

Comments 0 total

    Add comment