Available for hire
Builder Pattern With Ruby

At times you’ll need to create an object, that builds it’s definition over the course of the a request. Lets for example say we’re building a list of Traits for a particular user behaviour.

To create a Builder, you’ll need a class that defines at least 3 methods:

  1. initialize method which defines an array
  2. add method which adds a trait to an array and returns self, which allows us to chain
  3. build method which will add any semantic sugar and return as required, in the below case an array of symbols without nils
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class TraitBuilder
  def initialize
    @traits = []
  end

  def add(trait)
    @traits << trait
    self
  end

  def build
    @traits.compact
  end
end

That way we can use it as follows:

1
2
3
4
5
6
7
8
9
10
11
  trait_builder = TraitBuilder.new

  # You can just add one at a time
  trait_builder.add(:blonde_hair)

  # Or chain!
  trait_builder.add(:blue_eyes).add(:male).add(:black_shirt)

  # And then build
  trait_builder.build
  # => [:blonde_hair, :blue_eyes, :male, :black_shirt]

Comments