Class: TTY::Prompt::Choice

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/prompt/choice.rb

Overview

A single choice option

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value, key = nil) ⇒ Choice

Create a Choice instance



19
20
21
22
23
# File 'lib/tty/prompt/choice.rb', line 19

def initialize(name, value, key = nil)
  @name  = name
  @value = value
  @key   = key
end

Instance Attribute Details

#keyObject (readonly)



14
15
16
# File 'lib/tty/prompt/choice.rb', line 14

def key
  @key
end

#nameObject (readonly)

The label name



12
13
14
# File 'lib/tty/prompt/choice.rb', line 12

def name
  @name
end

Class Method Details

.from(val) ⇒ Choice

Create choice from value

Examples:

Choice.from(:option_1)
Choice.from([:option_1, 1])

Parameters:

  • val (Object)

    the value to be converted

Returns:

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/tty/prompt/choice.rb', line 39

def self.from(val)
  case val
  when Choice
    val
  when String, Symbol
    new(val, val)
  when Array
    new("#{val.first}", val.last)
  when Hash
    if val.key?(:name)
      new("#{val[:name]}", val[:value], val[:key])
    else
      new("#{val.keys.first}", val.values.first)
    end
  else
    raise ArgumentError, "#{val} cannot be coerced into Choice"
  end
end

Instance Method Details

#==(other) ⇒ Boolean

Object equality comparison

Returns:

  • (Boolean)


75
76
77
78
# File 'lib/tty/prompt/choice.rb', line 75

def ==(other)
  return false unless other.is_a?(self.class)
  name == other.name && value == other.value
end

#to_sString

Object string representation

Returns:

  • (String)


85
86
87
# File 'lib/tty/prompt/choice.rb', line 85

def to_s
  "#{name}"
end

#valueObject

Read value and evaluate



61
62
63
64
65
66
67
68
# File 'lib/tty/prompt/choice.rb', line 61

def value
  case @value
  when Proc
    @value.call
  else
    @value
  end
end