Is the information displayed in ruby-dump accessible at runtime?

In 10 Things You Didn't Know Ruby Do Do Slide 30, James Edward Gray II mentions

ruby -e 'puts { is_this_a_block }' --dump parsetree 

which produces

 ########################################################### ## Do NOT use this node dump for any purpose other than ## ## debug and research. Compatibility is not guaranteed. ## ########################################################### # @ NODE_SCOPE (line: 1) # +- nd_tbl: (empty) # +- nd_args: # | (null node) # +- nd_body: # @ NODE_ITER (line: 1) # +- nd_iter: # | @ NODE_FCALL (line: 1) # | +- nd_mid: :puts # | +- nd_args: # | (null node) # +- nd_body: # @ NODE_SCOPE (line: 1) # +- nd_tbl: (empty) # +- nd_args: # | (null node) # +- nd_body: # @ NODE_VCALL (line: 1) # +- nd_mid: :is_this_a_block 

Is the information displayed here available at runtime? If so, does the information only represent the code that was written, or does it also have the results of any metaprogramming that was done?

+4
source share
1 answer

Yeah. You can use the Ripper gem (which is included with MRI 1.9) to generate an AST (abstract syntax tree) for a given line of code (via Ripper.sexp ). However, due to architectural changes in MRI 1.9, when your code is parsed and converted to YARV bytecode, the source and AST are discarded and you can no longer get this information. However, if you enter any code that you generated by metaprogramming in Ripper.sexp , you can get the AST for the result. You can also use some of the other tricks shown in JEG2 to parse the source file and create an AST for it (although any metaprogrammed code will not be parsed since it does not exist yet).

+3
source

Source: https://habr.com/ru/post/1443407/


All Articles