Module: RenderImage

Defined in:
lib/render_image.rb

Overview

Module used to add methods to ActionController::Base

Instance Method Summary collapse

Instance Method Details

#render_image(template = nil, options = {}, assigns = {}) ⇒ Object

Provides image drawing for Rails app controller. Default format is action_name.png in file called action_name.png.xml.erb.

You can use different template name but it has to have extension .format.xml.erb. Passing extension .xml.erb is optional but file has be called with it.

You can optionaly pass options (see below) and assigns too. Assigns is Hash of keys and values which will be accessible from view as variables called as keys names.

Options

:quality

When saving into JPEG format you can pass :quality into options. Valid values are in 0 - 100.

Example

File show.png.xml.erb should looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE dynamic_images PUBLIC "-//malis//dynamic_images//EN" "https://raw.github.com/malis/dynamic_images/master/lib/parsers/xml.dtd">
<dynamic_images>
  <dynamic_image width="500" align="center" background="blue 0.5">
    <text font="Arial bold 20"><%= @article.title %></text>
    <text indent="30"><%= @article.text %></text>
  </dynamic_image>
</dynamic_images>

Attributes save, save_endless and quality will be omitted. You can pass quality in options Hash.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/render_image.rb', line 27

def render_image(template = nil, options = {}, assigns = {})
  template ||= "#{action_name}.png"
  template += ".xml.erb" if template.class == String && template !~ /\.xml\.erb\Z/i
  view_path = nil
  view_paths.each do |v_path|
    v_path = File.join(v_path, controller_path)
    view_path = v_path if File.exists? File.join(v_path, template)
  end
  raise "There is no template #{template} in paths: #{view_paths.join ' '}" unless view_path

  view = ActionView::Base.new(view_path, assigns)
  view.extend ApplicationHelper
  instance_variables.each do |var|
    next if var.to_s !~ /\A@[a-z]/i
    view.instance_variable_set var, instance_variable_get(var)
  end
  xml = view.render(:file => template)

  file = template.sub(/\.xml\.erb\Z/i, '')
  if RUBY_VERSION >= "1.9"
    tempfile = Tempfile.new file, :encoding => 'ascii-8bit'
  else
    tempfile = Tempfile.new file
  end
  options[:format] = file.scan(/\.([a-z0-9]+)\Z/i).flatten.first

  DynamicImageParsers::XmlParser.new xml, tempfile, options

  tempfile.rewind
  send_data tempfile.read, :filename => file, :disposition => 'inline', :type => "image/#{options[:format]}"
  tempfile.close
  tempfile.unlink
end