Module: Jets::Event::Helpers::S3Event

Extended by:
Memoist
Included in:
Base
Defined in:
lib/jets/event/helpers/s3_event.rb

Defined Under Namespace

Classes: NamedFile

Instance Method Summary collapse

Instance Method Details

#s3_eventsObject



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/jets/event/helpers/s3_event.rb', line 5

def s3_events
  encoded_messages = event[:Records].map do |record|
    record[:Sns][:Message] # SNS message is JSON
  end
  # Decode the JSON messages
  messages = encoded_messages.map do |message|
    data = JSON.load(message)
    ActiveSupport::HashWithIndifferentAccess.new(data)
  end
  # Extract the S3 event records
  messages.map do |message|
    message[:Records].map do |record|
      ActiveSupport::HashWithIndifferentAccess.new(record)
    end
  end.flatten
end

#s3_events?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/jets/event/helpers/s3_event.rb', line 22

def s3_events?
  event[:Records]&.any? { |r| r.dig(:Sns, :Message) }
end

#s3_filesObject

Downloads the s3 object and returns a Ruby File-like handle to the object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/jets/event/helpers/s3_event.rb', line 37

def s3_files
  s3_events.map do |event|
    bucket = event[:s3][:bucket][:name]
    object_key = event[:s3][:object][:key]

    s3 = Aws::S3::Resource.new
    obj = s3.bucket(bucket).object(object_key)

    file_path = "/tmp/s3_files/#{object_key}"
    FileUtils.mkdir_p(File.dirname(file_path))
    File.open(file_path, "w") do |file|
      obj.get(response_target: file)
    end

    file = File.open(file_path, "r")
    NamedFile.new(file, object_key)
  end
end

#s3_objectsObject



26
27
28
29
30
# File 'lib/jets/event/helpers/s3_event.rb', line 26

def s3_objects
  s3_events.map do |record|
    record[:s3][:object]
  end
end

#s3_objects?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/jets/event/helpers/s3_event.rb', line 32

def s3_objects?
  s3_events.any? { |r| r.dig(:s3, :object) }
end