Sunday, 15 April 2012

ruby on rails - Using wisper (pubsub library) with Devise -



ruby on rails - Using wisper (pubsub library) with Devise -

i'm trying figure out how utilize wisper devise.

when new user business relationship registered, want create sample info user.

so in user model have:

include wisper::publisher after_create :notify def notify publish(:user_created, self) end

and listener like:

class sampledatacreator def user_created(user) user.widgets.create!(name: "your first widget") end end

but can't figure out how tie devise. how can configure sampledatacreator hear events devise user model?

update

i've tried attaching listener in devise registration controller follows:

class registrationscontroller < devise::registrationscontroller def create super |resource| resource.subscribe(sampledatacreator.new) end end end

but seems listener never gets triggered.

update 2

i realised above approach wasn't working because record saved before yield called. seems tricky hook devise before point, instead overrode whole method:

def create build_resource(sign_up_params) resource_saved = resource.save yield resource if block_given? resource.subscribe(sampledatacreator.new) # <-------------------- add-on 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 works, although it's not elegant.

update 3

i found much simpler way, can hook build_resource:

class registrationscontroller < devise::registrationscontroller def build_resource(sign_up_params) super.subscribe(sampledatacreator.new) end end

i subscribe sampledatacreator globally.

i saw complex project listeners unsubscribing , subscribing times. chaotic. recommend avoid subscribe/unsubsribe dynamics.

ruby-on-rails ruby devise publish-subscribe wisper

No comments:

Post a Comment