Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

added Syntaxily.available_lexers method, raising LexerNotFound when i…

…t isn't found for String#syntaxify
  • Loading branch information...
commit 3cad536f15dcc179a457996d3c4d3d84f8d787fb 1 parent abe2390
@nakajima authored
View
4 lib/core_ext/string.rb
@@ -1,5 +1,9 @@
class String
def syntaxify(lexer)
+ unless Syntaxily.available_lexers.include?(lexer.to_s)
+ raise Syntaxily::LexerNotFound.new("No `#{lexer}` lexer found.")
+ end
+
Albino.new(self, lexer).colorize
end
end
View
20 lib/syntaxily.rb
@@ -8,13 +8,29 @@
require 'string'
module Syntaxily
+ class LexerNotFound < StandardError; end
+
def self.parse(text)
doc = Nokogiri::HTML.parse(text)
doc.search('pre.code').each do |node|
lexer = node['rel']
- lexed = node.text.syntaxify(lexer)
- node.replace Nokogiri::HTML.parse(lexed)
+ begin
+ lexed = node.text.syntaxify(lexer)
+ node.replace Nokogiri::HTML.parse(lexed)
+ rescue LexerNotFound
+ next
+ end
end
doc.to_html
end
+
+ def self.available_lexers
+ @available_lexers ||= begin
+ `pygmentize -L`.split(/\n\n/)[1] \
+ .split(/\n/) \
+ .select { |line| line =~ /^\*/ } \
+ .map { |line| line.gsub(/\* ([^:]+):/, '\1') } \
+ .join(', ')
+ end
+ end
end
View
20 spec/syntaxily_spec.rb
@@ -13,6 +13,13 @@
end
end
+ describe "available lexers" do
+ it "finds available lexers from pygments" do
+ Syntaxily.available_lexers.should include('ruby')
+ Syntaxily.available_lexers.should_not include('foobar')
+ end
+ end
+
describe "regular string helper" do
def render
"def foo; :bar end".syntaxify(:ruby)
@@ -24,6 +31,12 @@ def render
result.should have(1).keywords.with_text('end')
result.should have(1).symbols.with_text(':bar')
end
+
+ it "raises LexerNotFound when lexer doesn't exist" do
+ proc {
+ "def foo; :bar end".syntaxify(:foobar)
+ }.should raise_error(Syntaxily::LexerNotFound)
+ end
end
describe "rendering from markup" do
@@ -45,5 +58,12 @@ def render
result.should have(1).keywords.with_text('end')
result.should have(1).symbols.with_text(':bar')
end
+
+ it "rescues LexerNotFound errors" do
+ proc {
+ string = %(<pre class="code" rel="foobar">Something</pre>)
+ Syntaxily.parse(string)
+ }.should_not raise_error
+ end
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.