title: Using wisper (pubsub library) with Devise
body: <p>I'm trying to figure out how to use <a href="https://github.com/krisleech/wisper" rel="nofollow">wisper</a> with Devise.</p>
  
  <p>When a new user account is registered, I want to create some sample data for that user.</p>
  
  <p>So in my user model I would have:</p>
  
  <pre><code>include Wisper::Publisher
  after_create :notify
  def notify
    publish(:user_created, self)
  end
  </code></pre>
  
  <p>and my listener would be something like:</p>
  
  <pre><code>class SampleDataCreator
    def user_created(user)
      user.widgets.create!(name: "Your First Widget")
    end
  end
  </code></pre>
  
  <p>But I can't figure out how to tie this into Devise. How can I configure the <code>SampleDataCreator</code> to listen for events from the Devise user model?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I've tried attaching the listener in the Devise registration controller as follows:</p>
  
  <pre><code>class RegistrationsController &lt; Devise::RegistrationsController
    def create
      super do |resource|
        resource.subscribe(SampleDataCreator.new)
      end
    end
  end
  </code></pre>
  
  <p>but it seems the listener never gets triggered.</p>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>I realised the above approach wasn't working because the record is saved before yield is called. It seems tricky to hook into Devise before this point, so instead I overrode the whole method:</p>
  
  <pre><code>  def create
      build_resource(sign_up_params)
  
      resource_saved = resource.save
      yield resource if block_given?
      resource.subscribe(SampleDataCreator.new) # &lt;-------------------- my addition
      if resource_saved
        if resource.active_for_authentication?
          set_flash_message :notice, :signed_up if is_flashing_format?
          sign_up(resource_name, resource)
          respond_with resource, location: after_sign_up_path_for(resource)
        else
          set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
          expire_data_after_sign_in!
          respond_with resource, location: after_inactive_sign_up_path_for(resource)
        end
      else
        clean_up_passwords resource
        respond_with resource
      end
    end
  </code></pre>
  
  <p>This now works, although it's not very elegant.</p>
  
  <p><strong>UPDATE 3</strong></p>
  
  <p>I found a much simpler way, I can just hook into <code>build_resource</code>:</p>
  
  <pre><code>class RegistrationsController &lt; Devise::RegistrationsController
    def build_resource(sign_up_params)                                                       
      super.subscribe(SampleDataCreator.new)                                                 
    end
  end
  </code></pre>