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



59
60
61
# File 'lib/concerns_on_rails/models/activatable.rb', line 59

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

#active?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/concerns_on_rails/models/activatable.rb', line 51

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

#deactivate!Object



63
64
65
# File 'lib/concerns_on_rails/models/activatable.rb', line 63

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

#inactive?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/concerns_on_rails/models/activatable.rb', line 55

def inactive?
  !active?
end

#toggle_active!Object



67
68
69
70
71
# File 'lib/concerns_on_rails/models/activatable.rb', line 67

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