DeMarco
DeMarco

Reputation: 599

Ruby - Method Factory

I have being reading about Factory Method Pattern and I am still having trouble understanding how to use it in practical cases even after reading examples and questions about it.

For example, assume a case where there are two ways to get data into my class, i.e., the user input can be either:

Name Surname

Surname, Name

This is something that I would solve more or less like this:

class Name
  attr_accessor :name
  attr_accessor :surname
  def initialize(rawname)
    if(rawname.include? ',')
      @name = rawname.split(', ').last
      @surname = rawname.split(', ').first
    else
      @name = rawname.split(' ').first
      @surname = rawname.split(' ').last
    end
  end
  def print
    puts "#{@name} #{@surname}"
  end
end

How should I implement Factory method on this example? Or in general, how should my though process be in order to use such design patterns?

Upvotes: 1

Views: 771

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

How should I implement Factory Method on this example?

You shouldn't.

In class-based programming, the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created.

When you'll have specialized subclasses of Name, then maybe.

How should my thought process be in order to use such design patterns?

Your first thought should be "does this pattern even make sense here? Do I understand the pattern well enough to be trying to apply it here?". If answers are "yes" and "yes", then you just apply it.

Update:

What you most likely meant to use here is Factory pattern.

In class-based programming, a factory is an abstraction of a constructor of a class

class NameFactory
  def self.create(str)
    # break str here
    Name.new(first_name, last_name)
  end
end

# then

@user.name = NameFactory.create(params[:user_name])

In this concrete example, in real life, I wouldn't use any factory stuff. It's just unwarranted complication. But if I have a significantly more complicated class (say, Transaction), then I employ some kind of a creational pattern, yes. Most often it's a Builder.

Upvotes: 4

sawa
sawa

Reputation: 168081

It is not the most optimal, but you can normalize the raw name first.

class Name
  attr_accessor :name, :surname
  def initialize(rawname)
    @name, @surname = rawname.split(", ").rotate.join(" ").split
  end
end

Upvotes: 1

Related Questions