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 48 lines (39 sloc) 1.571 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
module Fleximage
  
  # Renders a .flexi template
  class View < ActionView::TemplateHandler #:nodoc:
    class TemplateDidNotReturnImage < RuntimeError #:nodoc:
    end
    
    def render(template)
      # 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
        
        #execute the template
        eval(template.source)
      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
      unless [:jpg, :gif, :png].include?(requested_format)
        raise 'Image must be requested with an image type format. jpg, gif and png only are supported.'
      end
      
      # Set proper content type
      @view.controller.response.content_type = Mime::Type.lookup_by_extension(requested_format.to_s).to_s
      
      # return rendered result
      return result.output_image(:format => requested_format)
    ensure
    
      # ensure garbage collection happens after every flex image render
      GC.start
    end
  end
end