Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using traits with a factory

I'm currently discovering scala and I was wondering if I could use traits with a factory.

I tried this :

abstract class Foo {
  ...
}
object Foo {
  def apply() = new Bar

  private class Bar extends Foo {
    ...
  }
}

Foo() with MyTrait // Not working

I guess it's because with must be preceded by new.

So is there any way to do this ?

Thank you

like image 982
Mr_Qqn Avatar asked Aug 01 '10 08:08

Mr_Qqn


People also ask

What is trait in factory bot?

FactoryBot's traits are an outstanding way to DRY up your tests and factories by naming groups of attributes, callbacks, and associations in one concise area. Imagine defining factories but without the attributes backed by a specific object.

What are traits in Rspec?

Rspec has great feature and that is trait. In rspec we create factory for each class which provides the simplest set of attributes necessary to create an instance of that class. Many times we need some attributes which we do not want to add in original factory and at the same time we do not want to repeat it.

What is transient in Rspec?

Transient attributes are essentially variables local to the factory that do not persist into the created object.


1 Answers

No it is too late, the instance is already created when the apply() method returns.

What you can do is using the traits inside the factory method. The code below is from a rather big code example I am writing:

object Avatar {
 // Avatar factory method
 def apply(name: String, race: RaceType.Value, character: CharacterType.Value
  ): Avatar = {
    race match {
      case RaceType.Dwarf => {
        character match {
          case CharacterType.Thief => new Avatar(name) with Dwarf with Thief
          case CharacterType.Warrior => new Avatar(name) with Dwarf with Warrior
          case CharacterType.Wizard => new Avatar(name) with Dwarf with Wizard
        }
      }
      case RaceType.Elf => {
        character match {
          case CharacterType.Thief => new Avatar(name) with Elf with Thief
          case CharacterType.Warrior => new Avatar(name) with Elf with Warrior
          case CharacterType.Wizard => new Avatar(name) with Elf with Wizard
        }
      }
    }
  }
}

class Avatar(val name: String) extends Character {
  ...
}

In this code the type (profession and race) of your Avatar is decided in the factory based on the RaceType and CharacterType enumerations. What you have is one factory for all sorts of different types or type combinations.

like image 181
olle kullberg Avatar answered Oct 28 '22 00:10

olle kullberg