Skip to content

Instantly share code, notes, and snippets.

@tangentus
Created September 11, 2020 14:15
Show Gist options
  • Save tangentus/d20055a777909b50f9653ed53a91884b to your computer and use it in GitHub Desktop.
Save tangentus/d20055a777909b50f9653ed53a91884b to your computer and use it in GitHub Desktop.
Fun with Bindings
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