Class: Errgonomic::VariantName

Inherits:
Object
  • Object
show all
Defined in:
lib/errgonomic/variant_name.rb

Overview

What a bare Some, None, Ok or Err evaluates to. Rust writes a value as return None, where here the value is None(); the bare name is for patterns. It matches as the class it names, and refuses to become a string, so a missing pair of parentheses raises rather than writing a class name into a column. It is not a class, so an application's own class None fails where it is written instead of reopening the gem's.

Examples:

case Some(1)
in Some(value) then value
end # => 1
None === None() # => true
None === Some(1) # => false
None.inspect # => "Errgonomic::Option::None"
"tier-#{None}" # => raise Errgonomic::SerializeError, "bare None names a variant for a pattern, not a value; build one with parentheses"
[Ok].join # => raise Errgonomic::SerializeError, "bare Ok names a variant for a pattern, not a value; build one with parentheses"
Some(1).is_a?(Some) # => raise TypeError, "class or module required"
Some(1).is_a?(Errgonomic::Option::Some) # => true

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, variant) ⇒ VariantName

Returns a new instance of VariantName.



36
37
38
39
40
# File 'lib/errgonomic/variant_name.rb', line 36

def initialize(name, variant)
  @name = name
  @variant = variant
  freeze
end

Class Method Details

.define(name, variant) ⇒ Object

Name a variant at top level, refusing a constant the application already holds there rather than replacing it.



25
26
27
28
29
30
31
32
33
34
# File 'lib/errgonomic/variant_name.rb', line 25

def self.define(name, variant)
  if Object.const_defined?(name, false)
    existing = Object.const_get(name)
    return if existing.is_a?(VariantName) && existing.names?(variant)

    raise NameError.new("#{name} is already defined as #{existing.inspect}; errgonomic defines #{name} " \
                        "at top level to name #{variant} in patterns, so rename the application's constant", name)
  end
  Object.const_set(name, new(name, variant))
end

Instance Method Details

#===(other) ⇒ Object



46
47
48
# File 'lib/errgonomic/variant_name.rb', line 46

def ===(other)
  @variant === other # rubocop:disable Style/CaseEquality
end

#inspectObject



50
51
52
# File 'lib/errgonomic/variant_name.rb', line 50

def inspect
  @variant.inspect
end

#names?(variant) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/errgonomic/variant_name.rb', line 42

def names?(variant)
  @variant.equal?(variant)
end

#refuse!(*_args) ⇒ Object Also known as: to_s, to_json, as_json

Refuse to stand in for a value.



55
56
57
58
# File 'lib/errgonomic/variant_name.rb', line 55

def refuse!(*_args)
  raise Errgonomic::SerializeError,
        "bare #{@name} names a variant for a pattern, not a value; build one with parentheses"
end