Module: ConcernsOnRails::Models::Activatable

Extended by:
ActiveSupport::Concern
Defined in:
lib/concerns_on_rails/models/activatable.rb

Overview

Boolean active/inactive toggle backed by a single column.

class Subscription < ApplicationRecord
include ConcernsOnRails::Activatable

activatable_by             # defaults to :active
# activatable_by :enabled  # custom column name
end

Subscription.active     # WHERE active = TRUE
Subscription.inactive   # WHERE active = FALSE OR active IS NULL

NULL is treated as inactive, mirroring how unset booleans behave in most apps.

Note: SoftDeletable also defines a .active scope (alias of .without_deleted). If both concerns are included on the same model, the later one wins.

Constant Summary collapse

DEFAULT_FIELD =
:active

Instance Method Summary collapse

Instance Method Details

#activate!Object



108
109
110
# File 'lib/concerns_on_rails/models/activatable.rb', line 108

def activate!
  update(self.class.activatable_field => true)
end

#active?Boolean

Returns:

  • (Boolean)


100
101
102
# File 'lib/concerns_on_rails/models/activatable.rb', line 100

def active?
  self[self.class.activatable_field] == true
end

#deactivate!Object



112
113
114
# File 'lib/concerns_on_rails/models/activatable.rb', line 112

def deactivate!
  update(self.class.activatable_field => false)
end

#inactive?Boolean

Returns:

  • (Boolean)


104
105
106
# File 'lib/concerns_on_rails/models/activatable.rb', line 104

def inactive?
  !active?
end

#toggle_active!Object



116
117
118
119
120
# File 'lib/concerns_on_rails/models/activatable.rb', line 116

def toggle_active!
  # Lock the row for the read-modify-write so concurrent toggles don't lose
  # an update (with_lock wraps a transaction + SELECT ... FOR UPDATE).
  with_lock { active? ? deactivate! : activate! }
end