Class: ReverseAdoc::Converters::Img

Inherits:
Base
  • Object
show all
Defined in:
lib/reverse_adoc/converters/img.rb

Instance Method Summary collapse

Methods inherited from Base

#escape_keychars, #extract_title, #treat, #treat_children

Instance Method Details

#convert(node, state = {}) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/reverse_adoc/converters/img.rb', line 58

def convert(node, state = {})
  alt   = node['alt']
  src   = node['src']
  id = node['id']
  width = node['width']
  height = node['height']
  anchor = id ? "[[#{id}]]\n" : ""
  title = extract_title(node)

  if ReverseAdoc.config.external_images
    # puts "external image conversion #{id}, #{src}"
    src = datauri2file(src)
  end

  title = ".#{title}\n" unless title.empty?
  attrs = alt
  attrs = "\"\"" if (width || height) && alt.nil?
  attrs += ",#{width}" if width
  attrs += ",#{height}" if width && height
  [anchor, title, "image::", src, "[", attrs, "]"].join("")
end

#copy_temp_file(imgdata) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/reverse_adoc/converters/img.rb', line 48

def copy_temp_file(imgdata)
  Tempfile.open(['radoc', '.jpg']) do |f|
    f.binmode
    f.write(Base64.strict_decode64(imgdata))
    f.rewind
    ext = Marcel::MimeType.for(f).sub(%r{^[^/]+/}, "")
    [ext, f.path]
  end
end

#datauri2file(src) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/reverse_adoc/converters/img.rb', line 22

def datauri2file(src)
  %r{^data:image/(?<imgtype>[^;]+);base64,(?<imgdata>.+)$} =~ src

  dest_dir = Pathname.new(ReverseAdoc.config.destination).dirname
  images_dir = dest_dir + 'images'
  FileUtils.mkdir_p(images_dir)

  ext, image_src_path = determine_image_src_path(src, imgdata)
  image_dest_path = images_dir + "#{image_number}.#{ext}"

  # puts "image_dest_path: #{image_dest_path.to_s}"
  # puts "image_src_path: #{image_src_path.to_s}"

  FileUtils.cp(image_src_path, image_dest_path)
  image_number_increment

  image_dest_path.relative_path_from(dest_dir)
end

#determine_image_src_path(src, imgdata) ⇒ Object



41
42
43
44
45
46
# File 'lib/reverse_adoc/converters/img.rb', line 41

def determine_image_src_path(src, imgdata)
  return copy_temp_file(imgdata) if imgdata

  ext = File.extname(src).strip.downcase[1..-1]
  [ext, Pathname.new(ReverseAdoc.config.sourcedir) + src]
end

#image_numberObject



11
12
13
14
15
16
# File 'lib/reverse_adoc/converters/img.rb', line 11

def image_number
  sprintf(
    ReverseAdoc.config.image_counter_pattern,
    ReverseAdoc.config.image_counter
  )
end

#image_number_incrementObject



18
19
20
# File 'lib/reverse_adoc/converters/img.rb', line 18

def image_number_increment
  ReverseAdoc.config.image_counter += 1
end