Class: ActionController::MimeResponds::Responder

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

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(controller) ⇒ Responder

Returns a new instance of Responder.


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

def initialize(controller)
  @controller = controller
  @request    = controller.request
  @response   = controller.response

  if ActionController::Base.use_accept_header
    @mime_type_priority = Array(Mime::Type.lookup_by_extension(@request.parameters[:format]) || @request.accepts)
  else
    @mime_type_priority = [@request.format]
  end

  @order     = []
  @responses = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, &block) ⇒ Object


147
148
149
150
151
152
153
154
155
# File 'lib/action_controller/mime_responds.rb', line 147

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


139
140
141
142
143
144
145
# File 'lib/action_controller/mime_responds.rb', line 139

def any(*args, &block)
  if args.any?
    args.each { |type| send(type, &block) }
  else
    custom(@mime_type_priority.first, &block)
  end
end

#custom(mime_type, &block) ⇒ Object


127
128
129
130
131
132
133
134
135
136
137
# 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

  @responses[mime_type] ||= Proc.new do
    @response.template.template_format = mime_type.to_sym
    @response.content_type = mime_type.to_s
    block_given? ? block.call : @controller.send(:render, :action => @controller.action_name)
  end
end

#respondObject


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

def respond
  for priority in @mime_type_priority
    if priority == Mime::ALL
      @responses[@order.first].call
      return
    else
      if @responses[priority]
        @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
    @controller.send :head, :not_acceptable
  end
end