Factory method using convention and ruby

We have been working in a new system of notifications, and soon we are going to talk about this new feature!. 

But now I want to write about how we used some “factory methods” to minimize dependency, and embrace duck typing in this feature.

Specially I want to talk about: how we create notifications.

Notifications::NewComment.create(comment)
Notifications::NewIdea.create(idea)

Given we have a lot of different kinds of notifications. Calling each kind of notification like this:

Would be very fragil, because we would have a lot of new dependencies in the system, just for the notifications. And if for some reason, we have to change the interface, we would need to update the changes in many places.

So what we did is to write a method, that serves as an interface for all the notifications.

module Notifications
  class Notifier
    def notify kind, *args
      notification_class(kind).create(*args)
    end

    private

    def notification_class(kind)
      "Notifications::#{kind.to_s.camelize}".constantize
    end
  end
end

With this little extra class, our application now has just one dependency. A method that create a notification in a dynamic way using a factory method that solves the notification class.

Also we add a “notify” method in the ApplicationController, so we can create a notification, in a prettier way =).

class ApplicationController < ActionController::Base

  # other stuff ..

  def notify(*args)
    Notifications::Notifier.new.notify(*args) 
  end
end

class CommentsController < ApplicationController
  # other stuff

  def create
    @comment = task.new_comment(params[:comment])

    if @comment.save
      notify :new_comment, @comment
      # render comment
    else
      # render errors
    end
  end 
end

And that’s all. hope you find it usefull =)

Recibe gratis nuestros más nuevos artículos y ensayos.