DEV Community

Rails Designer
Rails Designer

Posted on • Originally published at railsdesigner.com

Simplifying timestamp toggles in Rails

This article was originally published on Rails Designer's Build a SaaS Blog


I often use timestamps, like completed_at as a boolean flag. It offers just a bit more (meta) data than a real boolean.

But of course on the UI you want to show a checkbox that a user can toggle instead of a datetime field.

I have done this often enough, that I created a simple concern that I use throughout my apps. Given above completed_at example, it gives you an API like:

@resource.completed?
@resource.complete!
@resource.complete=
Enter fullscreen mode Exit fullscreen mode

So in your form, you can simply use form.check_box :completed and you're off.

The concern is simple enough:

# lib/boolean_attributes.rb
module BooleanAttribute
  extend ActiveSupport::Concern

  class_methods do
    def boolean_attribute(*fields)
      fields.each do |field|
        column = :"#{field}_at"

        define_method(field) { public_send(column).present? }

        define_method("#{field}?") { public_send(column).present? }

        define_method("#{field}=") do |value|
          public_send("#{column}=", ActiveModel::Type::Boolean.new.cast(value) ? Time.current : nil)
        end

        define_method("#{field}!") { update!("#{column}": Time.current) }
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

In your model use it like this:

class Task < ApplicationRecord
  include BooleanAttributes

  boolean_attribute :completed

  # …
end
Enter fullscreen mode Exit fullscreen mode

It is just that little concerns that make your life a bit easier.

Top comments (0)