Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this class inheritance cause an infinite recursion
    text
    copied!<p>I'm attempting to DRY up decorators in a Rails project.</p> <p>Essentially, I want to delegate any missing methods to the resource object (or the resource object's class).</p> <p>Here's a simplified example</p> <pre><code># Decorator base class class Decorator attr_accessor :resource private def method_missing(name, *args, &amp;block) self.resource.send(name, *args, &amp;block) end # infinite recursion happens here def self.method_missing(name, *args, &amp;block) self.resource.class.send(name, *args, &amp;block) end end # Decorator class that will be used class UserCreator &lt; Decorator attr_reader :user def initialize(params) @user = User.new(params[:user]) self.resource = @user end def save # do special stuff with user object if @user.save # perhaps do some more stuff after the save true else # perhaps handle the error here false end end end # A simple controller example class SomeController &lt; ApplicationController respond_to :json def create @user = UserCreator.new(params) if @user.save render :json =&gt; @user else render :json =&gt; @user.errors end end end </code></pre> <p>However, in the class <code>Decorator</code> an infinite recursion happens in the class (singleton) method <code>self.method_missing</code>. It's passing <code>resource</code> as the <code>name</code> argument in that method.</p> <p>I am trying to wrap my head around the control flow of what's going on here. A method <code>resource</code> exists in the base <code>Decorator</code> class via <code>attr_accessor</code>, so I thought, the subclass <code>UserCreator</code> also has this method. So I'm not sure why it thinks <code>resource</code> is a missing method. If I get rid of the <code>Decorator</code> superclass and just implement the <code>method_missing</code>s in the <code>UserCreator</code> class, all works as expected.</p> <p>Any help in implementing this base class to work as expected is greatly appreciated, so I don't have to implement the same <code>method_missing</code> methods in every decorator.</p>
 

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