Skip to content

Commit

Permalink
Merge pull request rails#8085 from acapilleri/format_never_nil
Browse files Browse the repository at this point in the history
if format is unknown NullMimeTypeObject is returned
  • Loading branch information
guilleiguaran committed Dec 22, 2012
2 parents 8a39d83 + c2267db commit cba0588
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 3 deletions.
5 changes: 5 additions & 0 deletions actionpack/CHANGELOG.md
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##

* Added `Mime::NullType` class. This allows to use html?, xml?, json?..etc when
the `format` of `request` is unknown, without raise an exception.

*Angelo Capilleri*

* Integrate the Journey gem into Action Dispatch so that the global namespace
is not polluted with names that may be used as models.

Expand Down
13 changes: 12 additions & 1 deletion actionpack/lib/action_dispatch/http/mime_type.rb
Expand Up @@ -27,7 +27,7 @@ def #{method}(*)
class << self
def [](type)
return type if type.is_a?(Type)
Type.lookup_by_extension(type)
Type.lookup_by_extension(type) || NullType.new
end

def fetch(type)
Expand Down Expand Up @@ -306,6 +306,17 @@ def respond_to_missing?(method, include_private = false) #:nodoc:
method.to_s.ends_with? '?'
end
end

class NullType
def nil?
true
end

private
def method_missing(method, *args)
false if method.to_s.ends_with? '?'
end
end
end

require 'action_dispatch/http/mime_types'
2 changes: 1 addition & 1 deletion actionpack/test/controller/send_file_test.rb
Expand Up @@ -144,7 +144,7 @@ def test_send_file_headers_with_bad_symbol
}

@controller.headers = {}
assert_raise(ArgumentError){ @controller.send(:send_file_headers!, options) }
assert !@controller.send(:send_file_headers!, options)
end

def test_send_file_headers_guess_type_from_extension
Expand Down
11 changes: 10 additions & 1 deletion actionpack/test/dispatch/request_test.rb
Expand Up @@ -591,9 +591,18 @@ def url_for(options = {})

request = stub_request
request.expects(:parameters).at_least_once.returns({ :format => :unknown })
assert request.formats.empty?
assert_instance_of Mime::NullType, request.format
end

test "format is not nil with unknown format" do
request = stub_request
request.expects(:parameters).at_least_once.returns({ format: :hello })
assert_equal request.format.nil?, true
assert_equal request.format.html?, false
assert_equal request.format.xml?, false
assert_equal request.format.json?, false
end

test "formats with xhr request" do
request = stub_request 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
request.expects(:parameters).at_least_once.returns({})
Expand Down

0 comments on commit cba0588

Please sign in to comment.