Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "qerub/singleton_class"
- module TextFilter
- class Error < StandardError
- end
- class << self
- def process(filename, data, variables = {})
- find_filter_chain(filename).inject(data) { |data, filter| filter.process(data, variables) }
- end
- def find_filter_chain(filename)
- basename, *extensions = filename.split(".")
- require("enumerator")
- steps = extensions.reverse.enum_cons(2).to_a
- plugins = TextFilter::Plugin.subclasses
- steps.map do |from, to|
- plugin = plugins.find do |plugin|
- plugin.handles[from] == to
- end
- plugin ||= plugins.find do |plugin|
- plugin.handles[from] == "*"
- end
- if plugin
- next plugin
- else
- raise Error, "Could not find a TextFilter plugin for converting from #{from} to #{to}"
- end
- end
- end
- end
- class Plugin
- class << self
- def subclasses
- @subclasses ||= []
- end
- def inherited(klass)
- subclasses << klass
- end
- def process(*args)
- new.filter(*args)
- end
- def handles
- @handles ||= {}
- end
- def handles=(value)
- @handles = value
- end
- end
- end
- class Context
- def initialize(env)
- env.each do |key, value|
- singleton_class.instance_eval do
- define_method(key) { value }
- end
- end
- end
- def context_binding
- binding
- end
- end
- module Plugins
- class TextileFilter < Plugin
- self.handles = { "textile" => "html" }
- def filter(text, env)
- require("redcloth")
- RedCloth.new(text).to_html
- end
- end
- class HTMLStripper < Plugin
- self.handles = { "html" => "txt" }
- def filter(text, env)
- text.gsub(/<.*?>/, "")
- end
- end
- class ERBFilter < Plugin
- self.handles = { "erb" => "*" }
- def filter(text, env)
- require("erb")
- context = Context.new(env)
- context.extend(ERB::Util)
- ERB.new(text, nil, "-").result(context.context_binding)
- end
- end
- end
- end
Add Comment
Please, Sign In to add comment