Class: Utopia::Controller::Respond::Responder

Inherits:
Object
  • Object
show all
Defined in:
lib/utopia/controller/respond.rb

Constant Summary collapse

HTTP_ACCEPT =
'HTTP_ACCEPT'.freeze
NOT_ACCEPTABLE_RESPONSE =
[406, {}, []].freeze

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Responder

Returns a new instance of Responder.



118
119
120
# File 'lib/utopia/controller/respond.rb', line 118

def initialize
  @converters = HTTP::Accept::MediaTypes::Map.new
end

Instance Method Details

#call(context, request, path, response) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/utopia/controller/respond.rb', line 142

def call(context, request, path, response)
  # Parse the list of browser preferred content types and return ordered by priority:
  media_types = HTTP::Accept::MediaTypes.browser_preferred_media_types(request.env)
  
  converter, media_range = @converters.for(media_types)
  
  if converter
    converter.call(context, response, media_range)
  else
    NOT_ACCEPTABLE_RESPONSE
  end
end

#freeze ⇒ Object



122
123
124
125
126
# File 'lib/utopia/controller/respond.rb', line 122

def freeze
  @converters.freeze
  
  super
end

#with(content_type, &block) ⇒ Object

Add a converter for the specified content type. Call the block with the response content if the request accepts the specified content_type.



129
130
131
# File 'lib/utopia/controller/respond.rb', line 129

def with(content_type, &block)
  @converters << Converter::Callback.new(content_type, block)
end

#with_json ⇒ Object

Add a converter for JSON when requests accept 'application/json'



138
139
140
# File 'lib/utopia/controller/respond.rb', line 138

def with_json
  @converters << Converter::ToJSON
end

#with_passthrough ⇒ Object



133
134
135
# File 'lib/utopia/controller/respond.rb', line 133

def with_passthrough
  @converters << Passthrough
end