Class: Sdk4me::Attachments

Inherits:
Object
  • Object
show all
Defined in:
lib/sdk4me/client/attachments.rb

Constant Summary collapse

S3_PROVIDER =
's3'.freeze
FILENAME_TEMPLATE =
'${filename}'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(client, path) ⇒ Attachments

Returns a new instance of Attachments.



6
7
8
9
# File 'lib/sdk4me/client/attachments.rb', line 6

def initialize(client, path)
  @client = client
  @path = path
end

Instance Method Details

#upload_attachments!(data) ⇒ Object

Upload attachments and replace the data inline with the uploaded attachments info.

To upload field attachments:

* data[:note_attachments] = ['/tmp/test.doc', '/tmp/test.log']

To upload inline images:

* data[:note] containing text referring to inline images in
  data[:note_attachments] by their array index, with the index being
  zero-based. Text can only refer to inline images in its own
  attachments collection. For example:

    data = {
      note: "Hello [note_attachments: 0] and [note_attachments: 1]",
      note_attachments: ['/tmp/jip.png', '/tmp/janneke.png'],
      ...
    }

After calling this method the data that will be posted to update the 4me record would look similar to:

data = {
  note: "Hello ![](storage/abc/adjhajdhjaadf.png) and ![](storage/abc/fskdhakjfkjdssdf.png])",
  note_attachments: [
    { key: 'storage/abc/adjhajdhjaadf.png', filesize: 12345, inline: true },
    { key: 'storage/abc/fskdhakjfkjdssdf.png'], filesize: 98765, inline: true }
  ],
  ...
}


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/sdk4me/client/attachments.rb', line 40

def upload_attachments!(data)
  # Field attachments
  field_attachments = []
  data.each do |field, value|
    next unless field.to_s.end_with?('_attachments')
    next unless value.is_a?(Enumerable) && value.any?

    value.map! { |attachment| upload_attachment(attachment) }.compact!
    field_attachments << field if value.any?
  end

  # Rich text inline attachments
  field_attachments.each do |field_attachment|
    field = field_attachment.to_s.sub(/_attachments$/, '')
    value = data[field.to_sym] || data[field]
    next unless value.is_a?(String)

    value.gsub!(/\[#{field_attachment}:\s?(\d+)\]/) do |match|
      idx = Regexp.last_match(1).to_i
      attachment = data[field_attachment][idx]
      if attachment
        attachment[:inline] = true
        "![](#{attachment[:key]})" # magic markdown for inline attachments
      else
        match
      end
    end
  end
end