Class: SvgExport::SvgTransformer

Inherits:
Object
  • Object
show all
Defined in:
app/services/svg_export/svg_transformer.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_url, options = {}) ⇒ SvgTransformer

Returns a new instance of SvgTransformer.



3
4
5
6
# File 'app/services/svg_export/svg_transformer.rb', line 3

def initialize(base_url, options={})
  @tempfiles = []
  @base_url = options[:base_url]
end

Instance Method Details

#transform(svg) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/services/svg_export/svg_transformer.rb', line 8

def transform(svg)
  doc = Nokogiri::XML.parse(svg)
  doc.search('image').each do |image|
    if image['xlink:href'] and image['xlink:href'][/^\//]
      if image['xlink:href'][%r{/assets/([^\?]+)}, 1] and path = find_asset_path($1)
        # local Asset path
        body = File.read(path)
        url = path
      elsif @base_url
        url = URI.join(@base_url, image['xlink:href']).to_s
        body = download(url)
      else
        next
      end

      ext =  url[/\.(\w+)$/, 1] || 'png'
      tf = Tempfile.new(["highchart-tmp-inline", ".#{ext}", Rails.root.join('tmp')])
      tf.binmode
      @tempfiles << tf
      tf.write(body)
      tf.flush
      # relative url
      image['xlink:href'] = "file://" + tf.path
    end
  end
  doc.to_s
end