Skip to content

Instantly share code, notes, and snippets.

@mrichie
Created March 6, 2012 11:16
Show Gist options
  • Save mrichie/1985728 to your computer and use it in GitHub Desktop.
Save mrichie/1985728 to your computer and use it in GitHub Desktop.
Using locals by extending Binding
###Breaking news!
#Have you ever dreamed to extract all local variables from current context using ruby?
#Do you hate writing partials below style? :
=render partial: 'form_additional', locals: {f: f, shortname: shortname, expanded: expanded}
#I bet you do!
#Here is extension for Binding class which lets you to avoid writing hardcore something: something. It looks pretty workaround but there is no other way...
#first of all - extend Binding
class Binding
def locals(specific = nil)
Hash[
(specific || self.eval('local_variables')).map{|v| [v.to_sym, self.eval(v.to_s)] }
]
end
end
#using
[2] pry(main)> x=123
=> 123
[3] pry(main)> locs = binding.locals %w{x}
=> {"x"=>123}
[4] pry(main)> z='how are you dan'
=> "how are you dan"
[5] pry(main)> binding.locals %w{x z}
=> {"x"=>123, "z"=>"how are you dan"}
#or extracting just everything
[6] pry(main)> another_var = 'another'
=> "another"
[7] pry(main)> binding.locals
=> {"another_var"=>"another",
"z"=>"how are you dan",
"locs"=>{"x"=>123},
"x"=>123,
"_"=>"another",
"_dir_"=>nil,
"_file_"=>nil,
"_ex_"=>nil,
"_pry_"=>
etc....
#Since today you are able to write your partials
=render partial: 'somepartial', locals: binding.locals
=render partial: 'form' , locals: binding.locals(%w{f additional extended})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment