Created
September 11, 2020 14:15
-
-
Save tangentus/d20055a777909b50f9653ed53a91884b to your computer and use it in GitHub Desktop.
Fun with Bindings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Blah | |
def initialize | |
@hello = 'world' | |
end | |
end | |
blah = Blah.new | |
blah_binding = blah.instance_eval { binding } | |
ERB.new("<%= hello %>").result(blah_binding) | |
# Result: | |
# NameError: undefined local variable or method `hello' for #<Blah:0x00007fcb999d2990 @hello="world"> | |
# Did you mean? @hello | |
# FIX 1: | |
class Blah | |
attr_reader :hello | |
def initialize | |
@hello = 'world' | |
end | |
end | |
blah = Blah.new | |
blah_binding = blah.instance_eval { binding } | |
ERB.new("<%= hello %>").result(blah_binding) | |
# => "world" | |
# Fix 2: (decorator pattern to capture a binding) | |
# OpenStruct has builtin accessors for instance varialbes that are created. | |
params = OpenStruct.new({hello: "world"}) | |
params_binding = params.instance_eval { binding } | |
ERB.new("<%= hello %>").result(params_binding) | |
# => "world" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment