1

I'm trying to figure out how to use wisper with Devise.

When a new user account is registered, I want to create some sample data for that user.

So in my user model I would have:

include Wisper::Publisher
after_create :notify
def notify
  publish(:user_created, self)
end

and my listener would be something like:

class SampleDataCreator
  def user_created(user)
    user.widgets.create!(name: "Your First Widget")
  end
end

But I can't figure out how to tie this into Devise. How can I configure the SampleDataCreator to listen for events from the Devise user model?

UPDATE

I've tried attaching the listener in the Devise registration controller as follows:

class RegistrationsController < Devise::RegistrationsController
  def create
    super do |resource|
      resource.subscribe(SampleDataCreator.new)
    end
  end
end

but it seems the listener never gets triggered.

UPDATE 2

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:

  def create
    build_resource(sign_up_params)

    resource_saved = resource.save
    yield resource if block_given?
    resource.subscribe(SampleDataCreator.new) # <-------------------- 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

This now works, although it's not very elegant.

UPDATE 3

I found a much simpler way, I can just hook into build_resource:

class RegistrationsController < Devise::RegistrationsController
  def build_resource(sign_up_params)                                                       
    super.subscribe(SampleDataCreator.new)                                                 
  end
end
Andy Waite
  • 10,785
  • 4
  • 33
  • 47
  • great solution (update 3), another less attractive option would be to globally subscribe `SampleDataCreator.new`: https://github.com/krisleech/wisper#global-listeners – Kris Jun 23 '14 at 08:36

1 Answers1

0

I would subscribe the SampleDataCreator globally.

I saw a complex project where the listeners were unsubscribing and subscribing all the times. It was almost chaotic. I would recommend to avoid the subscribe/unsubsribe dynamics.

Boti
  • 3,275
  • 1
  • 29
  • 54