Simplifying timestamp toggles in Rails
Source: Dev.to
Overview
I often use timestamps, like completed_at, as a boolean flag. It offers a bit more (meta) data than a real boolean, but on the UI you typically want to show a checkbox that a user can toggle instead of a datetime field.
Implementation
A simple concern provides an API such as:
@resource.completed?
@resource.complete!
@resource.complete=
You can then use form.check_box :completed in your forms.
Boolean attribute concern
# 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
Using the concern in a model
class Task < ApplicationRecord
include BooleanAttributes
boolean_attribute :completed
# …
end
Conclusion
It’s these small concerns that make your life a bit easier.
Original article published on Rails Designer’s Build a SaaS Blog.