Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>While OP has already accepted an answer using <code>instance_eval(string)</code>, I would strongly urge OP to avoid string forms of <code>eval</code> unless absolutely necessary. Eval invokes the ruby compiler -- it's expensive to compute and dangerous to use as it opens a vector for code injection attacks.</p> <p>As stated there's no need for send at all:</p> <pre><code>obj.foo.bar </code></pre> <p>If indeed the names of foo and bar are coming from some non-static calculation, then</p> <pre><code>obj.send(foo_method).send(bar_method) </code></pre> <p>is simple and all one needs for this.</p> <p>If the methods are coming in the form of a dotted string, one can use split and inject to chain the methods:</p> <pre><code>'foo.bar'.split('.').inject(obj, :send) </code></pre> <p>Clarifying in response to comments: String eval is one of the riskiest things one can do from a security perspective. If there's any way the string is constructed from user supplied input without incredibly diligent inspection and validation of that input, you should just consider your system owned.</p> <p>send(method) where method is obtained from user input has risks too, but there's a more limited attack vector. Your user input can cause you to execute any 0-arghument method dispatchable through the receiver. Good practise here would be to always whitelist the methods before dispatching:</p> <pre><code>VALID_USER_METHODS = %w{foo bar baz} def safe_send(method) raise ArgumentError, "#{method} not allowed" unless VALID_USER_METHODS.include?(method.to_s) send(method) end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload