SOLID In Rails - Open/Closed Principle


Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

We have notification system
class NotificationSender
def send(user, message)
EmailSender.send(user, message) if user.active?
end
end
view raw Solid-O01.rb hosted with ❤ by GitHub


But if we need to chose - send sms or email? So we can add something like if else, but the good way is to create another services
It's a way from Design Patterns.

class Sender
def send(user:, message:)
raise NotImplementedError
end
end
class EmailSender < Sender
def send(user:, message:)
# implementation for Email
end
end
class SmsSender < Sender
def send(user:, message:)
# implementation for SMS
end
end
sender = NotificationSender.new
sender.send(user, "Hello World", SmsSender.new)
view raw Solid-O02.rb hosted with ❤ by GitHub


http://rubyblog.pro/

Comments