Class: ActionController::MimeResponds::Responder

Inherits:
Object
  • Object
show all
Defined in:
lib/action_controller/mime_responds.rb

Overview

:nodoc:

Constant Summary collapse

DEFAULT_BLOCKS =
[:html, :js, :xml].inject({}) do |blocks, ext|
  template_extension = (ext == :html ? '' : ".r#{ext}")
  blocks.update ext => %(Proc.new { render :action => "\#{action_name}#{template_extension}", :content_type => Mime::#{ext.to_s.upcase} })
end

Instance Method Summary collapse

Constructor Details

#initialize(block_binding) ⇒ Responder

Returns a new instance of Responder.



115
116
117
118
119
120
121
122
123
124
125
# File 'lib/action_controller/mime_responds.rb', line 115

def initialize(block_binding)
  @block_binding = block_binding
  @mime_type_priority = eval(
    "(params[:format] && Mime::EXTENSION_LOOKUP[params[:format]]) ? " +
    "[ Mime::EXTENSION_LOOKUP[params[:format]] ] : request.accepts", 
    block_binding
  )

  @order     = []
  @responses = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, &block) ⇒ Object



150
151
152
153
154
155
156
157
158
# File 'lib/action_controller/mime_responds.rb', line 150

def method_missing(symbol, &block)
  mime_constant = symbol.to_s.upcase
  
  if Mime::SET.include?(Mime.const_get(mime_constant))
    custom(Mime.const_get(mime_constant), &block)
  else
    super
  end
end

Instance Method Details

#any(*args, &block) ⇒ Object



146
147
148
# File 'lib/action_controller/mime_responds.rb', line 146

def any(*args, &block)
  args.each { |type| send(type, &block) }
end

#custom(mime_type, &block) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/action_controller/mime_responds.rb', line 127

def custom(mime_type, &block)
  mime_type = mime_type.is_a?(Mime::Type) ? mime_type : Mime::Type.lookup(mime_type.to_s)
  
  @order << mime_type
  
  if block_given?
    @responses[mime_type] = Proc.new do
      eval "response.content_type = '#{mime_type.to_s}'", @block_binding
      block.call
    end
  else
    if source = DEFAULT_BLOCKS[mime_type.to_sym]
      @responses[mime_type] = eval(source, @block_binding)
    else
      raise ActionController::RenderError, "Expected a block but none was given for custom mime handler #{mime_type}"
    end
  end
end

#respondObject



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/action_controller/mime_responds.rb', line 160

def respond
  for priority in @mime_type_priority
    if priority == Mime::ALL
      @responses[@order.first].call
      return
    else
      if priority === @order
        @responses[priority].call
        return # mime type match found, be happy and return
      end
    end
  end
  
  if @order.include?(Mime::ALL)
    @responses[Mime::ALL].call
  else
    eval 'render(:nothing => true, :status => "406 Not Acceptable")', @block_binding
  end
end