Add Lexer class

This commit is contained in:
Joshua Peek
2011-05-19 23:25:47 -05:00
parent 029def30ce
commit 7b45e5c9f5
2 changed files with 76 additions and 0 deletions

39
lib/linguist/lexer.rb Normal file
View File

@@ -0,0 +1,39 @@
require 'yaml'
module Linguist
class Lexer < Struct.new(:name, :aliases, :filenames, :mimetypes)
@name_index = {}
@alias_index = {}
def self.find_by_name(name)
@name_index[name.downcase]
end
def self.find_by_alias(name)
@alias_index[name.downcase]
end
def self.[](name)
find_by_name(name) || find_by_alias(name)
end
def to_s
aliases.first
end
def ==(other)
eql?(other)
end
def eql?(other)
equal?(other)
end
YAML.load_file(File.expand_path("../lexers.yml", __FILE__)).each do |lexer|
@name_index[lexer.name.downcase] = lexer
lexer.aliases.each do |name|
@alias_index[name.downcase] = lexer
end
end
end
end

37
test/test_lexer.rb Normal file
View File

@@ -0,0 +1,37 @@
require 'linguist/lexer'
require 'test/unit'
class TestLexer < Test::Unit::TestCase
include Linguist
def test_find_by_name
assert_equal Lexer['Ruby'], Lexer.find_by_name('Ruby')
assert_equal Lexer['Ruby'], Lexer.find_by_name('ruby')
assert_equal Lexer['Ruby'], Lexer.find_by_name('RUBY')
end
def test_find_by_alias
assert_equal Lexer['Ruby'], Lexer.find_by_alias('rb')
assert_equal Lexer['Ruby'], Lexer.find_by_alias('ruby')
assert_equal Lexer['Ruby'], Lexer.find_by_alias('duby')
end
def test_name
assert_equal 'Ruby', Lexer['Ruby'].name
assert_equal 'Python', Lexer['Python'].name
assert_equal 'Perl', Lexer['Perl'].name
end
def test_aliases
assert_equal ['rb', 'ruby', 'duby'], Lexer['Ruby'].aliases
assert_equal ['python', 'py'], Lexer['Python'].aliases
assert_equal ['perl', 'pl'], Lexer['Perl'].aliases
end
def test_eql
assert Lexer['Ruby'].eql?(Lexer['Ruby'])
assert !Lexer['Ruby'].eql?(Lexer['Python'])
assert !Lexer['Ruby'].eql?(Lexer.new('Ruby'))
end
end