Sha256: 685bfdf8385e579b6f20faee8e1f3a8329fdb0e16462c65c32f69445aa8e0860

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

##
## $Rev: 77 $
## $Release: 2.4.1 $
## copyright(c) 2006-2007 kuwata-lab.com all rights reserved.
##


module Erubis


  ##
  ## context object for Engine#evaluate
  ##
  ## ex.
  ##   template = <<'END'
  ##   Hello <%= @user %>!
  ##   <% for item in @list %>
  ##    - <%= item %>
  ##   <% end %>
  ##   END
  ##
  ##   context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
  ##   # or
  ##   # context = Erubis::Context.new
  ##   # context[:user] = 'World'
  ##   # context[:list] = ['a', 'b', 'c']
  ##
  ##   eruby = Erubis::Eruby.new(template)
  ##   print eruby.evaluate(context)
  ##
  class Context
    include Enumerable

    def initialize(hash=nil)
      hash.each do |name, value|
        self[name] = value
      end if hash
    end

    def [](key)
      return instance_variable_get("@#{key}")
    end

    def []=(key, value)
      return instance_variable_set("@#{key}", value)
    end

    def keys
      return instance_variables.collect { |name| name[1..-1] }
    end

    def each
      instance_variables.each do |name|
        key = name[1..-1]
        value = instance_variable_get(name)
        yield(key, value)
      end
    end

    def to_hash
      hash = {}
      self.keys.each { |key| hash[key] = self[key] }
      return hash
    end

    def update(context_or_hash)
      arg = context_or_hash
      if arg.is_a?(Hash)
        arg.each do |key, val|
          self[key] = val
        end
      else
        arg.instance_variables.each do |varname|
          key = varname[1..-1]
          val = arg.instance_variable_get(varname)
          self[key] = val
        end
      end
    end

  end


end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
erubis-2.4.1 lib/erubis/context.rb