Skip to content

[Proposal] Introducing traits #43

@javierav

Description

@javierav

The reason for removing positional arguments for slots in PR #40 is to allow this proposal to work. The concept of trait is similar to what FactoryBot implements for its factories.

Suppose we have the following configuration:

cv = ClassVariants.build do
  variant color: :primary, class: "bg-primary"
  variant color: :secondary, class: "bg-secondary"

  defaults color: :primary
end

To use the primary variant, as it is the default, we don't have to do anything:

cv.render

But to use the secondary, we have to do:

cv.render(color: :secondary)

Since these examples are simple, it doesn't seem too redundant, but if we had to consider more variables, for example format, size or uppercase in addition to color, things get complicated:

cv.render(color: :secondary, size: :medium, format: :outline, uppercase: true)

With the proposed traits, this example will be much cleaner:

cv.render(:secondary, :medium, :outline, :uppercase)

Traits act as shortcuts for attributes under a single name, so they can be seamlessly mixed with other attributes in the traditional way:

cv.render(:secondary, :medium, format: :outline, uppercase: true)

At the definition level, I'm still not entirely sure, and we should consider the best way to do it, but it could be something like this:

cv = ClassVariants.build do
  variant color: :primary, class: "bg-primary"
  variant color: :secondary, class: "bg-secondary"

  # using new trait method
  trait :primary, color: :primary
  trait :secondary, color: :secondary
  trait :supertrait, color: :primary, size: :medium

  # remove duplicity?
  trait :primary, for: :color
  trait %i[primary secondary], for: :color
  trait %i[primary secondary], :color

  # or may be implemented as named defaults?
  defaults :primary, color: :primary
  defaults :secondary, color: :secondary
  defaults color: :primary
end

What do you think @adrianthedev?

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions