Class: CommandTower::Messaging::Preferences::PreferenceState

Inherits:
Data
  • Object
show all
Defined in:
app/services/command_tower/messaging/preferences/preference_state.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#channelsObject (readonly)

Returns the value of attribute channels

Returns:

  • (Object)

    the current value of channels



6
7
8
# File 'app/services/command_tower/messaging/preferences/preference_state.rb', line 6

def channels
  @channels
end

#inboxObject (readonly)

Returns the value of attribute inbox

Returns:

  • (Object)

    the current value of inbox



6
7
8
# File 'app/services/command_tower/messaging/preferences/preference_state.rb', line 6

def inbox
  @inbox
end

Class Method Details

.from_declaration_default(default_preference_state) ⇒ Object



37
38
39
# File 'app/services/command_tower/messaging/preferences/preference_state.rb', line 37

def self.from_declaration_default(default_preference_state)
  normalize(default_preference_state) || new(channels: {}.freeze, inbox: nil).freeze
end

.normalize(raw) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/services/command_tower/messaging/preferences/preference_state.rb', line 7

def self.normalize(raw)
  return nil if raw.nil?

  unless raw.respond_to?(:to_h)
    raise InvalidPreferenceStateError, "preference_state must be a hash-like object"
  end

  hash = raw.to_h.transform_keys(&:to_s)

  if hash.empty?
    return nil
  end

  channels_raw = hash["channels"]
  channels =
    if channels_raw.nil?
      {}.freeze
    else
      unless channels_raw.respond_to?(:to_h)
        raise InvalidPreferenceStateError, "preference_state channels must be a hash-like object"
      end

      channels_raw.to_h.transform_keys(&:to_s).transform_values { |value| !!value }.freeze
    end

  inbox = hash.key?("inbox") ? !!hash["inbox"] : nil

  new(channels:, inbox:).freeze
end

Instance Method Details

#channel_enabled?(channel_key, default: true) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
50
51
# File 'app/services/command_tower/messaging/preferences/preference_state.rb', line 47

def channel_enabled?(channel_key, default: true)
  return default unless channels.key?(channel_key)

  channels.fetch(channel_key)
end

#merge_over(base) ⇒ Object



41
42
43
44
45
# File 'app/services/command_tower/messaging/preferences/preference_state.rb', line 41

def merge_over(base)
  merged_channels = base.channels.merge(channels)
  merged_inbox = inbox.nil? ? base.inbox : inbox
  self.class.new(channels: merged_channels.freeze, inbox: merged_inbox).freeze
end

#to_raw_hashObject



53
54
55
56
57
# File 'app/services/command_tower/messaging/preferences/preference_state.rb', line 53

def to_raw_hash
  hash = { "channels" => channels.to_h }
  hash["inbox"] = inbox unless inbox.nil?
  hash
end