Class: TTY::Prompt::Choice

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

Overview

An immutable representation of a single choice option from select menu

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value, **options) ⇒ Choice

Create a Choice instance


78
79
80
81
82
83
84
# File 'lib/tty/prompt/choice.rb', line 78

def initialize(name, value, **options)
  @name  = name
  @value = value
  @key   = options[:key]
  @disabled = options[:disabled].nil? ? false : options[:disabled]
  freeze
end

Instance Attribute Details

#disabledObject (readonly)

The text to display for disabled choice


73
74
75
# File 'lib/tty/prompt/choice.rb', line 73

def disabled
  @disabled
end

#keyObject (readonly)

The keyboard key to activate this choice


68
69
70
# File 'lib/tty/prompt/choice.rb', line 68

def key
  @key
end

#nameObject (readonly)

The label name


63
64
65
# File 'lib/tty/prompt/choice.rb', line 63

def name
  @name
end

Class Method Details

.convert_hash(val) ⇒ Object

Convert hash into choice


50
51
52
53
54
55
56
57
58
# File 'lib/tty/prompt/choice.rb', line 50

def self.convert_hash(val)
  if val.key?(:name) && val.key?(:value)
    new(val[:name].to_s, val[:value], **val)
  elsif val.key?(:name)
    new(val[:name].to_s, val[:name].to_s, **val)
  else
    new(val.keys.first.to_s, val.values.first)
  end
end

.from(val) ⇒ Choice

Create choice from value

Parameters:

  • val (Object)

    the value to be converted

Returns:

Raises:

  • (ArgumentError)

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/tty/prompt/choice.rb', line 29

def self.from(val)
  case val
  when Choice
    val
  when Array
    name, value, options = *val
    if name.is_a?(Hash)
      convert_hash(name)
    else
      new(name.to_s, (value.nil? ? name.to_s : value), **(options || {}))
    end
  when Hash
    convert_hash(val)
  else
    new(val, val)
  end
end

Instance Method Details

#==(other) ⇒ Boolean

Object equality comparison

Returns:

  • (Boolean)

112
113
114
115
116
117
118
# File 'lib/tty/prompt/choice.rb', line 112

def ==(other)
  return false unless other.is_a?(self.class)

  name == other.name &&
    value == other.value &&
    key == other.key
end

#disabled?Boolean

Check if this choice is disabled

Returns:

  • (Boolean)

91
92
93
# File 'lib/tty/prompt/choice.rb', line 91

def disabled?
  !!@disabled
end

#to_sString

Object string representation

Returns:

  • (String)

125
126
127
# File 'lib/tty/prompt/choice.rb', line 125

def to_s
  name.to_s
end

#valueObject

Read value and evaluate


98
99
100
101
102
103
104
105
# File 'lib/tty/prompt/choice.rb', line 98

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