mirror of
https://github.com/KevinMidboe/linguist.git
synced 2025-12-08 20:38:47 +00:00
Make Language methods more resilient to non-String input (#3752)
* Add failing test for finding with non-String input Show the failing behaviour of find_by_alias, find_by_name, and [] when non-String input is provided. * Return nil rather than erroring on non-String input
This commit is contained in:
@@ -109,7 +109,7 @@ module Linguist
|
|||||||
#
|
#
|
||||||
# Returns the Language or nil if none was found.
|
# Returns the Language or nil if none was found.
|
||||||
def self.find_by_name(name)
|
def self.find_by_name(name)
|
||||||
return nil if name.to_s.empty?
|
return nil if !name.is_a?(String) || name.to_s.empty?
|
||||||
name && (@name_index[name.downcase] || @name_index[name.split(',').first.downcase])
|
name && (@name_index[name.downcase] || @name_index[name.split(',').first.downcase])
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -124,7 +124,7 @@ module Linguist
|
|||||||
#
|
#
|
||||||
# Returns the Language or nil if none was found.
|
# Returns the Language or nil if none was found.
|
||||||
def self.find_by_alias(name)
|
def self.find_by_alias(name)
|
||||||
return nil if name.to_s.empty?
|
return nil if !name.is_a?(String) || name.to_s.empty?
|
||||||
name && (@alias_index[name.downcase] || @alias_index[name.split(',').first.downcase])
|
name && (@alias_index[name.downcase] || @alias_index[name.split(',').first.downcase])
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -214,7 +214,7 @@ module Linguist
|
|||||||
#
|
#
|
||||||
# Returns the Language or nil if none was found.
|
# Returns the Language or nil if none was found.
|
||||||
def self.[](name)
|
def self.[](name)
|
||||||
return nil if name.to_s.empty?
|
return nil if !name.is_a?(String) || name.to_s.empty?
|
||||||
|
|
||||||
lang = @index[name.downcase]
|
lang = @index[name.downcase]
|
||||||
return lang if lang
|
return lang if lang
|
||||||
|
|||||||
@@ -270,6 +270,12 @@ class TestLanguage < Minitest::Test
|
|||||||
assert_nil Language[""]
|
assert_nil Language[""]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_does_not_blow_up_with_non_string_lookup
|
||||||
|
assert_nil Language.find_by_alias(true)
|
||||||
|
assert_nil Language.find_by_name(true)
|
||||||
|
assert_nil Language[true]
|
||||||
|
end
|
||||||
|
|
||||||
def test_name
|
def test_name
|
||||||
assert_equal 'Perl', Language['Perl'].name
|
assert_equal 'Perl', Language['Perl'].name
|
||||||
assert_equal 'Python', Language['Python'].name
|
assert_equal 'Python', Language['Python'].name
|
||||||
|
|||||||
Reference in New Issue
Block a user