Class: Configuration

Inherits:
Struct show all
Defined in:
lib/selecta.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(height, initialize, choices) ⇒ Configuration

Returns a new instance of Configuration.



149
150
151
152
153
# File 'lib/selecta.rb', line 149

def initialize(height, initialize, choices)
  # Constructor is defined to force argument presence; otherwise Struct
  # defaults missing arguments to nil
  super
end

Instance Attribute Details

#choicesObject

Returns the value of attribute choices

Returns:

  • (Object)

    the current value of choices



148
149
150
# File 'lib/selecta.rb', line 148

def choices
  @choices
end

#heightObject

Returns the value of attribute height

Returns:

  • (Object)

    the current value of height



148
149
150
# File 'lib/selecta.rb', line 148

def height
  @height
end

#initial_searchObject

Returns the value of attribute initial_search

Returns:

  • (Object)

    the current value of initial_search



148
149
150
# File 'lib/selecta.rb', line 148

def initial_search
  @initial_search
end

Class Method Details

.default_optionsObject



171
172
173
# File 'lib/selecta.rb', line 171

def self.default_options
  parse_options({})
end

.from_inputs(choices, options, screen_height = 21) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
# File 'lib/selecta.rb', line 159

def self.from_inputs(choices, options, screen_height=21)
  # Shrink the number of visible choices if the screen is too small
  if options.fetch(:height) == "full"
    height = screen_height
  else
    height = [options.fetch(:height), screen_height].min
  end

  choices = massage_choices(choices)
  Configuration.new(height, options.fetch(:search), choices)
end

.massage_choices(choices) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/selecta.rb', line 180

def self.massage_choices(choices)
  choices.map do |choice|
    # Encoding to UTF-8 with `:invalid => :replace` isn't good enough; it
    # still leaves some invalid characters. For example, this string will fail:
    #
    # echo "девуш\xD0:" | selecta
    #
    # Round-tripping through UTF-16, with `:invalid => :replace` as well,
    # fixes this. I don't understand why. I found it via:
    #
    # http://stackoverflow.com/questions/2982677/ruby-1-9-invalid-byte-sequence-in-utf-8
    if choice.valid_encoding?
      choice
    else
      utf16 = choice.encode('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
      utf16.encode('UTF-8', 'UTF-16')
    end.strip
  end
end

.parse_options(options) ⇒ Object



175
176
177
178
# File 'lib/selecta.rb', line 175

def self.parse_options(options)
  defaults = { search: "", height: 21 }
  defaults.merge(options)
end

Instance Method Details

#visible_choicesObject



155
156
157
# File 'lib/selecta.rb', line 155

def visible_choices
  height - 1
end