Class: Fleximage::LegacyView

Inherits:
Object
  • Object
show all
Defined in:
lib/fleximage/legacy_view.rb

Overview

Renders a .flexi template

Defined Under Namespace

Classes: TemplateDidNotReturnImage

Instance Method Summary collapse

Constructor Details

#initialize(view) ⇒ LegacyView

Returns a new instance of LegacyView.



8
9
10
# File 'lib/fleximage/legacy_view.rb', line 8

def initialize(view)
  @view = view
end

Instance Method Details

#render(template, local_assigns = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
60
61
# File 'lib/fleximage/legacy_view.rb', line 12

def render(template, local_assigns = {})
  # process the view
  result = @view.instance_eval do
    
    # Shorthand color creation
    def color(*args)
      if args.size == 1 && args.first.is_a?(String)
        args.first
      else
        Magick::Pixel.new(*args)
      end
    end
    
    # inject assigns into instance variables
    assigns.each do |key, value|
      instance_variable_set "@#{key}", value
    end
    
    # inject local assigns into reader methods
    local_assigns.each do |key, value|
      class << self; self; end.send(:define_method, key) { value }
    end
    
    #execute the template
    eval(template)
  end
  
  # Raise an error if object returned from template is not an image record
  unless result.class.include?(Fleximage::Model::InstanceMethods)
    raise TemplateDidNotReturnImage, ".flexi template was expected to return a model instance that acts_as_fleximage, but got an instance of <#{result.class}> instead."
  end
  
  # Figure out the proper format
  requested_format = (@view.params[:format] || :jpg).to_sym
  raise 'Image must be requested with an image type format.  jpg, gif and png only are supported.' unless [:jpg, :gif, :png].include?(requested_format)
  
  # Set proper content type
  @view.controller.headers["Content-Type"] = Mime::Type.lookup_by_extension(requested_format.to_s).to_s
  
  # get rendered result
  rendered_image = result.output_image(:format => requested_format)
  
  # Return image data
  return rendered_image
ensure

  # ensure garbage collection happens after every flex image render
  rendered_image.dispose!
  GC.start
end