public
Description: Rails plugin for uploading images as resources, with support for resizing, text stamping, and other special effects.
Homepage: http://fleximage.rubyforge.org
Clone URL: git://github.com/Squeegy/fleximage.git
fleximage / lib / fleximage / view.rb
100644 62 lines (49 sloc) 1.988 kb
1
2
3
4
5
6
7
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
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
62
module Fleximage
  
  # Renders a .flexi template
  class View #:nodoc:
    class TemplateDidNotReturnImage < RuntimeError #:nodoc:
    end
    
    def initialize(view)
      @view = view
    end
    
    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
      GC.start
    end
  end
end