scratch/lib/ultraviolet.rb

37 lines
1.1 KiB
Ruby
Raw Normal View History

2010-03-12 13:22:16 +00:00
class UltraVioletFilter < Nanoc3::Filter
identifier :ultraviolet
2010-09-21 14:52:25 +00:00
def protect(str)
str.gsub(%r{<([^>]*)>}) do
"&lt;#{$1}&gt;"
end
end
2010-03-12 13:22:16 +00:00
def run(content, params={})
require 'rubygems'
code_rule = %r{(<code class="([^"]+?)"( file="([^"]+?)")?>\n?(.+?)</code>)}m
2010-09-21 14:52:25 +00:00
new_content=content.gsub(code_rule) do |full|
@full, @lang, @filename, @code = $1, $2, $4, $5
2010-09-21 19:13:12 +00:00
@codeprefix=''
if not @filename.nil? and @filename != ""
create_file_for_code
end
@codeprefix+"\n\n<pre><code class=\"#{@lang}\">"+protect(@code)+"</code></pre>\n\n"
2010-09-21 14:52:25 +00:00
end
return new_content
2010-03-12 13:22:16 +00:00
end
private
2010-09-21 19:13:12 +00:00
def create_file_for_code
# Create a plaintext file version for download.
webpath = @item.path
url = webpath + 'code/' + @filename
@codeprefix=%{<div class="codefile"><a href="#{url}">&#x27A5; #{@filename}</a></div>\n}
2010-09-21 19:13:12 +00:00
code_path = "output#{webpath}code"
FileUtils.mkdir_p code_path
File.open(%{#{code_path}/#{@filename}}, 'w'){|f|f.write(@code)}
2010-03-12 13:22:16 +00:00
end
end