context.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. ##
  2. ## $Release: 2.7.0 $
  3. ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
  4. ##
  5. module Erubis
  6. ##
  7. ## context object for Engine#evaluate
  8. ##
  9. ## ex.
  10. ## template = <<'END'
  11. ## Hello <%= @user %>!
  12. ## <% for item in @list %>
  13. ## - <%= item %>
  14. ## <% end %>
  15. ## END
  16. ##
  17. ## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
  18. ## # or
  19. ## # context = Erubis::Context.new
  20. ## # context[:user] = 'World'
  21. ## # context[:list] = ['a', 'b', 'c']
  22. ##
  23. ## eruby = Erubis::Eruby.new(template)
  24. ## print eruby.evaluate(context)
  25. ##
  26. class Context
  27. include Enumerable
  28. def initialize(hash=nil)
  29. hash.each do |name, value|
  30. self[name] = value
  31. end if hash
  32. end
  33. def [](key)
  34. return instance_variable_get("@#{key}")
  35. end
  36. def []=(key, value)
  37. return instance_variable_set("@#{key}", value)
  38. end
  39. def keys
  40. return instance_variables.collect { |name| name[1..-1] }
  41. end
  42. def each
  43. instance_variables.each do |name|
  44. key = name[1..-1]
  45. value = instance_variable_get(name)
  46. yield(key, value)
  47. end
  48. end
  49. def to_hash
  50. hash = {}
  51. self.keys.each { |key| hash[key] = self[key] }
  52. return hash
  53. end
  54. def update(context_or_hash)
  55. arg = context_or_hash
  56. if arg.is_a?(Hash)
  57. arg.each do |key, val|
  58. self[key] = val
  59. end
  60. else
  61. arg.instance_variables.each do |varname|
  62. key = varname[1..-1]
  63. val = arg.instance_variable_get(varname)
  64. self[key] = val
  65. end
  66. end
  67. end
  68. end
  69. end