/tools/Rake/quicktemplate.rb

http://github.com/agross/netopenspace · Ruby · 48 lines · 37 code · 11 blank · 0 comment · 1 complexity · 28628ba21f3aeb820a25aa629dd9c196 MD5 · raw file

  1. require 'rake'
  2. require 'erb'
  3. class QuickTemplate
  4. attr_reader :args, :file
  5. def initialize(file)
  6. raise "The template file to process must be given" if file.nil?
  7. @file = file
  8. end
  9. def exec(args = {})
  10. template = prepare_template File.read(@file)
  11. result = exec_erb template, args
  12. resultFile = @file.ext('')
  13. File.open(resultFile, 'w') do
  14. |f| f.write(result)
  15. end
  16. puts "Created file #{resultFile}"
  17. end
  18. def prepare_template(template)
  19. tag_regex = /(@\w[\w\.]+\w@)/
  20. hits = template.scan(tag_regex)
  21. tags = hits.map do |item|
  22. item[0].chomp('@').reverse.chomp('@').reverse.strip
  23. end
  24. tags.map! do |a|
  25. a.to_sym
  26. end
  27. tags.uniq!
  28. tags.inject(template) do |text, tag|
  29. text.gsub /@#{tag.to_s}@/, "<%= #{tag.to_s} %>"
  30. end
  31. end
  32. def exec_erb(template, args)
  33. b = binding
  34. erb = ERB.new(template, 0, "%")
  35. erb.result(b)
  36. end
  37. end