Class: Fleximage::View

Inherits:
ActionView::TemplateHandler
  • Object
show all
Defined in:
lib/fleximage/view.rb

Overview

Renders a .flexi template

Defined Under Namespace

Classes: TemplateDidNotReturnImage

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(action_view) ⇒ View

Returns a new instance of View.



12
13
14
# File 'lib/fleximage/view.rb', line 12

def initialize(action_view)
  @view = action_view
end

Class Method Details

.call(template) ⇒ Object



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

def self.call(template)
  "Fleximage::View.new(self).render(template)"
end

Instance Method Details

#render(template) ⇒ Object



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
# File 'lib/fleximage/view.rb', line 16

def render(template)
  # process the view
  result = @view.instance_eval do
    
    # Shorthand color creation
    def color(*args)
      Fleximage::Operator::Base.color(*args)
    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
  
  # Set proper caching headers
  if defined?(Rails) && Rails.env == 'production'
    @view.controller.response.headers['Cache-Control'] = 'public, max-age=86400'
  end
  
  # return rendered result
  return result.output_image(:format => requested_format)
ensure

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