Skip to content

Instantly share code, notes, and snippets.

@ota42y
Last active December 21, 2017 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ota42y/148ca9ee02c50c447ad4e6401e4dfa51 to your computer and use it in GitHub Desktop.
Save ota42y/148ca9ee02c50c447ad4e6401e4dfa51 to your computer and use it in GitHub Desktop.
result_with_hash
require "erb"
erb_obj = ERB.new("<%=name%> \"Hello <%=first_name%> <%=last_name%>!\"")
name = 'honoka'
last_name = 'kousaka'
puts erb_obj.result_with_hash(first_name: 'kotori', last_name: 'minami')
puts "Top level name is #{name}, #{last_name}"
user = {first_name: 'umi', last_name: 'sonoda'}
puts erb_obj.result_with_hash(user)
puts "Top level name is #{name}, #{last_name}"
honoka "Hello kotori minami!"
Top level name is honoka, kousaka
honoka "Hello umi sonoda!"
Top level name is honoka, kousaka
def result_with_hash(hash)
b = new_toplevel
backup = {}
news = []
hash.each_pair do |key, value|
if b.local_variable_defined?(key)
backup[key] = b.local_variable_get(key)
else
news << key
end
b.local_variable_set(key, value)
end
ret = result(b)
backup.each_pair do |key, value|
b.local_variable_set(key, value)
end
news.each { |key| b.local_variable_set(key, nil) }
ret
end
honoka "Hello kotori minami!"
Top level name is honoka, minami # we want to honoka kousaka
honoka "Hello umi sonoda!"
Top level name is honoka, sonoda # we want to honoka kousaka
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment