module
Crystallabs::Helpers::Enums
Overview
Helpers for working with enums via plain shorthands, so callers can write
:vcenter / "vcenter" (or {:vcenter, :right}) instead of
Tput::AlignFlag::VCenter (or Tput::AlignFlag::VCenter | Tput::AlignFlag::Right).
A "shorthand" is a Symbol or String, both going through Enum.parse.
Conversion is via the generic .from class methods below, for any enum T.
Defined in:
crystallabs-helpers.crClass Method Summary
-
.from(t : T.class, value : Shorthand) forall T
Converts a single shorthand (symbol or string) into an enum member, e.g.
-
.from(t : T.class, values : Enumerable(Shorthand)) forall T
Converts a collection of shorthands into a combined enum value by OR-ing the members together — for
@[Flags]enums, e.g. -
.from(t : T.class, value : T) forall T
Passthrough: a value already of the target enum is returned as-is, so call sites accept both
:centerandAlignFlag::Centeruniformly.
Macro Summary
-
enum_property(decl)
Declares an enum-typed
propertylike the built-in macro, plus a setter overload accepting a shorthand or collection of shorthands (Symbol/String), so both the assignment form and any initializer routing throughself.NAME = ...accept shorthands transparently.
Class Method Detail
Converts a single shorthand (symbol or string) into an enum member, e.g.
Enums.from(AlignFlag, :center) or Enums.from(AlignFlag, "center"),
both # => AlignFlag::Center. Matching is case-insensitive (Enum.parse).
Converts a collection of shorthands into a combined enum value by OR-ing
the members together — for @[Flags] enums, e.g.
Enums.from(AlignFlag, {:vcenter, :right}) # => VCenter | Right.
Symbols and strings may be mixed. An empty collection yields the zero
value (e.g. AlignFlag::None).
Passthrough: a value already of the target enum is returned as-is, so call
sites accept both :center and AlignFlag::Center uniformly.
Macro Detail
Declares an enum-typed property like the built-in macro, plus a setter
overload accepting a shorthand or collection of shorthands
(Symbol/String), so both the assignment form and any initializer
routing through self.NAME = ... accept shorthands transparently.
The conversion target is derived from the property's own type via
typeof, so the enum is never named twice:
class Widget
Crystallabs::Helpers::Enums.enum_property align : Tput::AlignFlag = Tput::AlignFlag::Top | Tput::AlignFlag::Left
# In a hand-written initializer, widen the argument and route it through
# the setter; the enum is listed first, followed by the shared `Shorthands`:
def initialize(align : Tput::AlignFlag | Crystallabs::Helpers::Enums::Shorthands = @align)
self.align = align
end
end
w.align = :center # => Center
w.align = "center" # => Center
w.align = {:vcenter, :right} # => VCenter | Right
w.align = Tput::AlignFlag::Left