require 'erb' require 'zan_tools/string' module ZanTools class TemplateError < StandardError; end module Generatable def self.included(host_class) host_class.extend ClassMethods end class Configuration def initialize @config = {} end def each(&block) @config.each(&block) end def method_missing(name, *args) matches = name.match(/([^=]+)(=)?/) # 判断是否为赋值或取值 if !matches.nil? && !matches[2].nil? && args.size == 1 raise "preserved name `#{matches[1]}` is invalid" if respond_to?(matches[1]) @config[matches[1]] = args[0] elsif !matches.nil? && matches[2].nil? && @config.key?(matches[1]) @config[matches[1]] else super end end def compile(tmpl) template = ERB.new(tmpl, nil, '-') template.result(binding) rescue StandardError => e raise TemplateError.new("#{e.class} - #{e.message}") end end module ClassMethods def config @config ||= Configuration.new end alias :conf :config def configure yield config end def define(&block) config.instance_eval(&block) end def compile(tmpl) config.compile(tmpl) end end end end