mime-types/ruby-mime-types

MIME::Types[/regex/]: Exception thrown for unmatched regex

TheDeepestSpace opened this issue · 2 comments

MIME::Types[/regex_that_wont_match/]
=> NoMethodError: undefined method `sort' for nil:NilClass
        from /var/lib/gems/2.3.0/gems/mime-types-3.1/lib/mime/types.rb:132:in `[]'
        from /var/lib/gems/2.3.0/gems/mime-types-3.1/lib/mime/types/registry.rb:13:in `[]'
    ...

looks like match function returns nil when no matches were found:

def match(pattern)
@type_variants.select { |k, _|
k =~ pattern
}.values.inject(:+)
end

to be more specific:

[].inject(:+)
=> nil

nil value then gets assigned to matches variable:

matches = case type_id
when MIME::Type
@type_variants[type_id.simplified]
when Regexp
match(type_id)
else
@type_variants[MIME::Type.simplified(type_id)]
end
prune_matches(matches, complete, registered).sort { |a, b|
a.priority_compare(b)
}

then matches gets passed to prune_matches function, that would also return nil if matches parameter is set to nil:
def prune_matches(matches, complete, registered)
matches.delete_if { |e| !e.complete? } if complete
matches.delete_if { |e| !e.registered? } if registered
matches
end

a sort function is called on the returned nil, producing the error here:
prune_matches(matches, complete, registered).sort { |a, b|

Related to #117 and #127.

Resolved with edf3cd7.