Created
June 27, 2014 14:22
-
-
Save mikekreeki/8ea354849903a5b2f77e to your computer and use it in GitHub Desktop.
How to use ActiveRecord::Callbacks with clear separation of responsibilities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EmailListener | |
def user_created(user) | |
UserMailer.welcome_email(user).deliver | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
include Wisper::Publisher | |
############################## | |
# CALLBACKS | |
############################## | |
after_create :notify_created | |
############################## | |
# PRIVATE METHODS | |
############################## | |
private | |
def notify_created | |
publish(:user_created, self) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UsersController < ApplicationController | |
def create | |
@user = User.new(user_params) | |
@user.subscribe EmailListener.new | |
if @user.save | |
# .. | |
else | |
# .. | |
end | |
end | |
private | |
def user_params | |
# .. | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment