Module: Hg::Chunk

Defined in:
lib/hg/chunk.rb

Defined Under Namespace

Modules: ClassMethods, Initializer

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/hg/chunk.rb', line 5

def self.included(base)
  base.extend ClassMethods
  base.prepend Initializer
  base.id = base.to_s
  base.deliverables = []
  base.dynamic = false
  base.add_to_chunks
  base.include_chunks
end

Instance Method Details

#contextOpenStruct

Returns The execution context for this chunk instance.

Returns:

  • (OpenStruct)

    The execution context for this chunk instance.



16
17
18
# File 'lib/hg/chunk.rb', line 16

def context
  @memoized_context ||= @context
end

#deliverObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/hg/chunk.rb', line 20

def deliver
  Sidekiq::Logging.logger.info 'DELIVERABLES'
  self.class.deliverables.each do |deliverable|
    if deliverable.is_a? Hash
      Sidekiq::Logging.logger.info JSON.pretty_generate(deliverable)
    else
      Sidekiq::Logging.logger.info deliverable.inspect
    end
  end
  Sidekiq::Logging.logger.info 'RECIPIENT'
  Sidekiq::Logging.logger.info @recipient.inspect

  self.class.deliverables.each do |deliverable|
    # If another chunk...
    if deliverable.is_a? Class
      # ...deliver the chunk.
      deliverable.new(recipient: @recipient, context: context).deliver
    # If dynamic, then it needs to be evaluated at delivery time.
    elsif deliverable.is_a? Proc
      # Create a `template` anonymous subclass of the chunk class.
      template = Class.new(self.class)
      template.deliverables = []

      # Evaluate the dynamic block within it.
      template.class_exec(context, &deliverable)

      # Deliver the chunk.
      template.new(recipient: @recipient, context: context).deliver

    # Otherwise, it's just a raw message.
    else
      # Deliver the message
      response = Facebook::Messenger::Bot.deliver(deliverable.merge(recipient: @recipient), access_token: ENV['FB_ACCESS_TOKEN'])

      # Send to Chatbase if env var present
      if ENV['CHATBASE_API_KEY']
        ChatbaseAPIClient.new.send_bot_message(deliverable, response)
      end
    end
  end
end