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



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

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

#active?Boolean

Returns:

  • (Boolean)


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

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

#deactivate!Object



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

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

#inactive?Boolean

Returns:

  • (Boolean)


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

def inactive?
  !active?
end

#toggle_active!Object



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

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