template.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. class NotificationFactory::Template
  2. def initialize(objects, locale, template, escape = true)
  3. @objects = objects
  4. @locale = locale || 'en-us'
  5. @template = template
  6. @escape = escape
  7. end
  8. def render
  9. ERB.new(@template).result(binding)
  10. end
  11. # d - data of object
  12. # d('user.firstname', htmlEscape)
  13. def d(key, escape = nil)
  14. # do validaton, ignore some methodes
  15. if key =~ /(`|\.(|\s*)(save|destroy|delete|remove|drop|update\(|update_att|create\(|new|all|where|find))/i
  16. return "#{key} (not allowed)"
  17. end
  18. value = nil
  19. object_methods = key.split('.')
  20. object_name = object_methods.shift.to_sym
  21. object_refs = @objects[object_name]
  22. object_methods_s = ''
  23. object_methods.each {|method|
  24. if object_methods_s != ''
  25. object_methods_s += '.'
  26. end
  27. object_methods_s += method
  28. # if method exists
  29. if !object_refs.respond_to?( method.to_sym )
  30. value = "\#{#{object_name}.#{object_methods_s} / no such method}"
  31. break
  32. end
  33. object_refs = object_refs.send( method.to_sym )
  34. }
  35. placeholder = if !value
  36. object_refs
  37. else
  38. value
  39. end
  40. return placeholder if escape == false || (escape.nil? && !@escape)
  41. h placeholder
  42. end
  43. # c - config
  44. # c('fqdn', htmlEscape)
  45. def c(key, escape = nil)
  46. config = Setting.get(key)
  47. return config if escape == false || (escape.nil? && !@escape)
  48. h config
  49. end
  50. # t - translation
  51. # t('yes', htmlEscape)
  52. def t(key, escape = nil)
  53. translation = Translation.translate(@locale, key)
  54. return translation if escape == false || (escape.nil? && !@escape)
  55. h translation
  56. end
  57. # a_html - article body in html
  58. # a_html(article)
  59. def a_html(article)
  60. content_type = d "#{article}.content_type", false
  61. if content_type =~ /html/
  62. return d "#{article}.body", false
  63. end
  64. d("#{article}.body", false).text2html
  65. end
  66. # a_text - article body in text
  67. # a_text(article)
  68. def a_text(article)
  69. content_type = d "#{article}.content_type", false
  70. body = d "#{article}.body", false
  71. if content_type =~ /html/
  72. body = body.html2text
  73. end
  74. (body.strip + "\n").gsub(/^(.*?)$/, '> \\1')
  75. end
  76. # h - htmlEscape
  77. # h('fqdn', htmlEscape)
  78. def h(key)
  79. return key if !key
  80. CGI.escapeHTML(key.to_s)
  81. end
  82. end