Class: DocXify::Element::File

Inherits:
Base
  • Object
show all
Defined in:
lib/docxify/element/file.rb

Constant Summary collapse

PNG_SIGNATURE =
"\x89PNG\r\n\u001A\n".b.freeze
JPEG_START =
"\xFF\xD8".b.freeze
JPEG_END =
"\xFF\xD9".b.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path_or_data) ⇒ File

Returns a new instance of File.



12
13
14
15
# File 'lib/docxify/element/file.rb', line 12

def initialize(file_path_or_data)
  super()
  load_file_data(file_path_or_data)
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



10
11
12
# File 'lib/docxify/element/file.rb', line 10

def data
  @data
end

#filenameObject

Returns the value of attribute filename.



10
11
12
# File 'lib/docxify/element/file.rb', line 10

def filename
  @filename
end

Instance Method Details

#contains_jpeg_image?(data) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/docxify/element/file.rb', line 45

def contains_jpeg_image?(data)
  data[0..1] == JPEG_START && data[-2..] == JPEG_END
end

#contains_png_image?(data) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/docxify/element/file.rb', line 41

def contains_png_image?(data)
  data[0, 8] == PNG_SIGNATURE
end

#load_file_data(file_path_or_data) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/docxify/element/file.rb', line 17

def load_file_data(file_path_or_data)
  if ::File.exist?(file_path_or_data)
    file_path_or_data = ::File.read(file_path_or_data, mode: "rb")
  end

  if contains_png_image?(file_path_or_data)
    @data = file_path_or_data
    @filename = "#{Digest::SHA1.hexdigest(@data)}.png"
  elsif contains_jpeg_image?(file_path_or_data)
    @data = file_path_or_data
    @filename = "#{Digest::SHA1.hexdigest(@data)}.jpg"
  else
    raise ArgumentError.new("Unsupported file type - images must be PNG or JPEG")
  end
end

#referenceObject



33
34
35
# File 'lib/docxify/element/file.rb', line 33

def reference
  "image-#{Digest::SHA1.hexdigest(@data)[0, 8]}"
end

#to_sObject



37
38
39
# File 'lib/docxify/element/file.rb', line 37

def to_s
  "<Relationship Id=\"#{reference}\" Target=\"media/#{filename}\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\"/>"
end