Simple factory pattern

Ruby on Rails / Refactoring

Let’s start with a sample class:

class SocialMediaPublisher
  def publish(social_media_type, user, message)
    social_media_api = nil

    case social_media_type
      when 'facebook'
        social_media_api = Facebook::API.new(user)
      when 'twitter'
        social_media_api = Twitter::API.new(user)
      when 'instagram'
        social_media_api = Instagram::API.new(user)
      else
        fail(InvalidSocialMediaType, social_media_type)
    end

    social_media_api.sign_in
    social_media_api.push(message: message)
  end
end

The only different thing here is an object creation and factory pattern is about encapsulating object creation. We will extract now code responsible for object creation to separated class and we will name it SocialMediaPublisherFactory

class SocialMediaPublisherFactory
  def create_social_media_api(social_media_type, user)
    case social_media_type
      when 'facebook'
        Facebook::API.new(user)
      when 'twitter'
        Twitter::API.new(user)
      when 'instagram'
        Instagram::API.new(user)
      else
        fail(InvalidSocialMediaType, social_media_type)
    end
  end
end

We have our simple factory so we can update source class to use it:

class SocialMediaPublisher
  def publish(social_media_type, user, message)
    factory = SocialMediaPublisherFactory
    social_media_api = factory.create_social_media_api(
      social_media_type, user
    )

    social_media_api.sign_in
    social_media_api.push(message: message)
  end
end

As you can see there are no implementation details here. You can even add support for another social media provider and you don’t have to update this class as long as you will have the same method names for each new provider.