Class: DR::Eruby::Context

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/dr/base/eruby.rb

Overview

Copy/Pasted from erubis context.rb

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)

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ Context

Returns a new instance of Context.



230
231
232
233
234
# File 'lib/dr/base/eruby.rb', line 230

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

Instance Method Details

#[](key) ⇒ Object



236
237
238
# File 'lib/dr/base/eruby.rb', line 236

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

#[]=(key, value) ⇒ Object



240
241
242
# File 'lib/dr/base/eruby.rb', line 240

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

#eachObject



248
249
250
251
252
253
254
# File 'lib/dr/base/eruby.rb', line 248

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

#keysObject



244
245
246
# File 'lib/dr/base/eruby.rb', line 244

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

#to_hObject

Was to_hash, but changed to 'to_h' in commit 25d0e1e4b1a4ada40fd64945eb79823ea074d030 Indeed otherwise passing it to 'evaluate' it get interpreted as the options rather than as a context cf https://bugs.ruby-lang.org/issues/12884 corrected in ruby 2.4.1?



260
261
262
263
264
# File 'lib/dr/base/eruby.rb', line 260

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

#update(context_or_hash) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/dr/base/eruby.rb', line 266

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