Skip to content

Instantly share code, notes, and snippets.

@rachidcalazans
rachidcalazans / sample_03.rb
Created August 15, 2018 11:53
Example I for the Post - Design Patterns in Ruby - Strategy - Part I
IosStrategy = Struct.new(:app_token) do
def notify(context)
context.receivers.each { |receiver| push(user_token: receiver.token, title: context.subject_msg, content: context.content_msg) }
end
private
def push(user_token:, title:, content:)
@rachidcalazans
rachidcalazans / sample_02.rb
Created August 15, 2018 11:52
Example I for the Post - Design Patterns in Ruby - Strategy - Part I
EmailStrategy = Struct.new(:from) do
def notify(context)
context.receivers.each { |receiver| push(to: receiver.email, subject: context.subject_msg, content: context.content_msg) }
end
private
def push(to:, subject:, content:)
@rachidcalazans
rachidcalazans / sample_01.rb
Last active August 15, 2018 11:53
Example I for the Post - Design Patterns in Ruby - Strategy - Part I
Notification = Struct.new(:notifier_strategy, :receivers, :subject_msg, :content_msg) do
def notify
# The Notifier Strategy will be Email or iOS.
notifier_strategy.notify(self)
end
end
@rachidcalazans
rachidcalazans / sample_07.rb
Last active March 22, 2018 17:20
Example VII Avoiding Nil - Represent special cases as objects
def index
render :login unless current_user.authenticated?
end
@rachidcalazans
rachidcalazans / sample_06.rb
Last active March 22, 2018 17:20
Example VI Avoiding Nil - Represent special cases as objects
class GuestUser
def authenticated?
false
end
end
class User
def authenticated?
true
end
@rachidcalazans
rachidcalazans / sample_05.rb
Last active March 22, 2018 17:20
Example V Avoiding Nil - Represent special cases as objects
def index
render :login unless current_user
end
@rachidcalazans
rachidcalazans / sample_04.rb
Last active March 22, 2018 17:20
Example IV Avoiding Nil - Represent special cases as objects
def index
@posts = current_user.posts
end
@rachidcalazans
rachidcalazans / sample_03.rb
Last active March 22, 2018 17:20
Example III Avoiding Nil - Represent special cases as objects
class GuestUser
def posts
List.public_posts # Exactly same method that took the Conditional Controller.
end
end
@rachidcalazans
rachidcalazans / sample_02.rb
Last active March 22, 2018 17:19
Example II Avoiding Nil - Represent special cases as objects
class ApplicationController ...
...
def current_user
return GuestUser.new unless session[:user_id]
User.find(session[:user_id])
end
...
end
@rachidcalazans
rachidcalazans / sample_01.rb
Last active March 22, 2018 17:19
Example I Avoiding Nil - Represent special cases as objects
def index
if current_user
@posts = current_user.posts
else
@posts = List.public_posts
end
end