Class: HeyYou::Sender

Inherits:
Object
  • Object
show all
Extended by:
Helper
Includes:
Helper
Defined in:
lib/hey_you/sender.rb

Defined Under Namespace

Classes: NotRegisteredReceiver

Class Method Summary collapse

Methods included from Helper

config

Class Method Details

.send!(notification_key, receiver, **options) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/hey_you/sender.rb', line 30

def send!(notification_key, receiver, **options)
  to_hash = {}
  receiver.class.receiver_channels.each do |ch|
    if !options[:force] && !receiver.public_send("#{ch}_ch_receive_condition")
      next
    end

    to_hash[ch] = {
      # Fetch receiver's info for sending: phone_number, email, etc
      subject: receiver.public_send("#{ch}_ch_receive_info"),
      # Fetch receiver's options like :mailer_class
      options: receiver.public_send("#{ch}_ch_receive_options").merge(options) || {}
    }
  end

  send_to_receive_info(notification_key, to_hash, **options)
end

.send_to(receiver, notification_key, **options) ⇒ Object

Send notifications for receiver



20
21
22
23
24
25
26
27
28
# File 'lib/hey_you/sender.rb', line 20

def send_to(receiver, notification_key, **options)
  unless receiver_valid?(receiver)
    raise NotRegisteredReceiver, "Class '#{receiver.class}' not registered as receiver"
  end

  result = send!(notification_key, receiver, **options)
  config.log("Sender result: #{result}")
  result
end

.send_to_receive_info(notification_key, receive_info, **options) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/hey_you/sender.rb', line 48

def send_to_receive_info(notification_key, receive_info, **options)
  builder = Builder.new(notification_key, **options)
  response = {}
  config.registered_channels.each do |ch|
    if channel_allowed?(ch, receive_info, builder, **options) && builder.respond_to?(ch) && builder.public_send(ch)
      config.log(
        "Send #{ch}-message to `#{receive_info[ch][:subject]}` with data: #{builder.public_send(ch).data}" \
        " and options: #{receive_info[ch][:options]}"
      )
      receive_options = receive_info[ch].fetch(:options, {}) || {}
      klass_name = ch.to_s.downcase.split('_').map(&:capitalize).join
      response[ch] = Channels.const_get(klass_name).send!(
        builder, to: receive_info[ch][:subject], **receive_options
      )
    else
      config.log("Channel #{ch} not allowed or sending condition doesn't return truthy result.")
    end
  end
  response
end