Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm particularly fond of using <code>method_missing</code>, especially when the code you want to use is very similar across the various method calls. Here's an example from this <a href="http://www.trottercashion.com/2011/02/08/rubys-define_method-method_missing-and-instance_eval.html" rel="noreferrer">site</a> - whenever somebody calls <code>x.boo</code> and <code>boo</code> doesn't exist, method_missing is called with <code>boo</code>, the arguments to <code>boo</code>, and (optionally) a block:</p> <pre><code>class ActiveRecord::Base def method_missing(meth, *args, &amp;block) if meth.to_s =~ /^find_by_(.+)$/ run_find_by_method($1, *args, &amp;block) else super # You *must* call super if you don't handle the # method, otherwise you'll mess up Ruby's method # lookup. end end def run_find_by_method(attrs, *args, &amp;block) # Make an array of attribute names attrs = attrs.split('_and_') # #transpose will zip the two arrays together like so: # [[:a, :b, :c], [1, 2, 3]].transpose # # =&gt; [[:a, 1], [:b, 2], [:c, 3]] attrs_with_args = [attrs, args].transpose # Hash[] will take the passed associative array and turn it # into a hash like so: # Hash[[[:a, 2], [:b, 4]]] # =&gt; { :a =&gt; 2, :b =&gt; 4 } conditions = Hash[attrs_with_args] # #where and #all are new AREL goodness that will find all # records matching our conditions where(conditions).all end end </code></pre> <p><code>define_method</code> also looks like it would work for you, but I have less experience with it than <code>method_missing</code>. Here's the example from the same link:</p> <pre><code>%w(user email food).each do |meth| define_method(meth) { @data[meth.to_sym] } end </code></pre>
 

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