ruby - Getting local variable names defined inside a method from outside the method -
is possible in ruby local variables names defined inside method outside method using metaprogramming?
def foo var = 100 arr = [1,2] end
something foo.local_variables.
i need retrieve variable names, not values.
why i'm trying find variable names: have class want dynamically generate setters instance variables initialized in "#initialize".
in order that, inside "initialize", using instance_variables.each |inst_var_name| define_singleton_method(...) ...
this works: each instanced object gets setters singleton methods. however, looking solution read instance variables names outside "initialize" method, in order able use "#define_method" them, , create regular methods , not singleton methods.
you can (re)-parse method , inspect s-expr tree. see below proof of concept. can hold of file method defined using method#source_location
, read file. there surely room improvement code should started. functional piece of code , requires ruby parser gem (https://github.com/whitequark/parser).
require 'parser/current' node = parser::currentruby.parse(data.read) # data comes after __end__ def find_definition(node, name) return node if definition_node?(node, name) if node.respond_to?(:children) node.children.find |child| find_definition(child, name) end end end def definition_node?(node, name) return false if !node.respond_to?(:type) node.type == :def && node.children.first == name end def collect_lvasgn(node) result = [] return result if !node.respond_to?(:children) node.children.each |child| if child.respond_to?(:type) && child.type == :lvasgn result << child.children.first else result += collect_lvasgn(child) end end result end definition = find_definition(node, :foo) puts collect_lvasgn(definition) __end__ def foo var = 100 arr = [1,2] if = 3 * var end end def bar var = 200 arr = [3, 4] end
do mind telling why want find variables?
Comments
Post a Comment