diff options
author | Abinoam P. Marques Jr <abinoam@gmail.com> | 2017-09-25 14:51:49 -0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-09-25 14:51:49 -0300 |
commit | 73bd6a13a479cce042ed702a4154e15d169efb3f (patch) | |
tree | e2d93d36e2d4ea7c4c243bce29b84ec014001e5e | |
parent | 66b8ece6560879a4e7d34dd6bd0cf20d48f3b3a7 (diff) | |
parent | b48f09dc4828b6eab3588862d53a445197f6ee26 (diff) | |
download | highline-73bd6a13a479cce042ed702a4154e15d169efb3f.tar.gz |
Merge pull request #215 from JEG2/rubocopv2.0.0.pre.develop.11
Apply Rubocop stylistic suggestions
66 files changed, 1794 insertions, 1572 deletions
diff --git a/.rubocop.yml b/.rubocop.yml index 898f418..29b5448 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -3,16 +3,20 @@ # See options at: # https://github.com/bbatsov/rubocop/tree/master/config +AllCops: + TargetRubyVersion: 1.9 + # General # Multi-line method chaining should be done with leading dots. -Style/DotPosition: +Layout/DotPosition: EnforcedStyle: trailing SupportedStyles: - leading - trailing -# Enabling! +# Enabling +# -------- Style/CollectionMethods: Description: 'Preferred collection methods.' @@ -23,9 +27,59 @@ Style/StringMethods: Description: 'Checks if configured preferred methods are used over non-preferred.' Enabled: true -# Disabling! +# Disabling +# --------- + +# Modifying +# --------- +# Check quotes usage according to lint rule below. Style/StringLiterals: - Description: 'Checks if uses of quotes match the configured preference.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#consistent-string-literals' + Enabled: true + EnforcedStyle: double_quotes + +# Configuration parameters: SupportedStyles. +# SupportedStyles: snake_case, camelCase +Naming/MethodName: + EnforcedStyle: snake_case + Exclude: + - 'test/**/*' + +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, AutoCorrectEncodingComment. +# SupportedStyles: when_needed, always, never +Style/Encoding: + Enabled: true + EnforcedStyle: always + +# If we fix this, it will change method signature. +# Save it for major release. +Style/OptionalArguments: + Exclude: + - 'lib/highline/list_renderer.rb' + +# TemplateRenderer should never fail on method missing. +Style/MethodMissing: + Exclude: + - 'lib/highline/template_renderer.rb' + +# This is a breaking change for MRI 1.9. +# Revoke when updating to MRI 2.0 as minimum. +# Cop supports --auto-correct. +# Configuration parameters: MinSize, SupportedStyles. +# SupportedStyles: percent, brackets +Style/SymbolArray: + EnforcedStyle: brackets + +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: auto_detection, squiggly, active_support, powerpack, unindent +Layout/IndentHeredoc: + Exclude: + - 'examples/page_and_wrap.rb' + - 'highline.gemspec' + - 'test/acceptance/acceptance.rb' + +# Cop supports --auto-correct. +Lint/ScriptPermission: Enabled: false diff --git a/.travis.yml b/.travis.yml index 5657690..82bfae2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,12 +2,13 @@ language: ruby dist: trusty sudo: false +cache: bundler script: "bundle exec rake test" rvm: - - 1.9 - 2.0 - 2.1 - 2.2 + - 2.3 - ruby-head - rbx-3.81 - jruby-19mode # JRuby in 1.9 mode @@ -23,6 +24,10 @@ matrix: - rvm: jruby-19mode # JRuby in 1.9 mode - rvm: jruby-head include: - - rvm: 2.3 - script: "bundle exec rake test && bundle exec codeclimate-test-reporter" # Run only for 2.3 -bundler_args: --without development + - rvm: 1.9 + before_install: + - "gem update --system -N" + - "gem update bundler -N" + - rvm: 2.4 + script: "bundle exec rake test && bundle exec codeclimate-test-reporter" # Run only for 2.4 +bundler_args: --without code_quality diff --git a/Changelog.md b/Changelog.md index 4c81472..fe00ff2 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,8 +2,14 @@ Below is a complete listing of changes for each revision of HighLine. +### 2.0.0-develop.11 / 2017-09-25 +* PR #215 - Apply several Rubocop stylistic suggestions (@abinoam) + * Update gemspec/Gemfile to newer standards + * Update travis configuration fixing 1.9 problem + * Adjust .rubocop.yml with things we don't want to change + ### 2.0.0-develop.10 / 2017-06-29 -* PR #214 - Remove `$terminal` (global variable) +* PR #214 - Remove `$terminal` (global variable) (@abinoam) * Use HighLine.default_instance instead * Reorganize/Group code at lib/highline.rb @@ -1,13 +1,11 @@ -source "https://rubygems.org" +# encoding: utf-8 -gem "rake", require: false -gem "rdoc", require: false +source "https://rubygems.org" -group :development, :test do - gem "code_statistics", require: false - gem "minitest", require: false -end +git_source(:github) { |repo_name| "https://github.com/#{repo_name}" } +# Specify your gem's dependencies in tgem.gemspec +gemspec # Reporting only at one ruby version of travis matrix (no repetition) gem "codeclimate-test-reporter", group: :test, require: false @@ -17,16 +15,11 @@ platform :ruby do gem "simplecov", group: :test end -group :development do - gem 'pronto' - gem 'pronto-reek', require: false - gem 'pronto-rubocop', require: false - gem 'pronto-poper', require: false - - # Using strict versions of flay and pronto-flay while - # PR https://github.com/mmozuras/pronto-flay/pull/11/files - # is not merged - gem 'flay', '2.7.0' - gem 'pronto-flay', '0.6.1', require: false - gem 'flog' +group :code_quality do + gem "flog", require: false + gem "pronto", require: false + gem "pronto-flay", require: false + gem "pronto-poper", require: false + gem "pronto-reek", require: false + gem "pronto-rubocop", require: false end @@ -1,21 +1,15 @@ +# encoding: utf-8 + require "rake/testtask" -require "rubygems/package_task" require "bundler/gem_tasks" -require "code_statistics" - -require "rubygems" -task :default => [:test] +task default: [:test] Rake::TestTask.new do |test| - test.libs = ["lib", "test"] + test.libs = %w[lib test] test.verbose = true test.warning = true - test.test_files = FileList['test/test*.rb'] -end - -Gem::PackageTask.new(SPEC) do |package| - # do nothing: I just need a gem but this block is required + test.test_files = FileList["test/test*.rb"] end desc "Run some interactive acceptance tests" diff --git a/examples/ansi_colors.rb b/examples/ansi_colors.rb index 2a86e38..677ca45 100644 --- a/examples/ansi_colors.rb +++ b/examples/ansi_colors.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 # ansi_colors.rb # @@ -9,19 +10,13 @@ require "rubygems" require "highline/import" # Supported color sequences. -colors = %w{black red green yellow blue magenta cyan white} +colors = %w[black red green yellow blue magenta cyan white] # Using color() with symbols. colors.each_with_index do |c, i| say("This should be <%= color('#{c}', :#{c}) %>!") - if i == 0 - say( "This should be " + - "<%= color('white on #{c}', :white, :on_#{c}) %>!") - else - say( "This should be " + - "<%= color( '#{colors[i - 1]} on #{c}', - :#{colors[i - 1]}, :on_#{c} ) %>!") - end + say("This should be <%= color('#{colors[i - 1]} on #{c}', \ + :#{colors[i - 1]}, :on_#{c} ) %>!") end # Using color with constants. @@ -32,7 +27,7 @@ say("This should be <%= color('underlined', UNDERLINE) %>!") say("This might even <%= BLINK %>blink<%= CLEAR %>!") # It even works with list wrapping. -erb_digits = %w{Zero One Two Three Four} + +erb_digits = %w[Zero One Two Three Four] + ["<%= color('Five', :blue) %%>"] + - %w{Six Seven Eight Nine} + %w[Six Seven Eight Nine] say("<%= list(#{erb_digits.inspect}, :columns_down, 3) %>") diff --git a/examples/asking_for_arrays.rb b/examples/asking_for_arrays.rb index 42c3268..b659832 100644 --- a/examples/asking_for_arrays.rb +++ b/examples/asking_for_arrays.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 # asking_for_arrays.rb # @@ -12,8 +13,8 @@ require "pp" puts "Using: #{HighLine.default_instance.class}" puts -grades = ask( "Enter test scores (or a blank line to quit):", - lambda { |ans| ans =~ /^-?\d+$/ ? Integer(ans) : ans} ) do |q| +grades = ask("Enter test scores (or a blank line to quit):", + ->(ans) { ans =~ /^-?\d+$/ ? Integer(ans) : ans }) do |q| q.gather = "" end diff --git a/examples/basic_usage.rb b/examples/basic_usage.rb index 62e3ccb..c97b89f 100644 --- a/examples/basic_usage.rb +++ b/examples/basic_usage.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 # basic_usage.rb # @@ -12,32 +13,35 @@ require "yaml" puts "Using: #{HighLine.default_instance.terminal.class}" puts -contacts = [ ] +contacts = [] +# Just define a parse class method and use the class +# as a parser for HighLine#ask +# class NameClass - def self.parse( string ) - if string =~ /^\s*(\w+),\s*(\w+)\s*$/ - self.new($2, $1) - else - raise ArgumentError, "Invalid name format." - end + def self.parse(string) + raise ArgumentError, "Invalid name format." unless + string =~ /^\s*(\w+),\s*(\w+)\s*$/ + + new(Regexp.last_match(2), Regexp.last_match(1)) end def initialize(first, last) - @first, @last = first, last + @first = first + @last = last end attr_reader :first, :last end -begin - entry = Hash.new +loop do + entry = {} # basic output say("Enter a contact:") # basic input - entry[:name] = ask("Name? (last, first) ", NameClass) do |q| + entry[:name] = ask("Name? (last, first) ", NameClass) do |q| q.validate = /\A\w+, ?\w+\Z/ end entry[:company] = ask("Company? ") { |q| q.default = "none" } @@ -47,27 +51,30 @@ begin q.case = :up q.validate = /\A[A-Z]{2}\Z/ end - entry[:zip] = ask("Zip? ") do |q| + entry[:zip] = ask("Zip? ") do |q| q.validate = /\A\d{5}(?:-?\d{4})?\Z/ end - entry[:phone] = ask( "Phone? ", - lambda { |p| p.delete("^0-9"). - sub(/\A(\d{3})/, '(\1) '). - sub(/(\d{4})\Z/, '-\1') } ) do |q| - q.validate = lambda { |p| p.delete("^0-9").length == 10 } + entry[:phone] = ask("Phone? ", + lambda { |p| + p.delete("^0-9"). + sub(/\A(\d{3})/, '(\1) '). + sub(/(\d{4})\Z/, '-\1') + }) do |q| + q.validate = ->(p) { p.delete("^0-9").length == 10 } q.responses[:not_valid] = "Enter a phone numer with area code." end entry[:age] = ask("Age? ", Integer) { |q| q.in = 0..105 } entry[:birthday] = ask("Birthday? ", Date) - entry[:interests] = ask( "Interests? (comma separated list) ", - lambda { |str| str.split(/,\s*/) } ) + entry[:interests] = ask("Interests? (comma separated list) ", + ->(str) { str.split(/,\s*/) }) entry[:description] = ask("Enter a description for this contact.") do |q| q.whitespace = :strip_and_collapse end contacts << entry -# shortcut for yes and no questions -end while agree("Enter another contact? ", true) + # shortcut for yes and no questions + break unless agree("Enter another contact? ", true) +end if agree("Save these contacts? ", true) file_name = ask("Enter a file name: ") do |q| diff --git a/examples/color_scheme.rb b/examples/color_scheme.rb index 1fe8863..215a595 100644 --- a/examples/color_scheme.rb +++ b/examples/color_scheme.rb @@ -1,20 +1,21 @@ #!/usr/bin/env ruby -w +# encoding: utf-8 # color_scheme.rb # # Created by Jeremy Hinegardner on 2007-01-24 # Copyright 2007 Jeremy Hinegardner. All rights reserved -require 'rubygems' -require 'highline/import' +require "rubygems" +require "highline/import" # Create a color scheme, naming color patterns with symbol names. ft = HighLine::ColorScheme.new do |cs| - cs[:headline] = [ :bold, :yellow, :on_black ] - cs[:horizontal_line] = [ :bold, :white, :on_blue] - cs[:even_row] = [ :green ] - cs[:odd_row] = [ :magenta ] - end + cs[:headline] = [:bold, :yellow, :on_black] + cs[:horizontal_line] = [:bold, :white, :on_blue] + cs[:even_row] = [:green] + cs[:odd_row] = [:magenta] +end # Assign that color scheme to HighLine... HighLine.color_scheme = ft @@ -26,7 +27,7 @@ say("<%= color('-'*20, :horizontal_line) %>") # Setup a toggle for rows. i = true ("A".."D").each do |row| - row_color = i ? :even_row : :odd_row - say("<%= color('#{row}', '#{row_color}') %>") - i = !i + row_color = i ? :even_row : :odd_row + say("<%= color('#{row}', '#{row_color}') %>") + i = !i end diff --git a/examples/get_character.rb b/examples/get_character.rb index c0a666f..d94a9b7 100644 --- a/examples/get_character.rb +++ b/examples/get_character.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 require "rubygems" require "highline/import" @@ -8,8 +9,8 @@ puts choices = "ynaq" answer = ask("Your choice [#{choices}]? ") do |q| - q.echo = false - q.character = true - q.validate = /\A[#{choices}]\Z/ - end + q.echo = false + q.character = true + q.validate = /\A[#{choices}]\Z/ +end say("Your choice: #{answer}") diff --git a/examples/limit.rb b/examples/limit.rb index 6115580..460eeea 100644 --- a/examples/limit.rb +++ b/examples/limit.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby -w +# encoding: utf-8 # limit.rb # diff --git a/examples/menus.rb b/examples/menus.rb index 258c1ca..64e20e6 100644 --- a/examples/menus.rb +++ b/examples/menus.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 require "rubygems" require "highline/import" @@ -7,7 +8,7 @@ puts "Using: #{HighLine.default_instance.terminal.class}" puts # The old way, using ask() and say()... -choices = %w{ruby python perl} +choices = %w[ruby python perl] say("This is the old way using ask() and say()...") say("Please choose your favorite programming language:") say(choices.map { |c| " #{c}\n" }.join) @@ -24,11 +25,10 @@ say("\nThis is the new mode (default)...") choose do |menu| menu.prompt = "Please choose your favorite programming language? " - menu.choice :ruby do say("Good choice!") end - menu.choices(:python, :perl) do say("Not from around here, are you?") end + menu.choice(:ruby) { say("Good choice!") } + menu.choices(:python, :perl) { say("Not from around here, are you?") } menu.default = :ruby - end say("\nThis is letter indexing...") @@ -38,8 +38,8 @@ choose do |menu| menu.prompt = "Please choose your favorite programming language? " - menu.choice :ruby do say("Good choice!") end - menu.choices(:python, :perl) do say("Not from around here, are you?") end + menu.choice(:ruby) { say("Good choice!") } + menu.choices(:python, :perl) { say("Not from around here, are you?") } end say("\nThis is with a different layout...") @@ -49,8 +49,8 @@ choose do |menu| menu.header = "Languages" menu.prompt = "Favorite? " - menu.choice :ruby do say("Good choice!") end - menu.choices(:python, :perl) do say("Not from around here, are you?") end + menu.choice(:ruby) { say("Good choice!") } + menu.choices(:python, :perl) { say("Not from around here, are you?") } end say("\nYou can even build shells...") @@ -60,10 +60,10 @@ loop do menu.shell = true - menu.choice(:load, "Load a file.") do |command, details| + menu.choice(:load, "Load a file.") do |_command, details| say("Loading file with options: #{details}...") end - menu.choice(:save, "Save a file.") do |command, details| + menu.choice(:save, "Save a file.") do |_command, details| say("Saving file with options: #{details}...") end menu.choice(:quit, "Exit program.") { exit } diff --git a/examples/overwrite.rb b/examples/overwrite.rb index f3c9754..6ff8126 100644 --- a/examples/overwrite.rb +++ b/examples/overwrite.rb @@ -1,12 +1,13 @@ #!/usr/bin/env ruby +# encoding: utf-8 # overwrite.rb # # Created by Jeremy Hinegardner on 2007-01-24 # Copyright 2007 Jeremy Hinegardner. All rights reserved -require 'rubygems' -require 'highline/import' +require "rubygems" +require "highline/import" puts "Using: #{HighLine.default_instance.terminal.class}" puts @@ -15,8 +16,8 @@ prompt = "here is your password:" ask( "#{prompt} <%= color('mypassword', RED, BOLD) %> (Press Any Key to blank) " ) do |q| - q.overwrite = true - q.echo = false # overwrite works best when echo is false. - q.character = true # if this is set to :getc then overwrite does not work + q.overwrite = true + q.echo = false # overwrite works best when echo is false. + q.character = true # if this is set to :getc then overwrite does not work end say("<%= color('Look! blanked out!', GREEN) %>") diff --git a/examples/page_and_wrap.rb b/examples/page_and_wrap.rb index 24dd52d..d9c0662 100644 --- a/examples/page_and_wrap.rb +++ b/examples/page_and_wrap.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 # page_and_wrap.rb # @@ -11,7 +12,7 @@ require "highline/import" HighLine.default_instance.wrap_at = 80 HighLine.default_instance.page_at = 22 -say(<<END) +say(<<CONSTITUTION) THE UNITED STATES CONSTITUTION We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America. @@ -319,4 +320,4 @@ James Wilson. Gouv Morris Attest William Jackson Secretary -END +CONSTITUTION diff --git a/examples/password.rb b/examples/password.rb index 698829d..385e898 100644 --- a/examples/password.rb +++ b/examples/password.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 require "rubygems" require "highline/import" diff --git a/examples/repeat_entry.rb b/examples/repeat_entry.rb index 5e67f7d..a762961 100644 --- a/examples/repeat_entry.rb +++ b/examples/repeat_entry.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 require "rubygems" require "highline/import" @@ -6,7 +7,8 @@ require "highline/import" puts "Using: #{HighLine.default_instance.terminal.class}" puts -tounge_twister = ask("... try saying that three times fast") do |q| +# tounge_twister +ask("... try saying that three times fast") do |q| q.gather = 3 q.verify_match = true q.responses[:mismatch] = "Nope, those don't match. Try again." @@ -15,10 +17,10 @@ end puts "Ok, you did it." pass = ask("<%= key %>: ") do |q| - q.echo = '*' + q.echo = "*" q.verify_match = true - q.gather = {"Enter a password" => '', - "Please type it again for verification" => ''} + q.gather = { "Enter a password" => "", + "Please type it again for verification" => "" } end puts "Your password is now #{pass}!" diff --git a/examples/trapping_eof.rb b/examples/trapping_eof.rb index a63188c..41f7003 100644 --- a/examples/trapping_eof.rb +++ b/examples/trapping_eof.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 # trapping_eof.rb # @@ -13,7 +14,7 @@ loop do name = ask("What's your name?") break if name == "exit" puts "Hello, #{name}!" - rescue EOFError # HighLine throws this if @input.eof? + rescue EOFError # HighLine throws this if @input.eof? break end end diff --git a/examples/using_readline.rb b/examples/using_readline.rb index d8c072a..e69365c 100644 --- a/examples/using_readline.rb +++ b/examples/using_readline.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# encoding: utf-8 # using_readline.rb # @@ -9,7 +10,7 @@ require "rubygems" require "highline/import" loop do - cmd = ask("Enter command: ", %w{save sample load reset quit}) do |q| + cmd = ask("Enter command: ", %w[save sample load reset quit]) do |q| q.readline = true end say("Executing \"#{cmd}\"...") diff --git a/highline.gemspec b/highline.gemspec index e3e0dda..fc8e7f5 100644 --- a/highline.gemspec +++ b/highline.gemspec @@ -1,35 +1,35 @@ # coding: utf-8 -lib = File.expand_path('../lib', __FILE__) -$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'highline/version' - -GEM_VERSION = HighLine::VERSION -SPEC = Gem::Specification.new do |spec| - spec.name = "highline" - spec.version = GEM_VERSION - spec.platform = Gem::Platform::RUBY - spec.summary = "HighLine is a high-level command-line IO library." - spec.files = `git ls-files`.split("\n") - - spec.test_files = `git ls-files -- test/*.rb`.split("\n") - spec.has_rdoc = 'yard' - spec.extra_rdoc_files = %w[README.md TODO Changelog.md LICENSE] +lib = File.expand_path("../lib", __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) +require "highline/version" - spec.require_path = 'lib' +Gem::Specification.new do |spec| + spec.name = "highline" + spec.version = HighLine::VERSION + spec.author = "James Edward Gray II" + spec.email = "james@graysoftinc.com" - spec.author = "James Edward Gray II" - spec.email = "james@graysoftinc.com" - spec.rubyforge_project = "highline" - spec.homepage = "https://github.com/JEG2/highline" - spec.license = "Ruby" - spec.description = <<END_DESC + spec.summary = "HighLine is a high-level command-line IO library." + spec.description = <<DESCRIPTION A high-level IO library that provides validation, type conversion, and more for command-line interfaces. HighLine also includes a complete menu system that can crank out anything from simple list selection to complete shells with just minutes of work. -END_DESC +DESCRIPTION + spec.homepage = "https://github.com/JEG2/highline" + spec.license = "Ruby" + + spec.files = `git ls-files -z`.split("\x0").reject do |f| + f.match(%r{^(test|spec|features)/}) + end + spec.require_paths = ["lib"] + + spec.extra_rdoc_files = %w[README.md TODO Changelog.md LICENSE] + + spec.required_ruby_version = ">= 1.9.3" - spec.add_development_dependency "code_statistics" - spec.required_ruby_version = '>= 1.9.3' + spec.add_development_dependency "bundler" + spec.add_development_dependency "rake" + spec.add_development_dependency "minitest" end diff --git a/lib/highline.rb b/lib/highline.rb index a94bbed..b51a1a0 100755 --- a/lib/highline.rb +++ b/lib/highline.rb @@ -10,6 +10,7 @@ # # This is Free Software. See LICENSE and COPYING for details. +require "English" require "erb" require "optparse" require "stringio" @@ -29,17 +30,17 @@ require "highline/builtin_styles" # # A HighLine object is a "high-level line oriented" shell over an input and an # output stream. HighLine simplifies common console interaction, effectively -# replacing {Kernel#puts} and {Kernel#gets}. User code can simply specify the question to ask -# and any details about user interaction, then leave the rest of the work to -# HighLine. When {HighLine#ask} returns, you'll have the answer you requested, -# even if HighLine had to ask many times, validate results, perform range -# checking, convert types, etc. +# replacing {Kernel#puts} and {Kernel#gets}. User code can simply specify the +# question to ask and any details about user interaction, then leave the rest +# of the work to HighLine. When {HighLine#ask} returns, you'll have the answer +# you requested, even if HighLine had to ask many times, validate results, +# perform range checking, convert types, etc. # # @example Basic usage # cli = HighLine.new # answer = cli.ask "What do you think?" # puts "You have answered: #{answer}" - +# class HighLine include BuiltinStyles include CustomErrors @@ -58,7 +59,7 @@ class HighLine # Returns +true+ if HighLine is currently using a color scheme. def using_color_scheme? - !!@color_scheme + true if @color_scheme end # Reset color scheme to default (+nil+) @@ -75,7 +76,8 @@ class HighLine end # For checking if the current version of HighLine supports RGB colors - # Usage: HighLine.supports_rgb_color? rescue false # rescue for compatibility with older versions + # Usage: HighLine.supports_rgb_color? rescue false + # using rescue for compatibility with older versions # Note: color usage also depends on HighLine.use_color being set # TODO: Discuss removing this method def supports_rgb_color? @@ -97,8 +99,9 @@ class HighLine # @param page_at [Integer] page size and paginating. # @param indent_size [Integer] indentation size in spaces. # @param indent_level [Integer] how deep is indentated. - def initialize( input = $stdin, output = $stdout, - wrap_at = nil, page_at = nil, indent_size=3, indent_level=0 ) + def initialize(input = $stdin, output = $stdout, + wrap_at = nil, page_at = nil, + indent_size = 3, indent_level = 0) @input = input @output = output @@ -123,7 +126,7 @@ class HighLine # Returns truethy if HighLine instance is currently using color escapes. def use_color? - !!use_color + use_color end # Resets the use of color. @@ -136,7 +139,7 @@ class HighLine # Returns true if HighLine is currently tracking EOF for input. def track_eof? - !!track_eof + true if track_eof end # @return [Integer] The current column setting for wrapping output. @@ -182,11 +185,13 @@ class HighLine # # Raises EOFError if input is exhausted. # - # @param yes_or_no_question [String] a question that accepts yes and no as answers - # @param character [Boolean, :getc] character mode to be passed to Question#character + # @param yes_or_no_question [String] a question that accepts yes and no as + # answers + # @param character [Boolean, :getc] character mode to be passed to + # Question#character # @see Question#character - def agree( yes_or_no_question, character = nil ) - ask(yes_or_no_question, lambda { |yn| yn.downcase[0] == ?y}) do |q| + def agree(yes_or_no_question, character = nil) + ask(yes_or_no_question, ->(yn) { yn.downcase[0] == "y" }) do |q| q.validate = /\A(?:y(?:es)?|no?)\Z/i q.responses[:not_valid] = 'Please enter "yes" or "no".' q.responses[:ask_on_error] = :question @@ -236,7 +241,7 @@ class HighLine # @param items [Array<String>] # @param details [Proc] to be passed to Menu.new # @return [String] answer - def choose( *items, &details ) + def choose(*items, &details) menu = Menu.new(&details) menu.choices(*items) unless items.empty? @@ -268,7 +273,7 @@ class HighLine # @return [lambda] lambda to be used in autocompletion operations def shell_style_lambda(menu) - lambda do |command| # shell-style selection + lambda do |command| # shell-style selection first_word = command.to_s.split.first || "" options = menu.options @@ -359,7 +364,7 @@ class HighLine statement = render_statement(statement) return if statement.empty? - statement = (indentation+statement) + statement = (indentation + statement) # Don't add a newline if statement ends with whitespace, OR # if statement ends with whitespace before a color escape code. @@ -384,7 +389,7 @@ class HighLine # set to <tt>:auto</tt>, HighLine will attempt to determine the columns # available for the <tt>@output</tt> or use a sensible default. # - def wrap_at=( setting ) + def wrap_at=(setting) @wrap_at = setting == :auto ? output_cols : setting end @@ -394,7 +399,7 @@ class HighLine # set to <tt>:auto</tt>, HighLine will attempt to determine the rows available # for the <tt>@output</tt> or use a sensible default. # - def page_at=( setting ) + def page_at=(setting) @page_at = setting == :auto ? output_rows - 2 : setting end @@ -402,7 +407,7 @@ class HighLine # Outputs indentation with current settings # def indentation - ' '*@indent_size*@indent_level + " " * @indent_size * @indent_level end # @@ -413,7 +418,7 @@ class HighLine # @param multiline [Boolean] # @return [void] # @see #multi_indent - def indent(increase=1, statement=nil, multiline=nil) + def indent(increase = 1, statement = nil, multiline = nil) @indent_level += increase multi = @multi_indent @multi_indent ||= multiline @@ -443,7 +448,7 @@ class HighLine def output_cols return 80 unless @output.tty? terminal.terminal_size.first - rescue + rescue NoMethodError return 80 end @@ -454,7 +459,7 @@ class HighLine def output_rows return 24 unless @output.tty? terminal.terminal_size.last - rescue + rescue NoMethodError return 24 end @@ -468,7 +473,8 @@ class HighLine # Creates a new HighLine instance with the same options # def new_scope - self.class.new(@input, @output, @wrap_at, @page_at, @indent_size, @indent_level) + self.class.new(@input, @output, @wrap_at, + @page_at, @indent_size, @indent_level) end private @@ -505,7 +511,7 @@ class HighLine # @param question [Question] # @return [String] response def get_response_line_mode(question) - if question.echo == true and !question.limit + if question.echo == true && !question.limit get_line(question) else get_line_raw_no_echo_mode(question) @@ -529,13 +535,15 @@ class HighLine line = "" terminal.raw_no_echo_mode_exec do - while character = terminal.get_character + loop do + character = terminal.get_character + break unless character break if ["\n", "\r"].include? character # honor backspace and delete if character == "\b" chopped = line.chop! - output_erase_char if chopped and question.echo + output_erase_char if chopped && question.echo else line << character say_last_char_or_echo_char(line, question) @@ -563,11 +571,11 @@ class HighLine def say_last_char_or_echo_char(line, question) @output.print(line[-1]) if question.echo == true - @output.print(question.echo) if question.echo and question.echo != true + @output.print(question.echo) if question.echo && question.echo != true end def line_overflow_for_question?(line, question) - question.limit and line.size == question.limit + question.limit && line.size == question.limit end def output_erase_char diff --git a/lib/highline/builtin_styles.rb b/lib/highline/builtin_styles.rb index c829f60..71c2429 100644 --- a/lib/highline/builtin_styles.rb +++ b/lib/highline/builtin_styles.rb @@ -1,4 +1,4 @@ -#coding: utf-8 +# coding: utf-8 class HighLine # Builtin Styles that are included at HighLine initialization. @@ -23,17 +23,19 @@ class HighLine blink: "\e[5m", reverse: "\e[7m", concealed: "\e[8m" - } + }.freeze STYLE_LIST.each do |style_name, code| - style = String(style_name).upcase + style = String(style_name).upcase - const_set style, code - const_set style + "_STYLE", Style.new(name: style_name, code: code, builtin: true) + const_set style, code + const_set style + "_STYLE", + Style.new(name: style_name, code: code, builtin: true) end # Basic Style names like CLEAR, BOLD, UNDERLINE - STYLES = %w{CLEAR RESET BOLD DARK UNDERLINE UNDERSCORE BLINK REVERSE CONCEALED} + STYLES = %w[CLEAR RESET BOLD DARK UNDERLINE + UNDERSCORE BLINK REVERSE CONCEALED].freeze # A Hash with the basic colors an their ANSI escape codes. COLOR_LIST = { @@ -48,33 +50,35 @@ class HighLine gray: { code: "\e[37m", rgb: [192, 192, 192] }, grey: { code: "\e[37m", rgb: [192, 192, 192] }, none: { code: "\e[38m", rgb: [0, 0, 0] } - } + }.freeze COLOR_LIST.each do |color_name, attributes| - color = String(color_name).upcase + color = String(color_name).upcase - style = Style.new( - name: color_name, - code: attributes[:code], - rgb: attributes[:rgb], - builtin: true - ) + style = Style.new( + name: color_name, + code: attributes[:code], + rgb: attributes[:rgb], + builtin: true + ) - const_set color + "_STYLE", style + const_set color + "_STYLE", style end # The builtin styles basic colors like black, red, green. - BASIC_COLORS = %w{BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE GRAY GREY NONE} + BASIC_COLORS = + %w[BLACK RED GREEN YELLOW BLUE + MAGENTA CYAN WHITE GRAY GREY NONE].freeze colors = BASIC_COLORS.dup BASIC_COLORS.each do |color| bright_color = "BRIGHT_#{color}" colors << bright_color - const_set bright_color + '_STYLE', const_get(color + '_STYLE').bright + const_set bright_color + "_STYLE", const_get(color + "_STYLE").bright light_color = "LIGHT_#{color}" colors << light_color - const_set light_color + '_STYLE', const_get(color + '_STYLE').light + const_set light_color + "_STYLE", const_get(color + "_STYLE").light end # The builtin styles' colors like LIGHT_RED and BRIGHT_BLUE. @@ -86,11 +90,10 @@ class HighLine const_set "ON_#{color}", const_get("ON_#{color}_STYLE").code end - ON_NONE_STYLE.rgb = [255,255,255] # Override; white background + ON_NONE_STYLE.rgb = [255, 255, 255] # Override; white background # BuiltinStyles class methods to be extended. module ClassMethods - # Regexp to match against RGB style constant names. RGB_COLOR_PATTERN = /^(ON_)?(RGB_)([A-F0-9]{6})(_STYLE)?$/ @@ -98,27 +101,28 @@ class HighLine # builtin constants (without explicitly defining them) # @param name [Symbol] missing constant name def const_missing(name) - if name.to_s =~ RGB_COLOR_PATTERN - on = $1 - suffix = $4 - - if suffix - code_name = $1.to_s + $2 + $3 - else - code_name = name.to_s - end - - style_name = code_name + '_STYLE' - style = Style.rgb($3) - style = style.on if on - - const_set(style_name, style) - const_set(code_name, style.code) - - suffix ? style : style.code - else - raise NameError, "Bad color or uninitialized constant #{name}" - end + raise NameError, "Bad color or uninitialized constant #{name}" unless + name.to_s =~ RGB_COLOR_PATTERN + + on = Regexp.last_match(1) + suffix = Regexp.last_match(4) + + code_name = if suffix + Regexp.last_match(1).to_s + + Regexp.last_match(2) + + Regexp.last_match(3) + else + name.to_s + end + + style_name = code_name + "_STYLE" + style = Style.rgb(Regexp.last_match(3)) + style = style.on if on + + const_set(style_name, style) + const_set(code_name, style.code) + + suffix ? style : style.code end end end diff --git a/lib/highline/color_scheme.rb b/lib/highline/color_scheme.rb index 11cd687..e1bec88 100644 --- a/lib/highline/color_scheme.rb +++ b/lib/highline/color_scheme.rb @@ -8,7 +8,6 @@ # # This is Free Software. See LICENSE and COPYING for details - class HighLine # # ColorScheme objects encapsulate a named set of colors to be used in the @@ -19,7 +18,8 @@ class HighLine # # A ColorScheme contains named sets of HighLine color constants. # - # @example Instantiating a color scheme, applying it to HighLine, and using it: + # @example Instantiating a color scheme, applying it to HighLine, + # and using it: # ft = HighLine::ColorScheme.new do |cs| # cs[:headline] = [ :bold, :yellow, :on_black ] # cs[:horizontal_line] = [ :bold, :white ] @@ -49,15 +49,15 @@ class HighLine # constants. # # @param h [Hash] - def initialize( h = nil ) - @scheme = Hash.new + def initialize(h = nil) + @scheme = {} load_from_hash(h) if h yield self if block_given? end # Load multiple colors from key/value pairs. # @param h [Hash] - def load_from_hash( h ) + def load_from_hash(h) h.each_pair do |color_tag, constants| self[color_tag] = constants end @@ -66,20 +66,20 @@ class HighLine # Does this color scheme include the given tag name? # @param color_tag [#to_sym] # @return [Boolean] - def include?( color_tag ) + def include?(color_tag) @scheme.keys.include?(to_symbol(color_tag)) end # Allow the scheme to be accessed like a Hash. # @param color_tag [#to_sym] # @return [Style] - def []( color_tag ) + def [](color_tag) @scheme[to_symbol(color_tag)] end # Retrieve the original form of the scheme # @param color_tag [#to_sym] - def definition( color_tag ) + def definition(color_tag) style = @scheme[to_symbol(color_tag)] style && style.list end @@ -93,29 +93,33 @@ class HighLine # Allow the scheme to be set like a Hash. # @param color_tag [#to_sym] # @param constants [Array<Symbol>] Array of Style symbols - def []=( color_tag, constants ) - @scheme[to_symbol(color_tag)] = HighLine::Style.new(:name=>color_tag.to_s.downcase.to_sym, - :list=>constants, :no_index=>true) + def []=(color_tag, constants) + @scheme[to_symbol(color_tag)] = + HighLine::Style.new(name: color_tag.to_s.downcase.to_sym, + list: constants, + no_index: true) end # Retrieve the color scheme hash (in original definition format) # @return [Hash] scheme as Hash. It may be reused in a new ColorScheme. def to_hash - @scheme.inject({}) { |hsh, pair| key, value = pair; hsh[key] = value.list; hsh } + @scheme.each_with_object({}) do |pair, hsh| + key, value = pair + hsh[key] = value.list + end end - private # Return a normalized representation of a color name. - def to_symbol( t ) + def to_symbol(t) t.to_s.downcase end # Return a normalized representation of a color setting. - def to_constant( v ) + def to_constant(v) v = v.to_s if v.is_a?(Symbol) - if v.is_a?(::String) then + if v.is_a?(::String) HighLine.const_get(v.upcase) else v @@ -125,23 +129,23 @@ class HighLine # A sample ColorScheme. class SampleColorScheme < ColorScheme + SAMPLE_SCHEME = { + critical: [:yellow, :on_red], + error: [:bold, :red], + warning: [:bold, :yellow], + notice: [:bold, :magenta], + info: [:bold, :cyan], + debug: [:bold, :green], + row_even: [:cyan], + row_odd: [:magenta] + }.freeze # # Builds the sample scheme with settings for <tt>:critical</tt>, # <tt>:error</tt>, <tt>:warning</tt>, <tt>:notice</tt>, <tt>:info</tt>, # <tt>:debug</tt>, <tt>:row_even</tt>, and <tt>:row_odd</tt> colors. # - def initialize( h = nil ) - scheme = { - :critical => [ :yellow, :on_red ], - :error => [ :bold, :red ], - :warning => [ :bold, :yellow ], - :notice => [ :bold, :magenta ], - :info => [ :bold, :cyan ], - :debug => [ :bold, :green ], - :row_even => [ :cyan ], - :row_odd => [ :magenta ] - } - super(scheme) + def initialize(_h = nil) + super(SAMPLE_SCHEME) end end end diff --git a/lib/highline/compatibility.rb b/lib/highline/compatibility.rb index 33c889c..ee13fd6 100644 --- a/lib/highline/compatibility.rb +++ b/lib/highline/compatibility.rb @@ -4,13 +4,13 @@ unless STDIN.respond_to? :getbyte # HighLine adds #getbyte alias to #getc when #getbyte is not available. class IO # alias to #getc when #getbyte is not available - alias_method :getbyte, :getc + alias getbyte getc end # HighLine adds #getbyte alias to #getc when #getbyte is not available. class StringIO # alias to #getc when #getbyte is not available - alias_method :getbyte, :getc + alias getbyte getc end end @@ -18,6 +18,6 @@ unless "".respond_to? :each_line # HighLine adds #each_line alias to #each when each_line is not available. class String # alias to #each when each_line is not available. - alias_method :each_line, :each + alias each_line each end end diff --git a/lib/highline/custom_errors.rb b/lib/highline/custom_errors.rb index 2d45687..28e97df 100644 --- a/lib/highline/custom_errors.rb +++ b/lib/highline/custom_errors.rb @@ -1,5 +1,6 @@ -class HighLine +# encoding: utf-8 +class HighLine # Internal HighLine errors. module CustomErrors # An error that responds to :explanation_key diff --git a/lib/highline/import.rb b/lib/highline/import.rb index c2e6084..46cb3db 100644 --- a/lib/highline/import.rb +++ b/lib/highline/import.rb @@ -38,11 +38,11 @@ class Object # @param details [lambda] block to be called with the question # instance as argument. # @return [String] answer - def or_ask( *args, &details ) + def or_ask(*args, &details) ask(*args) do |question| question.first_answer = String(self) - details.call(question) if details + yield(question) if details end end end diff --git a/lib/highline/list.rb b/lib/highline/list.rb index 1f2af2c..6ca876f 100644 --- a/lib/highline/list.rb +++ b/lib/highline/list.rb @@ -1,10 +1,8 @@ # coding: utf-8 class HighLine - # List class with some convenience methods like {#col_down}. class List - # Original given *items* argument. # It's frozen at initialization time and # all later transformations will happen on {#list}. @@ -33,7 +31,6 @@ class HighLine attr_reader :transpose_mode - # Content are distributed first by column in col down mode. # @return [Boolean] # @@ -69,7 +66,8 @@ class HighLine build end - # Transpose the (already sliced by rows) list, turning its rows into columns. + # Transpose the (already sliced by rows) list, + # turning its rows into columns. # @return [self] def transpose first_row = @list[0] @@ -141,9 +139,7 @@ class HighLine # Set the {#row_join_string}. # @see #row_join_string - def row_join_string=(string) - @row_join_string = string - end + attr_writer :row_join_string # Returns the row join string size. # Useful for calculating the actual size of @@ -178,4 +174,4 @@ class HighLine row.compact.join(row_join_string) + "\n" end end -end
\ No newline at end of file +end diff --git a/lib/highline/list_renderer.rb b/lib/highline/list_renderer.rb index fde6ad4..cc53bf0 100644 --- a/lib/highline/list_renderer.rb +++ b/lib/highline/list_renderer.rb @@ -1,251 +1,257 @@ # coding: utf-8 -require 'highline/template_renderer' -require 'highline/wrapper' -require 'highline/list' - -# -# This class is a utility for quickly and easily laying out lists -# to be used by HighLine. -# -class HighLine::ListRenderer - # Items list - # @return [Array] - attr_reader :items - - # @return [Symbol] the current mode the List is being rendered - # @see #initialize for more details see mode parameter of #initialize - attr_reader :mode - - # Changes the behaviour of some modes. Example, in :inline mode - # the option is treated as the 'end separator' (defaults to " or ") - # @return option parameter that changes the behaviour of some modes. - attr_reader :option - - # @return [HighLine] context - attr_reader :highline - - # The only required parameters are _items_ and _highline_. - # @param items [Array] the Array of items to list - # @param mode [Symbol] controls how that list is formed - # @param option has different effects, depending on the _mode_. - # @param highline [HighLine] a HighLine instance to direct the output to. - # - # Recognized modes are: +require "highline/template_renderer" +require "highline/wrapper" +require "highline/list" + +class HighLine # - # <tt>:columns_across</tt>:: _items_ will be placed in columns, - # flowing from left to right. If given, - # _option_ is the number of columns to be - # used. When absent, columns will be - # determined based on _wrap_at_ or a - # default of 80 characters. - # <tt>:columns_down</tt>:: Identical to <tt>:columns_across</tt>, - # save flow goes down. - # <tt>:uneven_columns_across</tt>:: Like <tt>:columns_across</tt> but each - # column is sized independently. - # <tt>:uneven_columns_down</tt>:: Like <tt>:columns_down</tt> but each - # column is sized independently. - # <tt>:inline</tt>:: All _items_ are placed on a single line. - # The last two _items_ are separated by - # _option_ or a default of " or ". All - # other _items_ are separated by ", ". - # <tt>:rows</tt>:: The default mode. Each of the _items_ is - # placed on its own line. The _option_ - # parameter is ignored in this mode. + # This class is a utility for quickly and easily laying out lists + # to be used by HighLine. # - # Each member of the _items_ Array is passed through ERb and thus can contain - # their own expansions. Color escape expansions do not contribute to the - # final field width. - - def initialize(items, mode = :rows, option = nil, highline) - @highline = highline - @mode = mode - @option = option - @items = render_list_items(items) - end + class ListRenderer + # Items list + # @return [Array] + attr_reader :items + + # @return [Symbol] the current mode the List is being rendered + # @see #initialize for more details see mode parameter of #initialize + attr_reader :mode + + # Changes the behaviour of some modes. Example, in :inline mode + # the option is treated as the 'end separator' (defaults to " or ") + # @return option parameter that changes the behaviour of some modes. + attr_reader :option + + # @return [HighLine] context + attr_reader :highline + + # The only required parameters are _items_ and _highline_. + # @param items [Array] the Array of items to list + # @param mode [Symbol] controls how that list is formed + # @param option has different effects, depending on the _mode_. + # @param highline [HighLine] a HighLine instance to direct the output to. + # + # Recognized modes are: + # + # <tt>:columns_across</tt>:: _items_ will be placed in columns, + # flowing from left to right. If given, + # _option_ is the number of columns to be + # used. When absent, columns will be + # determined based on _wrap_at_ or a + # default of 80 characters. + # <tt>:columns_down</tt>:: Identical to <tt>:columns_across</tt>, + # save flow goes down. + # <tt>:uneven_columns_across</tt>:: Like <tt>:columns_across</tt> but each + # column is sized independently. + # <tt>:uneven_columns_down</tt>:: Like <tt>:columns_down</tt> but each + # column is sized independently. + # <tt>:inline</tt>:: All _items_ are placed on a single + # line. The last two _items_ are + # separated by _option_ or a default of + # " or ". All other _items_ are + # separated by ", ". + # <tt>:rows</tt>:: The default mode. Each of the _items_ + # is placed on its own line. The _option_ + # parameter is ignored in this mode. + # + # Each member of the _items_ Array is passed through ERb and thus can + # contain their own expansions. Color escape expansions do not contribute to + # the final field width. + + def initialize(items, mode = :rows, option = nil, highline) + @highline = highline + @mode = mode + @option = option + @items = render_list_items(items) + end - # Render the list using the appropriate mode and options. - # @return [String] rendered list as String - def render - return "" if items.empty? - - case mode - when :inline - list_inline_mode - when :columns_across - list_columns_across_mode - when :columns_down - list_columns_down_mode - when :uneven_columns_across - list_uneven_columns_mode - when :uneven_columns_down - list_uneven_columns_down_mode - else - list_default_mode + # Render the list using the appropriate mode and options. + # @return [String] rendered list as String + def render + return "" if items.empty? + + case mode + when :inline + list_inline_mode + when :columns_across + list_columns_across_mode + when :columns_down + list_columns_down_mode + when :uneven_columns_across + list_uneven_columns_mode + when :uneven_columns_down + list_uneven_columns_down_mode + else + list_default_mode + end end - end - private + private - def render_list_items(items) - items.to_ary.map do |item| - item = String(item) - template = ERB.new(item, nil, "%") - template_renderer = HighLine::TemplateRenderer.new(template, self, highline) - template_renderer.render + def render_list_items(items) + items.to_ary.map do |item| + item = String(item) + template = ERB.new(item, nil, "%") + template_renderer = + HighLine::TemplateRenderer.new(template, self, highline) + template_renderer.render + end end - end - def list_default_mode - items.map { |i| "#{i}\n" }.join - end + def list_default_mode + items.map { |i| "#{i}\n" }.join + end - def list_inline_mode - end_separator = option || " or " + def list_inline_mode + end_separator = option || " or " - if items.size == 1 - items.first - else - items[0..-2].join(", ") + "#{end_separator}#{items.last}" + if items.size == 1 + items.first + else + items[0..-2].join(", ") + "#{end_separator}#{items.last}" + end end - end - def list_columns_across_mode - HighLine::List.new(right_padded_items, cols: col_count).to_s - end + def list_columns_across_mode + HighLine::List.new(right_padded_items, cols: col_count).to_s + end - def list_columns_down_mode - HighLine::List.new(right_padded_items, cols: col_count, col_down: true).to_s - end + def list_columns_down_mode + HighLine::List.new( + right_padded_items, + cols: col_count, + col_down: true + ).to_s + end - def list_uneven_columns_mode(list=nil) - list ||= HighLine::List.new(items) + def list_uneven_columns_mode(list = nil) + list ||= HighLine::List.new(items) - col_max = option || items.size - col_max.downto(1) do |column_count| - list.cols = column_count - widths = get_col_widths(list) + col_max = option || items.size + col_max.downto(1) do |column_count| + list.cols = column_count + widths = get_col_widths(list) - if column_count == 1 or # last guess - inside_line_size_limit?(widths) or # good guess - option # defined by user - return pad_uneven_rows(list, widths) + if column_count == 1 || # last guess + inside_line_size_limit?(widths) || # good guess + option # defined by user + return pad_uneven_rows(list, widths) + end end end - end - def list_uneven_columns_down_mode - list = HighLine::List.new(items, col_down: true) - list_uneven_columns_mode(list) - end + def list_uneven_columns_down_mode + list = HighLine::List.new(items, col_down: true) + list_uneven_columns_mode(list) + end - def pad_uneven_rows(list, widths) - right_padded_list = Array(list).map do |row| - right_pad_row(row.compact, widths) + def pad_uneven_rows(list, widths) + right_padded_list = Array(list).map do |row| + right_pad_row(row.compact, widths) + end + stringfy_list(right_padded_list) end - stringfy_list(right_padded_list) - end - def stringfy_list(list) - list.map { |row| row_to_s(row) }.join - end + def stringfy_list(list) + list.map { |row| row_to_s(row) }.join + end - def row_to_s(row) - row.compact.join(row_join_string) + "\n" - end + def row_to_s(row) + row.compact.join(row_join_string) + "\n" + end - def right_pad_row(row, widths) - row.zip(widths).map do |field, width| - right_pad_field(field, width) + def right_pad_row(row, widths) + row.zip(widths).map do |field, width| + right_pad_field(field, width) + end end - end - def right_pad_field(field, width) - field = String(field) # nil protection - pad_size = width - actual_length(field) - field + (pad_char * pad_size) - end + def right_pad_field(field, width) + field = String(field) # nil protection + pad_size = width - actual_length(field) + field + (pad_char * pad_size) + end - def get_col_widths(lines) - lines = transpose(lines) - get_segment_widths(lines) - end + def get_col_widths(lines) + lines = transpose(lines) + get_segment_widths(lines) + end - def get_row_widths(lines) - get_segment_widths(lines) - end + def get_row_widths(lines) + get_segment_widths(lines) + end - def get_segment_widths(lines) - lines.map do |col| - actual_lengths_for(col).max + def get_segment_widths(lines) + lines.map do |col| + actual_lengths_for(col).max + end end - end - def actual_lengths_for(line) - line.map do |item| - actual_length(item) + def actual_lengths_for(line) + line.map do |item| + actual_length(item) + end end - end - def transpose(lines) - lines = Array(lines) - first_line = lines.shift - first_line.zip(*lines) - end + def transpose(lines) + lines = Array(lines) + first_line = lines.shift + first_line.zip(*lines) + end - def inside_line_size_limit?(widths) - line_size = widths.inject(0) { |sum, n| sum + n + row_join_str_size } - line_size <= line_size_limit + row_join_str_size - end + def inside_line_size_limit?(widths) + line_size = widths.reduce(0) { |sum, n| sum + n + row_join_str_size } + line_size <= line_size_limit + row_join_str_size + end - def actual_length(text) - HighLine::Wrapper.actual_length text - end + def actual_length(text) + HighLine::Wrapper.actual_length text + end - def items_max_length - @items_max_length ||= max_length(items) - end + def items_max_length + @items_max_length ||= max_length(items) + end - def max_length(items) - items.map { |item| actual_length(item) }.max - end + def max_length(items) + items.map { |item| actual_length(item) }.max + end - def line_size_limit - @line_size_limit ||= ( highline.wrap_at || 80 ) - end + def line_size_limit + @line_size_limit ||= (highline.wrap_at || 80) + end - def row_join_string - @row_join_string ||= " " - end + def row_join_string + @row_join_string ||= " " + end - def row_join_string=(string) - @row_join_string = string - end + attr_writer :row_join_string - def row_join_str_size - row_join_string.size - end + def row_join_str_size + row_join_string.size + end - def get_col_count - (line_size_limit + row_join_str_size) / - (items_max_length + row_join_str_size) - end + def col_count_calculate + (line_size_limit + row_join_str_size) / + (items_max_length + row_join_str_size) + end - def col_count - option || get_col_count - end + def col_count + option || col_count_calculate + end - def right_padded_items - items.map do |item| - right_pad_field(item, items_max_length) + def right_padded_items + items.map do |item| + right_pad_field(item, items_max_length) + end end - end - def pad_char - " " - end + def pad_char + " " + end - def row_count - (items.count / col_count.to_f).ceil + def row_count + (items.count / col_count.to_f).ceil + end end -end
\ No newline at end of file +end diff --git a/lib/highline/menu.rb b/lib/highline/menu.rb index e1834ef..5f73cd7 100644 --- a/lib/highline/menu.rb +++ b/lib/highline/menu.rb @@ -13,7 +13,8 @@ require "highline/menu/item" class HighLine # - # Menu objects encapsulate all the details of a call to {HighLine#choose HighLine#choose}. + # Menu objects encapsulate all the details of a call to + # {HighLine#choose HighLine#choose}. # Using the accessors and {Menu#choice} and {Menu#choices}, the block passed # to {HighLine#choose} can detail all aspects of menu display and control. # @@ -21,16 +22,16 @@ class HighLine # Pass +false+ to _color_ to turn off HighLine::Menu's # index coloring. # Pass a color and the Menu's indices will be colored. - def self.index_color=(color = :rgb_77bbff) - @index_color = color + class << self + attr_writer :index_color end # Initialize it self.index_color = false # Returns color used for coloring Menu's indices - def self.index_color - @index_color + class << self + attr_reader :index_color end # @@ -53,10 +54,10 @@ class HighLine # Initialize Question objects with ignored values, we'll # adjust ours as needed. # - super("Ignored", [ ], &nil) # avoiding passing the block along + super("Ignored", [], &nil) # avoiding passing the block along - @items = [ ] - @hidden_items = [ ] + @items = [] + @hidden_items = [] @help = Hash.new("There's no help for that topic.") @index = :number @@ -75,13 +76,13 @@ class HighLine @index_color = self.class.index_color # Override Questions responses, we'll set our own. - @responses = { } + @responses = {} # Context for action code. @highline = nil yield self if block_given? - init_help if @shell and not @help.empty? + init_help if @shell && !@help.empty? end # @@ -179,26 +180,27 @@ class HighLine # cli.choose do |menu| # menu.shell = true # - # menu.choice(:load, text: 'Load a file', help: "Load a file using your favourite editor.") + # menu.choice(:load, text: 'Load a file', + # help: "Load a file using your favourite editor.") # menu.choice(:save, help: "Save data in file.") # menu.choice(:quit, help: "Exit program.") # # menu.help("rules", "The rules of this system are as follows...") # end - def choice( name, help = nil, text = nil, &action ) + def choice(name, help = nil, text = nil, &action) item = Menu::Item.new(name, text: text, help: help, action: action) @items << item @help.merge!(item.item_help) - update_responses # rebuild responses based on our settings + update_responses # rebuild responses based on our settings end # - # This method helps reduce the namespaces in the original call, which would look - # like this: HighLine::Menu::Item.new(...) + # This method helps reduce the namespaces in the original call, + # which would look like this: HighLine::Menu::Item.new(...) # With #build_item, it looks like this: menu.build_item(...) - # @param *args splat args, the same args you would pass to an initialization of - # HighLine::Menu::Item + # @param *args splat args, the same args you would pass to an + # initialization of HighLine::Menu::Item # @return [HighLine::Menu::Item] the menu item def build_item(*args) @@ -206,8 +208,8 @@ class HighLine end # - # Adds an item directly to the menu. If you want more configuraiton or options, - # use this method + # Adds an item directly to the menu. If you want more configuration + # or options, use this method # # @param item [Menu::Item] item containing choice fields and more # @return [void] @@ -223,7 +225,8 @@ class HighLine # warned:</b> An _action_ set here will apply to *all* provided # _names_. This is considered to be a feature, so you can easily # hand-off interface processing to a different chunk of code. - # @param names [Array<#to_s>] menu item titles/headers/names to be displayed. + # @param names [Array<#to_s>] menu item titles/headers/names to be + # displayed. # @param action (see #choice) # @return [void] # @example (see HighLine::Menu#initialize) @@ -231,7 +234,7 @@ class HighLine # choice has more options available to you, like longer text or help (and # of course, individual actions) # - def choices( *names, &action ) + def choices(*names, &action) names.each { |n| choice(n, &action) } end @@ -242,7 +245,7 @@ class HighLine # @param action (see #choice) # @return (see #choice) - def hidden( name, help = nil, &action ) + def hidden(name, help = nil, &action) item = Menu::Item.new(name, text: name, help: help, action: action) @hidden_items << item @help.merge!(item.item_help) @@ -263,31 +266,36 @@ class HighLine # _index_suffix_ to a single space and _select_by_ to <tt>:name</tt>. # Because of this, you should make a habit of setting the _index_ first. # - def index=( style ) + def index=(style) @index = style + return unless @index == :none || @index.is_a?(::String) + # Default settings. - if @index == :none or @index.is_a?(::String) - @index_suffix = " " - @select_by = :name - end + @index_suffix = " " + @select_by = :name end # # Initializes the help system by adding a <tt>:help</tt> choice, some # action code, and the default help listing. # - def init_help( ) + def init_help return if @items.include?(:help) topics = @help.keys.sort - help_help = @help.include?("help") ? @help["help"] : - "This command will display helpful messages about " + - "functionality, like this one. To see the help for " + - "a specific topic enter:\n\thelp [TOPIC]\nTry asking " + - "for help on any of the following:\n\n" + - "<%= list(#{topics.inspect}, :columns_across) %>" - choice(:help, help_help) do |command, topic| + help_help = + if @help.include?("help") + @help["help"] + else + "This command will display helpful messages about " \ + "functionality, like this one. To see the help for " \ + "a specific topic enter:\n\thelp [TOPIC]\nTry asking " \ + "for help on any of the following:\n\n" \ + "<%= list(#{topics.inspect}, :columns_across) %>" + end + + choice(:help, help_help) do |_command, topic| topic.strip! topic.downcase! if topic.empty? @@ -302,11 +310,11 @@ class HighLine # Used to set help for arbitrary topics. Use the topic <tt>"help"</tt> # to override the default message. Mainly for internal use. # - # @param topic [String] the menu item header/title/name to be associated with - # a help message. + # @param topic [String] the menu item header/title/name to be associated + # with a help message. # @param help [String] the help message to be associated with the menu # item/title/name. - def help( topic, help ) + def help(topic, help) @help[topic] = help end @@ -339,14 +347,14 @@ class HighLine # will default to <tt>:none</tt> and _flow_ will default to # <tt>:inline</tt>. # - def layout=( new_layout ) + def layout=(new_layout) @layout = new_layout # Default settings. case @layout when :one_line, :menu_only self.index = :none - @flow = :inline + @flow = :inline end end @@ -387,12 +395,14 @@ class HighLine # rules for this Menu object. If an action was provided for the # selection, it will be executed as described in {#choice}. # - # @param highline_context [HighLine] a HighLine instance to be used as context. - # @param selection [String, Integer] index or title of the selected menu item. + # @param highline_context [HighLine] a HighLine instance to be used + # as context. + # @param selection [String, Integer] index or title of the selected + # menu item. # @param details additional parameter to be passed when in shell mode. # @return [nil, Object] if @nil_on_handled is set it returns +nil+, # else it returns the action return value. - def select( highline_context, selection, details = nil ) + def select(highline_context, selection, details = nil) # add in any hidden menu commands items = all_items @@ -423,18 +433,20 @@ class HighLine def get_item_by_letter(items, selection) item = items.find { |i| i.name == selection } return item if item - l_index = "`" # character before the letter "a" - index = items.map { "#{l_index.succ!}" }.index(selection) + + # 97 is the "a" letter at ascii table + # Ex: For "a" it will return 0, and for "c" it will return 2 + index = selection.ord - 97 items[index] end def value_for_selected_item(item, details) if item.action - if @shell - result = item.action.call(item.name, details) - else - result = item.action.call(item.name) - end + result = if @shell + item.action.call(item.name, details) + else + item.action.call(item.name) + end @nil_on_handled ? nil : result else item.name @@ -451,7 +463,7 @@ class HighLine elsif selections.is_a?(Hash) value_for_hash_selections(items, selections, details) else - fail ArgumentError, 'selections must be either Array or Hash' + raise ArgumentError, "selections must be either Array or Hash" end end @@ -512,23 +524,23 @@ class HighLine # Allows Menu to behave as a String, just like Question. Returns the # _layout_ to be rendered, which is used by HighLine.say(). # - def to_s( ) + def to_s case @layout when :list %(<%= header ? "#{header}:\n" : '' %>) + - parse_list + - show_default_if_any + - "<%= prompt %>" + parse_list + + show_default_if_any + + "<%= prompt %>" when :one_line %(<%= header ? "#{header}: " : '' %>) + - "<%= prompt %>" + - "(" + parse_list + ")" + - show_default_if_any + - "<%= prompt[/\s*$/] %>" + "<%= prompt %>" \ + "(" + parse_list + ")" + + show_default_if_any + + "<%= prompt[/\s*$/] %>" when :menu_only parse_list + - show_default_if_any + - "<%= prompt %>" + show_default_if_any + + "<%= prompt %>" else @layout end @@ -536,11 +548,11 @@ class HighLine def parse_list "<%= list( menu, #{@flow.inspect}, - #{@list_option.inspect} ) %>" + #{@list_option.inspect} ) %>" end def show_default_if_any - return default.to_s.empty? ? "" : "(#{default}) " + default.to_s.empty? ? "" : "(#{default}) " end # diff --git a/lib/highline/menu/item.rb b/lib/highline/menu/item.rb index 76e1e56..78594cf 100644 --- a/lib/highline/menu/item.rb +++ b/lib/highline/menu/item.rb @@ -1,3 +1,5 @@ +# encoding: utf-8 + class HighLine class Menu < Question # Represents an Item of a HighLine::Menu. diff --git a/lib/highline/paginator.rb b/lib/highline/paginator.rb index 48792af..9da8735 100644 --- a/lib/highline/paginator.rb +++ b/lib/highline/paginator.rb @@ -3,7 +3,6 @@ class HighLine # Take the task of paginating some piece of text given a HighLine context class Paginator - # @return [HighLine] HighLine context attr_reader :highline @@ -36,18 +35,18 @@ class HighLine # Return last line if user wants to abort paging return "...\n#{lines.last}" unless continue_paging? end - return lines.join + lines.join end # - # Ask user if they wish to continue paging output. Allows them to type "q" to - # cancel the paging process. + # Ask user if they wish to continue paging output. Allows them to + # type "q" to cancel the paging process. # def continue_paging? command = highline.new_scope.ask( "-- press enter/return to continue or q to stop -- " ) { |q| q.character = true } - command !~ /\A[qQ]\Z/ # Only continue paging if Q was not hit. + command !~ /\A[qQ]\Z/ # Only continue paging if Q was not hit. end end -end
\ No newline at end of file +end diff --git a/lib/highline/question.rb b/lib/highline/question.rb index 4f9560c..f93d4d1 100755 --- a/lib/highline/question.rb +++ b/lib/highline/question.rb @@ -8,6 +8,7 @@ # # This is Free Software. See LICENSE and COPYING for details. +require "English" require "optparse" require "date" require "pathname" @@ -59,11 +60,11 @@ class HighLine @case = nil @in = nil @first_answer = nil - @directory = Pathname.new(File.expand_path(File.dirname($0))) @glob = "*" - @user_responses = Hash.new - @internal_responses = default_responses_hash @overwrite = false + @user_responses = {} + @internal_responses = default_responses_hash + @directory = Pathname.new(File.expand_path(File.dirname($PROGRAM_NAME))) # allow block to override settings yield self if block_given? @@ -148,11 +149,11 @@ class HighLine # # Asks a yes or no confirmation question, to ensure a user knows what # they have just agreed to. The confirm attribute can be set to : - # +true+ : In this case the question will be, "Are you sure?". - # Proc : The Proc is yielded the answer given. The Proc must - # output a string which is then used as the confirm - # question. - # String : The String must use ERB syntax. The String is + # +true+ : In this case the question will be, "Are you sure?". + # Proc : The Proc is yielded the answer given. The Proc must + # output a string which is then used as the confirm + # question. + # String : The String must use ERB syntax. The String is # evaluated with access to question and answer and # is then used as the confirm question. # When set to +false+ or +nil+ (the default), answers are not confirmed. @@ -261,8 +262,8 @@ class HighLine def default_responses_hash { - :ask_on_error => "? ", - :mismatch => "Your entries didn't match." + ask_on_error: "? ", + mismatch: "Your entries didn't match." } end @@ -270,15 +271,15 @@ class HighLine # @param message_source (see #build_responses) # @return [Hash] responses hash def build_responses_new_hash(message_source) - { :ambiguous_completion => "Ambiguous choice. Please choose one of " + - choice_error_str(message_source) + '.', - :invalid_type => "You must enter a valid #{message_source}.", - :no_completion => "You must choose one of " + - choice_error_str(message_source) + '.', - :not_in_range => "Your answer isn't within the expected range " + - "(#{expected_range}).", - :not_valid => "Your answer isn't valid (must match " + - "#{validate.inspect})." } + { ambiguous_completion: "Ambiguous choice. Please choose one of " + + choice_error_str(message_source) + ".", + invalid_type: "You must enter a valid #{message_source}.", + no_completion: "You must choose one of " + + choice_error_str(message_source) + ".", + not_in_range: "Your answer isn't within the expected range " \ + "(#{expected_range}).", + not_valid: "Your answer isn't valid (must match " \ + "#{validate.inspect})." } end # This is the actual responses hash that gets used in determining output @@ -369,7 +370,7 @@ class HighLine # Returns an English explanation of the current range settings. def expected_range - expected = [ ] + expected = [] expected << "above #{above}" if above expected << "below #{below}" if below @@ -392,7 +393,7 @@ class HighLine # Returns true if _first_answer_ is set. def first_answer? - !!@first_answer + true if @first_answer end # @@ -402,9 +403,9 @@ class HighLine # are not checked. # def in_range? - (!above or answer > above) and - (!below or answer < below) and - (!@in or @in.include?(answer)) + (!above || answer > above) && + (!below || answer < below) && + (!@in || @in.include?(answer)) end # @@ -468,7 +469,7 @@ class HighLine File.basename(file) end else - [ ] + [] end end @@ -485,9 +486,9 @@ class HighLine # and case handling. # def valid_answer? - !validate or - (validate.is_a?(Regexp) and answer =~ validate) or - (validate.is_a?(Proc) and validate[answer]) + !validate || + (validate.is_a?(Regexp) && answer =~ validate) || + (validate.is_a?(Proc) && validate[answer]) end # @@ -534,11 +535,11 @@ class HighLine if confirm == true "Are you sure? " elsif confirm.is_a?(Proc) - confirm.call(self.answer) + confirm.call(answer) else # evaluate ERb under initial scope, so it will have # access to question and answer - template = ERB.new(confirm, nil, "%") + template = ERB.new(confirm, nil, "%") template_renderer = TemplateRenderer.new(template, self, highline) template_renderer.render end @@ -547,7 +548,8 @@ class HighLine # Provides the String to be asked when at an error situation. # It may be just the question itself (repeat on error). # @return [self] if :ask_on_error on responses Hash is set to :question - # @return [String] if :ask_on_error on responses Hash is set to something else + # @return [String] if :ask_on_error on responses Hash is set to + # something else def ask_on_error_msg if final_responses[:ask_on_error] == :question self @@ -564,7 +566,7 @@ class HighLine # @param highline [HighLine] context # @return [void] def show_question(highline) - highline.say(self) unless (readline && (echo == true && !limit)) + highline.say(self) unless readline && (echo == true && !limit) end # Returns an echo string that is adequate for this Question settings. @@ -577,7 +579,7 @@ class HighLine if echo == true response # any truethy value, probably a String - elsif !!echo + elsif echo echo # any falsy value, false or nil else @@ -594,11 +596,11 @@ class HighLine # def append_default if template =~ /([\t ]+)\Z/ - template << "|#{default}|#{$1}" + template << "|#{default}|#{Regexp.last_match(1)}" elsif template == "" template << "|#{default}| " elsif template[-1, 1] == "\n" - template[-2, 0] = " |#{default}|" + template[-2, 0] = " |#{default}|" else template << " |#{default}|" end @@ -606,7 +608,7 @@ class HighLine def choice_error_str(message_source) if message_source.is_a? Array - '[' + message_source.join(', ') + ']' + "[" + message_source.join(", ") + "]" else message_source.inspect end diff --git a/lib/highline/question/answer_converter.rb b/lib/highline/question/answer_converter.rb index d4067f1..76558ae 100644 --- a/lib/highline/question/answer_converter.rb +++ b/lib/highline/question/answer_converter.rb @@ -1,6 +1,6 @@ # coding: utf-8 -require 'forwardable' +require "forwardable" class HighLine class Question @@ -100,4 +100,4 @@ class HighLine end end end -end
\ No newline at end of file +end diff --git a/lib/highline/question_asker.rb b/lib/highline/question_asker.rb index 06e6647..cb8dfa8 100644 --- a/lib/highline/question_asker.rb +++ b/lib/highline/question_asker.rb @@ -1,3 +1,5 @@ +# encoding: utf-8 + class HighLine # Deals with the task of "asking" a question class QuestionAsker @@ -31,13 +33,12 @@ class HighLine question.convert if question.confirm - raise NoConfirmationQuestionError unless @highline.send(:confirm, question) + confirmation = @highline.send(:confirm, question) + raise NoConfirmationQuestionError unless confirmation end - rescue ExplainableError => e explain_error(e.explanation_key) retry - rescue ArgumentError => error case error.message when /ambiguous/ @@ -65,29 +66,27 @@ class HighLine # # @return [Array, Hash] answers def gather_answers - original_question_template = question.template verify_match = question.verify_match + answers = [] - begin # when verify_match is set this loop will repeat until unique_answers == 1 - question.template = original_question_template - + # when verify_match is set this loop will repeat until unique_answers == 1 + loop do answers = gather_answers_based_on_type - if verify_match && (@highline.send(:unique_answers, answers).size > 1) - explain_error(:mismatch) - else - verify_match = false - end - end while verify_match + break unless verify_match && + (@highline.send(:unique_answers, answers).size > 1) + + explain_error(:mismatch) + end - question.verify_match ? @highline.send(:last_answer, answers) : answers + verify_match ? @highline.send(:last_answer, answers) : answers end # Gather multiple integer values based on {Question#gather} count # @return [Array] answers def gather_integer gather_with_array do |answers| - (question.gather-1).times { answers << ask_once } + (question.gather - 1).times { answers << ask_once } end end @@ -112,7 +111,6 @@ class HighLine end end - private ## Delegate to Highline @@ -133,7 +131,7 @@ class HighLine def answer_matches_regex(answer) if question.gather.is_a?(::String) || question.gather.is_a?(Symbol) answer.to_s == question.gather.to_s - else question.gather.is_a?(Regexp) + elsif question.gather.is_a?(Regexp) answer.to_s =~ question.gather end end diff --git a/lib/highline/simulate.rb b/lib/highline/simulate.rb index c1ee6df..f92eaa3 100644 --- a/lib/highline/simulate.rb +++ b/lib/highline/simulate.rb @@ -10,12 +10,9 @@ # # adapted from https://gist.github.com/194554 - class HighLine - # Simulates Highline input for use in tests. class Simulate - # Creates a simulator with an array of Strings as a script # @param strings [Array<String>] preloaded string to be used # as input buffer when simulating. @@ -28,14 +25,15 @@ class HighLine @strings.shift end - # Simulate StringIO#getbyte by shifting a single character off of the next line of the script + # Simulate StringIO#getbyte by shifting a single character off of + # the next line of the script def getbyte line = gets - if line.length > 0 - char = line.slice! 0 - @strings.unshift line - char - end + return if line.empty? + + char = line.slice! 0 + @strings.unshift line + char end # The simulator handles its own EOF diff --git a/lib/highline/statement.rb b/lib/highline/statement.rb index 5e6e2f2..35d7961 100644 --- a/lib/highline/statement.rb +++ b/lib/highline/statement.rb @@ -1,8 +1,8 @@ # coding: utf-8 -require 'highline/wrapper' -require 'highline/paginator' -require 'highline/template_renderer' +require "highline/wrapper" +require "highline/paginator" +require "highline/template_renderer" class HighLine # This class handles proper formatting based @@ -45,6 +45,10 @@ class HighLine statement end + def self.const_missing(constant) + HighLine.const_get(constant) + end + private def stringfy(template_string) @@ -52,14 +56,16 @@ class HighLine end def format_statement - return template_string unless template_string.length > 0 + return template_string if template_string.empty? statement = render_template statement = HighLine::Wrapper.wrap(statement, highline.wrap_at) statement = HighLine::Paginator.new(highline).page_print(statement) - statement = statement.gsub(/\n(?!$)/,"\n#{highline.indentation}") if highline.multi_indent + statement = statement.gsub(/\n(?!$)/, "\n#{highline.indentation}") if + highline.multi_indent + statement end @@ -74,9 +80,5 @@ class HighLine def template @template ||= ERB.new(template_string, nil, "%") end - - def self.const_missing(constant) - HighLine.const_get(constant) - end end -end
\ No newline at end of file +end diff --git a/lib/highline/string.rb b/lib/highline/string.rb index 162cfeb..8d2e0a6 100644 --- a/lib/highline/string.rb +++ b/lib/highline/string.rb @@ -3,12 +3,13 @@ require "highline/string_extensions" class HighLine - # - # HighLine::String is a subclass of String with convenience methods added for colorization. + # HighLine::String is a subclass of String with convenience methods added + # for colorization. # # Available convenience methods include: - # * 'color' method e.g. highline_string.color(:bright_blue, :underline) + # * 'color' method e.g. highline_string.color(:bright_blue, + # :underline) # * colors e.g. highline_string.magenta # * RGB colors e.g. highline_string.rgb_ff6000 # or highline_string.rgb(255,96,0) @@ -17,19 +18,19 @@ class HighLine # or highline_string.on_rgb(255,96,0) # * styles e.g. highline_string.underline # - # Additionally, convenience methods can be chained, for instance the following are equivalent: + # Additionally, convenience methods can be chained, for instance the + # following are equivalent: # highline_string.bright_blue.blink.underline # highline_string.color(:bright_blue, :blink, :underline) # HighLine.color(highline_string, :bright_blue, :blink, :underline) # - # For those less squeamish about possible conflicts, the same convenience methods can be - # added to the built-in String class, as follows: + # For those less squeamish about possible conflicts, the same convenience + # methods can be added to the built-in String class, as follows: # # require 'highline' # Highline.colorize_strings # - class String < ::String include StringExtensions end -end
\ No newline at end of file +end diff --git a/lib/highline/string_extensions.rb b/lib/highline/string_extensions.rb index d2f2de4..f6c4c6b 100644 --- a/lib/highline/string_extensions.rb +++ b/lib/highline/string_extensions.rb @@ -1,16 +1,18 @@ # coding: utf-8 -class HighLine +class HighLine #:nodoc: # Returns a HighLine::String from any given String. # @param s [String] # @return [HighLine::String] from the given string. - def self.String(s) + def self.String(s) # rubocop:disable Naming/MethodName HighLine::String.new(s) end # HighLine extensions for String class. # Included by HighLine::String. module StringExtensions + STYLE_METHOD_NAME_PATTERN = /^(on_)?rgb_([0-9a-fA-F]{6})$/ + # Included hook. Actions to take when being included. # @param base [Class, Module] base class def self.included(base) @@ -35,7 +37,7 @@ class HighLine undef :on if method_defined? :on def on(arg) - color(('on_' + arg.to_s).to_sym) + color(("on_" + arg.to_s).to_sym) end undef :uncolor if method_defined? :uncolor @@ -57,19 +59,33 @@ class HighLine # @todo Chain existing method_missing? undef :method_missing if method_defined? :method_missing - def method_missing(method, *args, &blk) - if method.to_s =~ /^(on_)?rgb_([0-9a-fA-F]{6})$/ + def method_missing(method, *_args) + if method.to_s =~ STYLE_METHOD_NAME_PATTERN color(method) else - raise NoMethodError, "undefined method `#{method}' for #<#{self.class}:#{'%#x'%self.object_id}>" + super end end + undef :respond_to_missing if method_defined? :respond_to_missing + def respond_to_missing?(method_name, include_private = false) + method_name.to_s =~ STYLE_METHOD_NAME_PATTERN || super + end + private def setup_color_code(*colors) - color_code = colors.map{|color| color.is_a?(Numeric) ? '%02x'%color : color.to_s}.join - raise "Bad RGB color #{colors.inspect}" unless color_code =~ /^[a-fA-F0-9]{6}/ + color_code = colors.map do |color| + if color.is_a?(Numeric) + format("%02x", color) + else + color.to_s + end + end.join + + raise "Bad RGB color #{colors.inspect}" unless + color_code =~ /^[a-fA-F0-9]{6}/ + color_code end end @@ -80,28 +96,28 @@ class HighLine def self.define_builtin_style_methods(base) HighLine::COLORS.each do |color| color = color.downcase - base.class_eval <<-END + base.class_eval <<-METHOD_DEFINITION undef :#{color} if method_defined? :#{color} def #{color} color(:#{color}) end - END + METHOD_DEFINITION - base.class_eval <<-END + base.class_eval <<-METHOD_DEFINITION undef :on_#{color} if method_defined? :on_#{color} def on_#{color} on(:#{color}) end - END + METHOD_DEFINITION HighLine::STYLES.each do |style| style = style.downcase - base.class_eval <<-END + base.class_eval <<-METHOD_DEFINITION undef :#{style} if method_defined? :#{style} def #{style} color(:#{style}) end - END + METHOD_DEFINITION end end end diff --git a/lib/highline/style.rb b/lib/highline/style.rb index c53024a..773cba0 100755 --- a/lib/highline/style.rb +++ b/lib/highline/style.rb @@ -8,16 +8,14 @@ # # This is Free Software. See LICENSE and COPYING for details - -class HighLine - +class HighLine #:nodoc: # Creates a style using {.find_or_create_style} or # {.find_or_create_style_list} # @param args [Array<Style, Hash, String>] style properties # @return [Style] def self.Style(*args) args = args.compact.flatten - if args.size==1 + if args.size == 1 find_or_create_style(args.first) else find_or_create_style_list(*args) @@ -33,21 +31,22 @@ class HighLine if arg.is_a?(Style) Style.list[arg.name] || Style.index(arg) elsif arg.is_a?(::String) && arg =~ /^\e\[/ # arg is a code - if styles = Style.code_index[arg] + styles = Style.code_index[arg] + if styles styles.first else - Style.new(:code=>arg) + Style.new(code: arg) end - elsif style = Style.list[arg] - style + elsif Style.list[arg] + Style.list[arg] elsif HighLine.color_scheme && HighLine.color_scheme[arg] HighLine.color_scheme[arg] elsif arg.is_a?(Hash) Style.new(arg) elsif arg.to_s.downcase =~ /^rgb_([a-f0-9]{6})$/ - Style.rgb($1) + Style.rgb(Regexp.last_match(1)) elsif arg.to_s.downcase =~ /^on_rgb_([a-f0-9]{6})$/ - Style.rgb($1).on + Style.rgb(Regexp.last_match(1)).on else raise NameError, "#{arg.inspect} is not a defined Style" end @@ -62,12 +61,11 @@ class HighLine def self.find_or_create_style_list(*args) name = args - Style.list[name] || Style.new(:list=>args) + Style.list[name] || Style.new(list: args) end # ANSI styles to be used by HighLine. class Style - # Index the given style. # Uses @code_index (Hash) as repository. # @param style [Style] @@ -77,10 +75,12 @@ class HighLine @styles ||= {} @styles[style.name] = style end - if !style.list + unless style.list @code_index ||= {} @code_index[style.code] ||= [] - @code_index[style.code].reject!{|indexed_style| indexed_style.name == style.name} + @code_index[style.code].reject! do |indexed_style| + indexed_style.name == style.name + end @code_index[style.code] << style end style @@ -91,9 +91,9 @@ class HighLine # @return [void] def self.clear_index # reset to builtin only styles - @styles = list.select { |name, style| style.builtin } + @styles = list.select { |_name, style| style.builtin } @code_index = {} - @styles.each { |name, style| index(style) } + @styles.each_value { |style| index(style) } end # Converts all given color codes to hexadecimal and @@ -106,7 +106,7 @@ class HighLine # HighLine::Style.rgb_hex(9, 10, "11") # => "090a11" def self.rgb_hex(*colors) colors.map do |color| - color.is_a?(Numeric) ? '%02x'%color : color.to_s + color.is_a?(Numeric) ? format("%02x", color) : color.to_s end.join end @@ -117,7 +117,7 @@ class HighLine # HighLine::Style.rgb_parts("090A0B") # => [9, 10, 11] def self.rgb_parts(hex) - hex.scan(/../).map{|part| part.to_i(16)} + hex.scan(/../).map { |part| part.to_i(16) } end # Search for or create a new Style from the colors provided. @@ -132,29 +132,37 @@ class HighLine # def self.rgb(*colors) hex = rgb_hex(*colors) - name = ('rgb_' + hex).to_sym - if style = list[name] - style - else - parts = rgb_parts(hex) - new(:name=>name, :code=>"\e[38;5;#{rgb_number(parts)}m", :rgb=>parts) - end + name = ("rgb_" + hex).to_sym + style = list[name] + return style if style + + parts = rgb_parts(hex) + new(name: name, code: "\e[38;5;#{rgb_number(parts)}m", rgb: parts) end # Returns the rgb number to be used as escape code on ANSI terminals. - # @param parts [Array<Numeric>] three numerical codes for red, green and blue + # @param parts [Array<Numeric>] three numerical codes for red, green + # and blue # @return [Numeric] to be used as escape code on ANSI terminals def self.rgb_number(*parts) parts = parts.flatten - 16 + parts.inject(0) {|kode, part| kode*6 + (part/256.0*6.0).floor} + 16 + parts.reduce(0) do |kode, part| + kode * 6 + (part / 256.0 * 6.0).floor + end end # From an ANSI number (color escape code), craft an 'rgb_hex' code of it # @param ansi_number [Integer] ANSI escape code # @return [String] all color codes joined as {.rgb_hex} def self.ansi_rgb_to_hex(ansi_number) - raise "Invalid ANSI rgb code #{ansi_number}" unless (16..231).include?(ansi_number) - parts = (ansi_number-16).to_s(6).rjust(3,'0').scan(/./).map{|d| (d.to_i*255.0/6.0).ceil} + raise "Invalid ANSI rgb code #{ansi_number}" unless + (16..231).cover?(ansi_number) + parts = (ansi_number - 16). + to_s(6). + rjust(3, "0"). + scan(/./). + map { |d| (d.to_i * 255.0 / 6.0).ceil } + rgb_hex(*parts) end @@ -170,9 +178,9 @@ class HighLine # Remove any ANSI color escape sequence of the given String. # @param string [String] - # @return [String] + # @return [String] def self.uncolor(string) - string.gsub(/\e\[\d+(;\d+)*m/, '') + string.gsub(/\e\[\d+(;\d+)*m/, "") end # Style name @@ -202,7 +210,7 @@ class HighLine @builtin = defn[:builtin] if @rgb hex = self.class.rgb_hex(@rgb) - @name ||= 'rgb_' + hex + @name ||= "rgb_" + hex elsif @list @name ||= @list end @@ -228,11 +236,12 @@ class HighLine code + string + HighLine::CLEAR end - # @return [String] all codes of the Style list joined together (if a Style list) + # @return [String] all codes of the Style list joined together + # (if a Style list) # @return [String] the Style code def code if @list - @list.map{|element| HighLine.Style(element).code}.join + @list.map { |element| HighLine.Style(element).code }.join else @code end @@ -257,22 +266,30 @@ class HighLine # @param new_name [Symbol] # @param options [Hash] Style attributes to be changed # @return [Style] new Style with changed attributes - def variant(new_name, options={}) + def variant(new_name, options = {}) raise "Cannot create a variant of a style list (#{inspect})" if @list new_code = options[:code] || code if options[:increment] - raise "Unexpected code in #{inspect}" unless new_code =~ /^(.*?)(\d+)(.*)/ - new_code = $1 + ($2.to_i + options[:increment]).to_s + $3 + raise "Unexpected code in #{inspect}" unless + new_code =~ /^(.*?)(\d+)(.*)/ + + new_code = + Regexp.last_match(1) + + (Regexp.last_match(2).to_i + + options[:increment]).to_s + + Regexp.last_match(3) end new_rgb = options[:rgb] || @rgb - self.class.new(self.to_hash.merge(:name=>new_name, :code=>new_code, :rgb=>new_rgb)) + self.class.new(to_hash.merge(name: new_name, + code: new_code, + rgb: new_rgb)) end # Uses the color as background and return a new style. # @return [Style] def on - new_name = ('on_'+@name.to_s).to_sym - self.class.list[new_name] ||= variant(new_name, :increment=>10) + new_name = ("on_" + @name.to_s).to_sym + self.class.list[new_name] ||= variant(new_name, increment: 10) end # @return [Style] a brighter version of this Style @@ -288,11 +305,17 @@ class HighLine private def create_bright_variant(variant_name) - raise "Cannot create a #{name} variant of a style list (#{inspect})" if @list - new_name = ("#{variant_name}_"+@name.to_s).to_sym - new_rgb = @rgb == [0,0,0] ? [128, 128, 128] : @rgb.map {|color| color==0 ? 0 : [color+128,255].min } - - find_style(new_name) or variant(new_name, :increment=>60, :rgb=>new_rgb) + raise "Cannot create a #{name} variant of a style list (#{inspect})" if + @list + new_name = ("#{variant_name}_" + @name.to_s).to_sym + new_rgb = + if @rgb == [0, 0, 0] + [128, 128, 128] + else + @rgb.map { |color| color.zero? ? 0 : [color + 128, 255].min } + end + + find_style(new_name) || variant(new_name, increment: 60, rgb: new_rgb) end def find_style(name) diff --git a/lib/highline/template_renderer.rb b/lib/highline/template_renderer.rb index 9ac3970..e948c06 100644 --- a/lib/highline/template_renderer.rb +++ b/lib/highline/template_renderer.rb @@ -1,6 +1,6 @@ # coding: utf-8 -require 'forwardable' +require "forwardable" class HighLine # Renders an erb template taking a {Question} and a {HighLine} instance @@ -42,9 +42,9 @@ class HighLine # is not available. # @return [String] error message. def method_missing(method, *args) - "Method #{method} with args #{args.inspect} " + - "is not available on #{self.inspect}. " + - "Try #{methods(false).sort.inspect}" + "Method #{method} with args #{args.inspect} " \ + "is not available on #{inspect}. " \ + "Try #{methods(false).sort.inspect}" end # @return [Question, Menu] {#source} attribute. @@ -59,4 +59,4 @@ class HighLine HighLine.const_get(name) end end -end
\ No newline at end of file +end diff --git a/lib/highline/terminal.rb b/lib/highline/terminal.rb index a76a136..cd1d3dc 100755 --- a/lib/highline/terminal.rb +++ b/lib/highline/terminal.rb @@ -16,24 +16,17 @@ class HighLine # input and output to. # The specialized Terminals all decend from this HighLine::Terminal class class Terminal - # Probe for and return a suitable Terminal instance # @param input [IO] input stream # @param output [IO] output stream def self.get_terminal(input, output) - terminal = nil - # First of all, probe for io/console begin require "io/console" require "highline/terminal/io_console" terminal = HighLine::Terminal::IOConsole.new(input, output) rescue LoadError - end - - # Fall back to UnixStty - unless terminal - require 'highline/terminal/unix_stty' + require "highline/terminal/unix_stty" terminal = HighLine::Terminal::UnixStty.new(input, output) end @@ -57,8 +50,7 @@ class HighLine # An initialization callback. # It is called by {.get_terminal}. - def initialize_system_extensions - end + def initialize_system_extensions; end # @return [Array<Integer, Integer>] two value terminal # size like [columns, lines] @@ -67,8 +59,7 @@ class HighLine end # Enter Raw No Echo mode. - def raw_no_echo_mode - end + def raw_no_echo_mode; end # Yieds a block to be executed in Raw No Echo mode and # then restore the terminal state. @@ -80,40 +71,38 @@ class HighLine end # Restore terminal to its default mode - def restore_mode - end + def restore_mode; end # Get one character from the terminal # @return [String] one character - def get_character - end + def get_character; end # rubocop:disable Naming/AccessorMethodName # Get one line from the terminal and format accordling. # Use readline if question has readline mode set. # @param question [HighLine::Question] # @param highline [HighLine] # @param options [Hash] - def get_line(question, highline, options={}) + def get_line(question, highline) raw_answer = - if question.readline - get_line_with_readline(question, highline, options={}) - else - get_line_default(highline) - end + if question.readline + get_line_with_readline(question, highline) + else + get_line_default(highline) + end question.format_answer(raw_answer) end # Get one line using #readline_read # @param (see #get_line) - def get_line_with_readline(question, highline, options={}) - require "readline" # load only if needed + def get_line_with_readline(question, highline) + require "readline" # load only if needed question_string = highline.render_statement(question) raw_answer = readline_read(question_string, question) - if !raw_answer and highline.track_eof? + if !raw_answer && highline.track_eof? raise EOFError, "The input stream is exhausted." end @@ -140,7 +129,7 @@ class HighLine Readline.readline(prompt, true) end - $VERBOSE = old_verbose + $VERBOSE = old_verbose raw_answer end @@ -148,8 +137,8 @@ class HighLine # Get one line from terminal using default #gets method. # @param highline (see #get_line) def get_line_default(highline) - raise EOFError, "The input stream is exhausted." if highline.track_eof? and - highline.input.eof? + raise EOFError, "The input stream is exhausted." if highline.track_eof? && + highline.input.eof? highline.input.gets end @@ -157,12 +146,12 @@ class HighLine # Running on JRuby? def jruby? - defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' + defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby" end # Running on Rubinius? def rubinius? - defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx' + defined?(RUBY_ENGINE) && RUBY_ENGINE == "rbx" end # Running on Windows? @@ -190,7 +179,11 @@ class HighLine # Saves terminal state using shell stty command. def save_stty - @stty_save = `stty -g`.chomp rescue nil + @stty_save = begin + `stty -g`.chomp + rescue StandardError + nil + end end # Restores terminal state using shell stty command. diff --git a/lib/highline/terminal/io_console.rb b/lib/highline/terminal/io_console.rb index eee152f..e9ff925 100644 --- a/lib/highline/terminal/io_console.rb +++ b/lib/highline/terminal/io_console.rb @@ -21,9 +21,9 @@ class HighLine end # (see Terminal#get_character) - def get_character + def get_character # rubocop:disable Naming/AccessorMethodName input.getch # from ruby io/console end end end -end
\ No newline at end of file +end diff --git a/lib/highline/terminal/ncurses.rb b/lib/highline/terminal/ncurses.rb index 817cc23..72ffac8 100644 --- a/lib/highline/terminal/ncurses.rb +++ b/lib/highline/terminal/ncurses.rb @@ -3,9 +3,10 @@ class HighLine class Terminal # NCurses HighLine::Terminal - # @note Code migrated +UNTESTED+ from the old code base to the new terminal api. + # @note Code migrated +UNTESTED+ from the old code base to the new + # terminal api. class NCurses < Terminal - require 'ffi-ncurses' + require "ffi-ncurses" # (see Terminal#raw_no_echo_mode) def raw_no_echo_mode @@ -34,4 +35,4 @@ class HighLine end end end -end
\ No newline at end of file +end diff --git a/lib/highline/terminal/unix_stty.rb b/lib/highline/terminal/unix_stty.rb index 3b9668a..ad9c85d 100644 --- a/lib/highline/terminal/unix_stty.rb +++ b/lib/highline/terminal/unix_stty.rb @@ -5,25 +5,28 @@ class HighLine # HighLine::Terminal option that uses external "stty" program # to control terminal options. class UnixStty < Terminal - # A Unix savvy method using stty to fetch the console columns, and rows. # ... stty does not work in JRuby # @return (see Terminal#terminal_size) def terminal_size begin require "io/console" - winsize = IO.console.winsize.reverse rescue nil + winsize = begin + IO.console.winsize.reverse + rescue NoMethodError + nil + end return winsize if winsize rescue LoadError end - if /solaris/ =~ RUBY_PLATFORM and - `stty` =~ /\brows = (\d+).*\bcolumns = (\d+)/ - [$2, $1].map { |x| x.to_i } + if /solaris/ =~ RUBY_PLATFORM && + `stty` =~ /\brows = (\d+).*\bcolumns = (\d+)/ + [Regexp.last_match(2), Regexp.last_match(1)].map(&:to_i) elsif `stty size` =~ /^(\d+)\s(\d+)$/ - [$2.to_i, $1.to_i] + [Regexp.last_match(2).to_i, Regexp.last_match(1).to_i] else - [ 80, 24 ] + [80, 24] end end @@ -40,9 +43,9 @@ class HighLine end # (see Terminal#get_character) - def get_character( input = STDIN ) + def get_character(input = STDIN) input.getc end end end -end
\ No newline at end of file +end diff --git a/lib/highline/version.rb b/lib/highline/version.rb index 5b6b4f8..87be435 100644 --- a/lib/highline/version.rb +++ b/lib/highline/version.rb @@ -2,5 +2,5 @@ class HighLine # The version of the installed library. - VERSION = "2.0.0-develop.10".freeze + VERSION = "2.0.0-develop.11".freeze end diff --git a/lib/highline/wrapper.rb b/lib/highline/wrapper.rb index ae93db6..a2ab4ac 100644 --- a/lib/highline/wrapper.rb +++ b/lib/highline/wrapper.rb @@ -1,12 +1,12 @@ # coding: utf-8 -class HighLine +require "English" +class HighLine # A simple Wrapper module that is aware of ANSI escape codes. # It compensates for the ANSI escape codes so it works on the # actual (visual) line length. module Wrapper - # # Wrap a sequence of _lines_ at _wrap_at_ characters per line. Existing # newlines will not be affected by this process, but additional newlines @@ -18,24 +18,25 @@ class HighLine return text unless wrap_at wrap_at = Integer(wrap_at) - wrapped = [ ] + wrapped = [] text.each_line do |line| # take into account color escape sequences when wrapping - wrap_at = wrap_at + (line.length - actual_length(line)) + wrap_at += (line.length - actual_length(line)) while line =~ /([^\n]{#{wrap_at + 1},})/ - search = $1.dup - replace = $1.dup - if index = replace.rindex(" ", wrap_at) + search = Regexp.last_match(1).dup + replace = Regexp.last_match(1).dup + index = replace.rindex(" ", wrap_at) + if index replace[index, 1] = "\n" replace.sub!(/\n[ \t]+/, "\n") line.sub!(search, replace) else - line[$~.begin(1) + wrap_at, 0] = "\n" + line[$LAST_MATCH_INFO.begin(1) + wrap_at, 0] = "\n" end end wrapped << line end - return wrapped.join + wrapped.join end # @@ -45,8 +46,8 @@ class HighLine # @param string_with_escapes [String] any ANSI colored String # @return [Integer] length based on the visual size of the String # (without the escape codes) - def self.actual_length( string_with_escapes ) + def self.actual_length(string_with_escapes) string_with_escapes.to_s.gsub(/\e\[\d{1,2}m/, "").length end end -end
\ No newline at end of file +end diff --git a/test/acceptance/acceptance.rb b/test/acceptance/acceptance.rb index 5ba6784..508b0f6 100644 --- a/test/acceptance/acceptance.rb +++ b/test/acceptance/acceptance.rb @@ -12,7 +12,7 @@ acceptance_test_files.each { |file| load file } # Print a report -report = <<EOF +report = <<REPORT === Well done! @@ -36,22 +36,30 @@ james@grayproductions.net Date: #{Time.now.utc} HighLine::VERSION: #{HighLine::VERSION} Terminal: #{HighLine.default_instance.terminal.class} -RUBY_DESCRIPTION: #{RUBY_DESCRIPTION rescue 'not available'} -Readline::VERSION: #{Readline::VERSION rescue 'not availabe'} +RUBY_DESCRIPTION: #{begin + RUBY_DESCRIPTION + rescue NameError + 'not available' + end} +Readline::VERSION: #{begin + Readline::VERSION + rescue NameError + 'not availabe' + end} ENV['SHELL']: #{ENV['SHELL']} ENV['TERM']: #{ENV['TERM']} ENV['TERM_PROGRAM']: #{ENV['TERM_PROGRAM']} Answers: #{HighLine::AcceptanceTest.answers_for_report} -EOF +REPORT puts report -timestamp = Time.now.strftime('%Y%m%d%H%M%S') +timestamp = Time.now.strftime("%Y%m%d%H%M%S") filename = "highlinetests-#{timestamp}.log" -File.open "#{filename}", 'w+' do |f| +File.open filename.to_s, "w+" do |f| f.puts report end diff --git a/test/acceptance/acceptance_test.rb b/test/acceptance/acceptance_test.rb index 19f6dea..b77e56d 100644 --- a/test/acceptance/acceptance_test.rb +++ b/test/acceptance/acceptance_test.rb @@ -1,69 +1,71 @@ # coding: utf-8 -require 'highline/import' +require "highline/import" -class HighLine::AcceptanceTest - @@answers ||= {} +class HighLine + class AcceptanceTest + @answers ||= {} - def self.check(&block) - caller_file = File.basename(caller[0].split(":")[-3]) + class << self + attr_reader :answers + end - test = new - yield test - test.caller_file = caller_file - test.check - end + def self.check + caller_file = File.basename(caller(1..1).first.split(":")[-3]) - def self.answers - @@answers - end + test = new + yield test + test.caller_file = caller_file + test.check + end - def self.answers_for_report - answers.map do |file, answer| - "#{file}: #{answer}" - end.join("\n") - end + def self.answers_for_report + answers.map do |file, answer| + "#{file}: #{answer}" + end.join("\n") + end - # A test description to be shown to user. - # It should express what the user is - # expected to check. - attr_accessor :desc + # A test description to be shown to user. + # It should express what the user is + # expected to check. + attr_accessor :desc - # A test action to be checked by the user - attr_accessor :action + # A test action to be checked by the user + attr_accessor :action - # A text asking the confirmation if - # the action worked (y) or not (n). - attr_accessor :question + # A text asking the confirmation if + # the action worked (y) or not (n). + attr_accessor :question - # Automatically filled attribute pointing - # to the file where the current test - # source is located. So we could check - # at the report what tests passed or failed. - attr_accessor :caller_file + # Automatically filled attribute pointing + # to the file where the current test + # source is located. So we could check + # at the report what tests passed or failed. + attr_accessor :caller_file - def check - # Print a header with the test description - puts "=====" - puts " #{caller_file}" - puts "=====" - puts - puts desc + def check + # Print a header with the test description + puts "=====" + puts " #{caller_file}" + puts "=====" + puts + puts desc - # Execute the proc/lambda assigned to action - puts "---" - puts - action.call - puts - puts "---" - puts + # Execute the proc/lambda assigned to action + puts "---" + puts + action.call + puts + puts "---" + puts - # Gather the user feedback about the test - print question - answer = STDIN.gets.chomp - answer = "y" if answer.empty? - @@answers[caller_file] = answer + # Gather the user feedback about the test + print question + answer = STDIN.gets.chomp + answer = "y" if answer.empty? + HighLine::AcceptanceTest.answers[caller_file] = answer - puts + puts + end end end diff --git a/test/acceptance/at_color_output_using_erb_templates.rb b/test/acceptance/at_color_output_using_erb_templates.rb index c45f264..e17df87 100644 --- a/test/acceptance/at_color_output_using_erb_templates.rb +++ b/test/acceptance/at_color_output_using_erb_templates.rb @@ -1,6 +1,6 @@ # coding: utf-8 -require_relative 'acceptance_test' +require_relative "acceptance_test" HighLine::AcceptanceTest.check do |t| t.desc = @@ -9,7 +9,7 @@ HighLine::AcceptanceTest.check do |t| "You should see the word _grass_ " \ "colored in green color" - t.action = Proc.new do + t.action = proc do say "The <%= color('grass', :green) %> should be green!" end diff --git a/test/acceptance/at_echo_false.rb b/test/acceptance/at_echo_false.rb index 2466b8d..282ec16 100644 --- a/test/acceptance/at_echo_false.rb +++ b/test/acceptance/at_echo_false.rb @@ -1,6 +1,6 @@ # coding: utf-8 -require_relative 'acceptance_test' +require_relative "acceptance_test" HighLine::AcceptanceTest.check do |t| t.desc = @@ -12,12 +12,13 @@ HighLine::AcceptanceTest.check do |t| "When typing the characters you should not " \ "see any of them on the screen." - t.action = Proc.new do + t.action = proc do answer = ask "Enter some characters and press <enter>: " do |q| q.echo = false end puts "You've entered -> #{answer} <-" end - t.question = "Were the characters adequately hidden when you typed them (y/n)? " + t.question = "Were the characters adequately hidden " \ + "when you typed them (y/n)? " end diff --git a/test/acceptance/at_readline.rb b/test/acceptance/at_readline.rb index 8a66f09..5167394 100644 --- a/test/acceptance/at_readline.rb +++ b/test/acceptance/at_readline.rb @@ -1,6 +1,6 @@ # coding: utf-8 -require_relative 'acceptance_test' +require_relative "acceptance_test" HighLine::AcceptanceTest.check do |t| t.desc = @@ -22,12 +22,12 @@ HighLine::AcceptanceTest.check do |t| "When ready, just type 'exit' and the loop will finish.\n\n" \ "Don't forget to answer 'y' (yes) or 'n' (no) to the question at the end." - t.action = Proc.new do + t.action = proc do loop do cmd = - ask "Enter command: ", %w{ save sample exec exit load } do |q| - q.readline = true - end + ask "Enter command: ", %w[save sample exec exit load] do |q| + q.readline = true + end say("Executing \"#{cmd}\"...") break if cmd == "exit" end diff --git a/test/io_console_compatible.rb b/test/io_console_compatible.rb index c8e2e70..7ff06f5 100644 --- a/test/io_console_compatible.rb +++ b/test/io_console_compatible.rb @@ -1,7 +1,7 @@ # coding: utf-8 -require 'stringio' -require 'tempfile' +require "stringio" +require "tempfile" # # On tests, we try to simulate input output with @@ -34,4 +34,4 @@ end class StringIO include IOConsoleCompatible -end
\ No newline at end of file +end diff --git a/test/string_methods.rb b/test/string_methods.rb index 9c61359..b99d53a 100644 --- a/test/string_methods.rb +++ b/test/string_methods.rb @@ -9,25 +9,25 @@ # # String class convenience methods -module StringMethods +module StringMethods def test_color assert_equal("\e[34mstring\e[0m", @string.color(:blue)) - assert_equal("\e[1m\e[47mstring\e[0m", @string.color(:bold,:on_white)) + assert_equal("\e[1m\e[47mstring\e[0m", @string.color(:bold, :on_white)) assert_equal("\e[45mstring\e[0m", @string.on(:magenta)) assert_equal("\e[36mstring\e[0m", @string.cyan) assert_equal("\e[41m\e[5mstring\e[0m\e[0m", @string.blink.on_red) assert_equal("\e[38;5;137mstring\e[0m", @string.color(:rgb_906030)) - assert_equal("\e[38;5;101mstring\e[0m", @string.rgb('606030')) - assert_equal("\e[38;5;107mstring\e[0m", @string.rgb('60','90','30')) - assert_equal("\e[38;5;107mstring\e[0m", @string.rgb(96,144,48)) + assert_equal("\e[38;5;101mstring\e[0m", @string.rgb("606030")) + assert_equal("\e[38;5;107mstring\e[0m", @string.rgb("60", "90", "30")) + assert_equal("\e[38;5;107mstring\e[0m", @string.rgb(96, 144, 48)) assert_equal("\e[38;5;173mstring\e[0m", @string.rgb_c06030) assert_equal("\e[48;5;137mstring\e[0m", @string.color(:on_rgb_906030)) - assert_equal("\e[48;5;101mstring\e[0m", @string.on_rgb('606030')) - assert_equal("\e[48;5;107mstring\e[0m", @string.on_rgb('60','90','30')) - assert_equal("\e[48;5;107mstring\e[0m", @string.on_rgb(96,144,48)) + assert_equal("\e[48;5;101mstring\e[0m", @string.on_rgb("606030")) + assert_equal("\e[48;5;107mstring\e[0m", @string.on_rgb("60", "90", "30")) + assert_equal("\e[48;5;107mstring\e[0m", @string.on_rgb(96, 144, 48)) assert_equal("\e[48;5;173mstring\e[0m", @string.on_rgb_c06030) end - + def test_uncolor colored_string = HighLine::String("\e[38;5;137mstring\e[0m") assert_equal "string", colored_string.uncolor diff --git a/test/test_answer_converter.rb b/test/test_answer_converter.rb index 5a4497d..47bf33c 100644 --- a/test/test_answer_converter.rb +++ b/test/test_answer_converter.rb @@ -12,7 +12,7 @@ class TestAnswerConverter < Minitest::Test answer_converter = HighLine::Question::AnswerConverter.new(question) refute_equal "18", answer_converter.convert - assert_equal 18, answer_converter.convert + assert_equal 18, answer_converter.convert end def test_float_convertion @@ -21,6 +21,6 @@ class TestAnswerConverter < Minitest::Test answer_converter = HighLine::Question::AnswerConverter.new(question) refute_equal "3.14159", answer_converter.convert - assert_equal 3.14159, answer_converter.convert + assert_equal 3.14159, answer_converter.convert end -end
\ No newline at end of file +end diff --git a/test/test_color_scheme.rb b/test/test_color_scheme.rb index 9b4d61b..0716327 100644 --- a/test/test_color_scheme.rb +++ b/test/test_color_scheme.rb @@ -3,7 +3,7 @@ # tc_color_scheme.rb # -# Created by Jeremy Hinegardner on 2007-01-24. +# Created by Jeremy Hinegardner on 2007-01-24. # Copyright 2007 Jeremy Hinegardner. All rights reserved. # # This is Free Software. See LICENSE and COPYING for details. @@ -22,32 +22,37 @@ class TestColorScheme < Minitest::Test end def test_using_color_scheme - assert_equal(false,HighLine.using_color_scheme?) + refute(HighLine.using_color_scheme?) HighLine.color_scheme = HighLine::ColorScheme.new - assert_equal(true,HighLine.using_color_scheme?) + assert(true, HighLine.using_color_scheme?) end def test_scheme HighLine.color_scheme = HighLine::SampleColorScheme.new @terminal.say("This should be <%= color('warning yellow', :warning) %>.") - assert_equal("This should be \e[1m\e[33mwarning yellow\e[0m.\n",@output.string) + assert_equal("This should be \e[1m\e[33mwarning yellow\e[0m.\n", + @output.string) @output.rewind - + @terminal.say("This should be <%= color('warning yellow', 'warning') %>.") - assert_equal("This should be \e[1m\e[33mwarning yellow\e[0m.\n",@output.string) + assert_equal("This should be \e[1m\e[33mwarning yellow\e[0m.\n", + @output.string) @output.rewind @terminal.say("This should be <%= color('warning yellow', 'WarNing') %>.") - assert_equal("This should be \e[1m\e[33mwarning yellow\e[0m.\n",@output.string) + assert_equal("This should be \e[1m\e[33mwarning yellow\e[0m.\n", + @output.string) @output.rewind - + # Check that keys are available, and as expected - assert_equal ["critical", "error", "warning", "notice", "info", "debug", "row_even", "row_odd"].sort, + assert_equal %w[critical error warning notice + info debug row_even row_odd].sort, HighLine.color_scheme.keys.sort - - # Color scheme doesn't care if we use symbols or strings, and is case-insensitive + + # Color scheme doesn't care if we use symbols or strings. + # And it isn't case-sensitive warning1 = HighLine.color_scheme[:warning] warning2 = HighLine.color_scheme["warning"] warning3 = HighLine.color_scheme[:wArning] @@ -62,7 +67,7 @@ class TestColorScheme < Minitest::Test # Nonexistent keys return nil assert_nil HighLine.color_scheme[:nonexistent] - + # Same as above, for definitions defn1 = HighLine.color_scheme.definition(:warning) defn2 = HighLine.color_scheme.definition("warning") @@ -77,18 +82,19 @@ class TestColorScheme < Minitest::Test assert_equal [:bold, :yellow], defn3 assert_equal [:bold, :yellow], defn4 assert_nil HighLine.color_scheme.definition(:nonexistent) - + color_scheme_hash = HighLine.color_scheme.to_hash assert_instance_of Hash, color_scheme_hash - assert_equal ["critical", "error", "warning", "notice", "info", "debug", "row_even", "row_odd"].sort, + assert_equal %w[critical error warning notice + info debug row_even row_odd].sort, color_scheme_hash.keys.sort assert_instance_of Array, HighLine.color_scheme.definition(:warning) assert_equal [:bold, :yellow], HighLine.color_scheme.definition(:warning) # turn it back off, should raise an exception HighLine.color_scheme = nil - assert_raises(NameError) { + assert_raises(NameError) do @terminal.say("This should be <%= color('nothing at all', :error) %>.") - } + end end -end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index 65c7646..0273900 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,21 +1,21 @@ #!/usr/bin/env ruby # coding: utf-8 +require "English" + # Run code coverage only for mri -require 'simplecov' if RUBY_ENGINE == 'ruby' +require "simplecov" if RUBY_ENGINE == "ruby" # Compatibility module for StringIO, File # and Tempfile. Necessary for some tests. require "io_console_compatible" -require 'highline' +require "highline" debug_message = "Tests will be run under:\n" debug_message << " - #{HighLine.new.terminal.class}\n" debug_message << " - HighLine::VERSION #{HighLine::VERSION}\n" -if defined? RUBY_DESCRIPTION - debug_message << " - #{RUBY_DESCRIPTION}\n" -end +debug_message << " - #{RUBY_DESCRIPTION}\n" if defined? RUBY_DESCRIPTION puts debug_message diff --git a/test/test_highline.rb b/test/test_highline.rb index 76ed572..6f4d1e0 100755 --- a/test/test_highline.rb +++ b/test/test_highline.rb @@ -15,27 +15,25 @@ require "stringio" require "readline" require "tempfile" -=begin -if HighLine::CHARACTER_MODE == "Win32API" - class HighLine - # Override Windows' character reading so it's not tied to STDIN. - def get_character( input = STDIN ) - input.getc - end - end -end -=end +# if HighLine::CHARACTER_MODE == "Win32API" +# class HighLine +# # Override Windows' character reading so it's not tied to STDIN. +# def get_character( input = STDIN ) +# input.getc +# end +# end +# end class TestHighLine < Minitest::Test def setup HighLine.reset @input = StringIO.new @output = StringIO.new - @terminal = HighLine.new(@input, @output) + @terminal = HighLine.new(@input, @output) end - + def test_agree_valid_yes_answers - valid_yes_answers = %w{ y yes Y YES } + valid_yes_answers = %w[y yes Y YES] valid_yes_answers.each do |user_input| @input << "#{user_input}\n" @@ -50,7 +48,7 @@ class TestHighLine < Minitest::Test end def test_agree_valid_no_answers - valid_no_answers = %w{ n no N NO } + valid_no_answers = %w[n no N NO] valid_no_answers.each do |user_input| @input << "#{user_input}\n" @@ -65,17 +63,19 @@ class TestHighLine < Minitest::Test end def test_agree_invalid_answers - invalid_answers = [ "ye", "yuk", "nope", "Oh yes", "Oh no", "Hell no!"] + invalid_answers = ["ye", "yuk", "nope", "Oh yes", "Oh no", "Hell no!"] invalid_answers.each do |user_input| - # Each invalid answer, should be followed by a 'y' (as the question is reasked) + # Each invalid answer, should be followed by a 'y' + # (as the question is reasked) @input << "#{user_input}\ny\n" @input.rewind assert_equal true, @terminal.agree("Yes or no? ") # It reasks the question if the answer is invalid - assert_equal "Yes or no? Please enter \"yes\" or \"no\".\nYes or no? ", @output.string + assert_equal "Yes or no? Please enter \"yes\" or \"no\".\nYes or no? ", + @output.string @input.truncate(@input.rewind) @output.truncate(@output.rewind) @@ -89,7 +89,7 @@ class TestHighLine < Minitest::Test assert_equal(true, @terminal.agree("Yes or no? ", :getc)) end - + def test_agree_with_block @input << "\n\n" @input.rewind @@ -97,17 +97,17 @@ class TestHighLine < Minitest::Test assert_equal(true, @terminal.agree("Yes or no? ") { |q| q.default = "y" }) assert_equal(false, @terminal.agree("Yes or no? ") { |q| q.default = "n" }) end - + def test_ask name = "James Edward Gray II" @input << name << "\n" @input.rewind assert_equal(name, @terminal.ask("What is your name? ")) - + assert_raises(EOFError) { @terminal.ask("Any input left? ") } end - + def test_ask_string name = "James Edward Gray II" @input << name << "\n" @@ -133,59 +133,62 @@ class TestHighLine < Minitest::Test assert_instance_of HighLine::String, answer - assert_raises(EOFError) { @terminal.ask("Any input left? ", HighLine::String) } + assert_raises(EOFError) do + @terminal.ask("Any input left? ", HighLine::String) + end end def test_indent text = "Testing...\n" - @terminal.indent_level=1 + @terminal.indent_level = 1 @terminal.say(text) - assert_equal(' '*3+text, @output.string) + assert_equal(" " * 3 + text, @output.string) @output.truncate(@output.rewind) - @terminal.indent_level=3 + @terminal.indent_level = 3 @terminal.say(text) - assert_equal(' '*9+text, @output.string) + assert_equal(" " * 9 + text, @output.string) @output.truncate(@output.rewind) - @terminal.indent_level=0 - @terminal.indent_size=5 + @terminal.indent_level = 0 + @terminal.indent_size = 5 @terminal.indent(2, text) - assert_equal(' '*10+text, @output.string) + assert_equal(" " * 10 + text, @output.string) @output.truncate(@output.rewind) - @terminal.indent_level=0 - @terminal.indent_size=4 - @terminal.indent { + @terminal.indent_level = 0 + @terminal.indent_size = 4 + @terminal.indent do @terminal.say(text) - } - assert_equal(' '*4+text, @output.string) + end + assert_equal(" " * 4 + text, @output.string) @output.truncate(@output.rewind) - @terminal.indent_size=2 - @terminal.indent(3) { |t| + @terminal.indent_size = 2 + @terminal.indent(3) do |t| t.say(text) - } - assert_equal(' '*6+text, @output.string) + end + assert_equal(" " * 6 + text, @output.string) @output.truncate(@output.rewind) - @terminal.indent { |t| - t.indent { - t.indent { - t.indent { |tt| + @terminal.indent do |t| + t.indent do + t.indent do + t.indent do |tt| tt.say(text) - } - } - } - } - assert_equal(' '*8+text, @output.string) + end + end + end + end + assert_equal(" " * 8 + text, @output.string) text = "Multi\nLine\nIndentation\n" - indent = ' '*4 - @terminal.indent_level=2 + indent = " " * 4 + @terminal.indent_level = 2 @output.truncate(@output.rewind) @terminal.say(text) - assert_equal("#{indent}Multi\n#{indent}Line\n#{indent}Indentation\n", @output.string) + assert_equal("#{indent}Multi\n#{indent}Line\n#{indent}Indentation\n", + @output.string) @output.truncate(@output.rewind) @terminal.multi_indent = false @@ -194,9 +197,10 @@ class TestHighLine < Minitest::Test @output.truncate(@output.rewind) @terminal.indent(0, text, true) - assert_equal("#{indent}Multi\n#{indent}Line\n#{indent}Indentation\n", @output.string) + assert_equal("#{indent}Multi\n#{indent}Line\n#{indent}Indentation\n", + @output.string) end - + def test_newline @terminal.newline @terminal.newline @@ -209,36 +213,36 @@ class TestHighLine < Minitest::Test @input.rewind languages = [:Perl, :Python, :Ruby] - answer = @terminal.ask( "What is your favorite programming language? ", - languages ) + answer = @terminal.ask("What is your favorite programming language? ", + languages) assert_equal(languages.last, answer) @input.truncate(@input.rewind) @input << "ruby\n" @input.rewind - answer = @terminal.ask( "What is your favorite programming language? ", - languages ) do |q| + answer = @terminal.ask("What is your favorite programming language? ", + languages) do |q| q.case = :capitalize end assert_equal(languages.last, answer) - + # poor auto-complete error message @input.truncate(@input.rewind) @input << "lisp\nruby\n" @input.rewind @output.truncate(@output.rewind) - answer = @terminal.ask( "What is your favorite programming language? ", - languages ) do |q| + answer = @terminal.ask("What is your favorite programming language? ", + languages) do |q| q.case = :capitalize end assert_equal(languages.last, answer) - assert_equal( "What is your favorite programming language? " + - "You must choose one of [Perl, Python, Ruby].\n" + - "? ", @output.string ) + assert_equal("What is your favorite programming language? " \ + "You must choose one of [Perl, Python, Ruby].\n" \ + "? ", @output.string) end - + def test_case_changes @input << "jeg2\n" @input.rewind @@ -302,8 +306,8 @@ class TestHighLine < Minitest::Test @input.rewind @output.truncate(@output.rewind) - answer = @terminal.ask( "Select an option (1, 2 or 3): ", - Integer ) do |q| + answer = @terminal.ask("Select an option (1, 2 or 3): ", + Integer) do |q| q.echo = "*" q.character = true end @@ -312,33 +316,37 @@ class TestHighLine < Minitest::Test end def test_backspace_does_not_enter_prompt - @input << "\b\b" - @input.rewind - answer = @terminal.ask("Please enter your password: ") do |q| - q.echo = "*" - end - assert_equal("", answer) - assert_equal("Please enter your password: \n", @output.string) + @input << "\b\b" + @input.rewind + answer = @terminal.ask("Please enter your password: ") do |q| + q.echo = "*" + end + assert_equal("", answer) + assert_equal("Please enter your password: \n", @output.string) end def test_after_some_chars_backspace_does_not_enter_prompt_when_ascii - @input << "apple\b\b\b\b\b\b\b\b\b\b" - @input.rewind - answer = @terminal.ask("Please enter your password: ") do |q| - q.echo = "*" - end - assert_equal("", answer) - assert_equal("apple".size, @output.string.count("\b")) + @input << "apple\b\b\b\b\b\b\b\b\b\b" + @input.rewind + answer = @terminal.ask("Please enter your password: ") do |q| + q.echo = "*" + end + assert_equal("", answer) + + # There's only enough backspaces to clear the given string + assert_equal(5, @output.string.count("\b")) end def test_after_some_chars_backspace_does_not_enter_prompt_when_utf8 - @input << "maçã\b\b\b\b\b\b\b\b" - @input.rewind - answer = @terminal.ask("Please enter your password: ") do |q| - q.echo = "*" - end - assert_equal("", answer) - assert_equal("maçã".size, @output.string.count("\b")) + @input << "maçã\b\b\b\b\b\b\b\b" + @input.rewind + answer = @terminal.ask("Please enter your password: ") do |q| + q.echo = "*" + end + assert_equal("", answer) + + # There's only enough backspaces to clear the given string + assert_equal(4, @output.string.count("\b")) end def test_readline_mode @@ -353,7 +361,7 @@ class TestHighLine < Minitest::Test terminal = @terminal.terminal - if terminal.jruby? or terminal.rubinius? or terminal.windows? + if terminal.jruby? || terminal.rubinius? || terminal.windows? skip "We can't test Readline on JRuby, Rubinius and Windows yet" end @@ -364,8 +372,8 @@ class TestHighLine < Minitest::Test temp_stdin = Tempfile.new "temp_stdin" temp_stdout = Tempfile.new "temp_stdout" - Readline.input = @input = File.open(temp_stdin.path, 'w+') - Readline.output = @output = File.open(temp_stdout.path, 'w+') + Readline.input = @input = File.open(temp_stdin.path, "w+") + Readline.output = @output = File.open(temp_stdout.path, "w+") @terminal = HighLine.new(@input, @output) @@ -392,8 +400,8 @@ class TestHighLine < Minitest::Test temp_stdin = Tempfile.new "temp_stdin" temp_stdout = Tempfile.new "temp_stdout" - Readline.input = @input = File.open(temp_stdin.path, 'w+') - Readline.output = @output = File.open(temp_stdout.path, 'w+') + Readline.input = @input = File.open(temp_stdin.path, "w+") + Readline.output = @output = File.open(temp_stdout.path, "w+") @terminal = HighLine.new(@input, @output) @@ -425,9 +433,10 @@ class TestHighLine < Minitest::Test q.echo = "*" end assert_equal("you can't see me", answer) - assert_equal("Please enter some hidden text: ****************\n", @output.string) + assert_equal("Please enter some hidden text: ****************\n", + @output.string) end - + def test_character_reading # WARNING: This method does NOT cover Unix and Windows savvy testing! @input << "12345" @@ -440,7 +449,7 @@ class TestHighLine < Minitest::Test end def test_frozen_statement - @terminal.say('This is a frozen statement'.freeze) + @terminal.say("This is a frozen statement".freeze) assert_equal("This is a frozen statement\n", @output.string) end @@ -450,10 +459,10 @@ class TestHighLine < Minitest::Test @output.truncate(@output.rewind) - @terminal.say( "This should be " + - "<%= BOLD + ON_WHITE %>bold on white<%= CLEAR %>!" ) - assert_equal( "This should be \e[1m\e[47mbold on white\e[0m!\n", - @output.string ) + @terminal.say("This should be " \ + "<%= BOLD + ON_WHITE %>bold on white<%= CLEAR %>!") + assert_equal("This should be \e[1m\e[47mbold on white\e[0m!\n", + @output.string) @output.truncate(@output.rewind) @@ -462,10 +471,10 @@ class TestHighLine < Minitest::Test @output.truncate(@output.rewind) - @terminal.say( "This should be " + - "<%= color('blinking on red', :blink, :on_red) %>!" ) - assert_equal( "This should be \e[5m\e[41mblinking on red\e[0m!\n", - @output.string ) + @terminal.say("This should be " \ + "<%= color('blinking on red', :blink, :on_red) %>!") + assert_equal("This should be \e[5m\e[41mblinking on red\e[0m!\n", + @output.string) @output.truncate(@output.rewind) @@ -475,27 +484,37 @@ class TestHighLine < Minitest::Test @output.truncate(@output.rewind) @terminal.say("This should be <%= RGB_906030 %>rgb_906030<%= CLEAR %>!") - assert_equal("This should be \e[38;5;137mrgb_906030\e[0m!\n", @output.string) + assert_equal("This should be \e[38;5;137mrgb_906030\e[0m!\n", + @output.string) @output.truncate(@output.rewind) - @terminal.say("This should be <%= ON_RGB_C06030 %>on_rgb_c06030<%= CLEAR %>!") - assert_equal("This should be \e[48;5;173mon_rgb_c06030\e[0m!\n", @output.string) + @terminal.say( + "This should be <%= ON_RGB_C06030 %>on_rgb_c06030<%= CLEAR %>!" + ) + assert_equal("This should be \e[48;5;173mon_rgb_c06030\e[0m!\n", + @output.string) # Relying on const_missing assert_instance_of HighLine::Style, HighLine::ON_RGB_C06031_STYLE - assert_instance_of String , HighLine::ON_RGB_C06032 - assert_raises(NameError) { HighLine::ON_RGB_ZZZZZZ } + assert_instance_of String, HighLine::ON_RGB_C06032 + assert_raises(NameError) { HighLine::ON_RGB_ZZZZZZ } # Retrieving color_code from a style assert_equal "\e[41m", @terminal.color_code([HighLine::ON_RED_STYLE]) @output.truncate(@output.rewind) - + # Does class method work, too? - @terminal.say("This should be <%= HighLine.color('reverse underlined magenta', :reverse, :underline, :magenta) %>!") - assert_equal( "This should be \e[7m\e[4m\e[35mreverse underlined magenta\e[0m!\n", - @output.string ) + @terminal.say( + "This should be <%= HighLine.color('reverse underlined magenta', " \ + ":reverse, :underline, :magenta) %>!" + ) + + assert_equal( + "This should be \e[7m\e[4m\e[35mreverse underlined magenta\e[0m!\n", + @output.string + ) @output.truncate(@output.rewind) @@ -510,7 +529,7 @@ class TestHighLine < Minitest::Test end def test_color_setting_per_instance - require 'highline/import' + require "highline/import" old_glob_instance = HighLine.default_instance old_setting = HighLine.use_color? @@ -592,7 +611,7 @@ class TestHighLine < Minitest::Test assert_equal("This should be \e[36mcyan\e[0m!\n", @output.string) cli.say("This should be <%= color('cyan', CYAN) %>!") - assert_equal("This should be cyan!\n", cli_output.string ) + assert_equal("This should be cyan!\n", cli_output.string) gterm_output.truncate(gterm_output.rewind) @output.truncate(@output.rewind) @@ -619,23 +638,32 @@ class TestHighLine < Minitest::Test def test_uncolor # instance method - assert_equal( "This should be reverse underlined magenta!\n", - @terminal.uncolor("This should be \e[7m\e[4m\e[35mreverse underlined magenta\e[0m!\n") - ) + assert_equal( + "This should be reverse underlined magenta!\n", + @terminal.uncolor( + "This should be \e[7m\e[4m\e[35mreverse underlined magenta\e[0m!\n" + ) + ) @output.truncate(@output.rewind) # class method - assert_equal( "This should be reverse underlined magenta!\n", - HighLine.uncolor("This should be \e[7m\e[4m\e[35mreverse underlined magenta\e[0m!\n") - ) + assert_equal( + "This should be reverse underlined magenta!\n", + HighLine.uncolor( + "This should be \e[7m\e[4m\e[35mreverse underlined magenta\e[0m!\n" + ) + ) @output.truncate(@output.rewind) # RGB color - assert_equal( "This should be rgb_906030!\n", - @terminal.uncolor("This should be \e[38;5;137mrgb_906030\e[0m!\n") - ) + assert_equal( + "This should be rgb_906030!\n", + @terminal.uncolor( + "This should be \e[38;5;137mrgb_906030\e[0m!\n" + ) + ) end def test_grey_is_the_same_of_gray @@ -661,7 +689,7 @@ class TestHighLine < Minitest::Test assert_equal bright_blue_code, light_blue_code end - + def test_confirm @input << "junk.txt\nno\nsave.txt\ny\n" @input.rewind @@ -671,11 +699,11 @@ class TestHighLine < Minitest::Test q.responses[:ask_on_error] = :question end assert_equal("save.txt", answer) - assert_equal( "Enter a filename: " + - "Are you sure you want to overwrite junk.txt? " + - "Enter a filename: " + + assert_equal("Enter a filename: " \ + "Are you sure you want to overwrite junk.txt? " \ + "Enter a filename: " \ "Are you sure you want to overwrite save.txt? ", - @output.string ) + @output.string) @input.truncate(@input.rewind) @input << "junk.txt\nyes\nsave.txt\nn\n" @@ -686,29 +714,29 @@ class TestHighLine < Minitest::Test q.confirm = "Are you sure you want to overwrite <%= answer %>? " end assert_equal("junk.txt", answer) - assert_equal( "Enter a filename: " + + assert_equal("Enter a filename: " \ "Are you sure you want to overwrite junk.txt? ", - @output.string ) + @output.string) @input.truncate(@input.rewind) @input << "junk.txt\nyes\nsave.txt\nn\n" @input.rewind @output.truncate(@output.rewind) - scoped_variable = { "junk.txt" => '20mb' } + scoped_variable = { "junk.txt" => "20mb" } answer = @terminal.ask("Enter a filename: ") do |q| - q.confirm = Proc.new do |answer| - "Are you sure you want to overwrite #{answer} with size " + - "of #{scoped_variable[answer]}? " + q.confirm = proc do |checking_answer| + "Are you sure you want to overwrite #{checking_answer} with size " \ + "of #{scoped_variable[checking_answer]}? " end end assert_equal("junk.txt", answer) - assert_equal( "Enter a filename: " + - "Are you sure you want to overwrite junk.txt " + + assert_equal("Enter a filename: " \ + "Are you sure you want to overwrite junk.txt " \ "with size of 20mb? ", - @output.string ) + @output.string) end - + def test_generic_confirm_with_true @input << "junk.txt\nno\nsave.txt\ny\n" @input.rewind @@ -718,11 +746,11 @@ class TestHighLine < Minitest::Test q.responses[:ask_on_error] = :question end assert_equal("save.txt", answer) - assert_equal( "Enter a filename: " + - "Are you sure? " + - "Enter a filename: " + + assert_equal("Enter a filename: " \ + "Are you sure? " \ + "Enter a filename: " \ "Are you sure? ", - @output.string ) + @output.string) @input.truncate(@input.rewind) @input << "junk.txt\nyes\nsave.txt\nn\n" @@ -733,9 +761,9 @@ class TestHighLine < Minitest::Test q.confirm = true end assert_equal("junk.txt", answer) - assert_equal( "Enter a filename: " + + assert_equal("Enter a filename: " \ "Are you sure? ", - @output.string ) + @output.string) end def test_defaults @@ -757,8 +785,8 @@ class TestHighLine < Minitest::Test q.validate = /\Ay(?:es)?|no?|no comment\Z/i end assert_equal("No Comment", answer) - assert_equal( "Are you sexually active? |No Comment| ", - @output.string ) + assert_equal("Are you sexually active? |No Comment| ", + @output.string) end def test_default_with_String @@ -828,24 +856,24 @@ class TestHighLine < Minitest::Test end assert_equal("yes", answer) end - + def test_erb - @terminal.say( "The integers from 1 to 10 are:\n" + - "% (1...10).each do |n|\n" + - "\t<%= n %>,\n" + - "% end\n" + - "\tand 10" ) - assert_equal( "The integers from 1 to 10 are:\n" + - "\t1,\n\t2,\n\t3,\n\t4,\n\t5,\n" + + @terminal.say("The integers from 1 to 10 are:\n" \ + "% (1...10).each do |n|\n" \ + "\t<%= n %>,\n" \ + "% end\n" \ + "\tand 10") + assert_equal("The integers from 1 to 10 are:\n" \ + "\t1,\n\t2,\n\t3,\n\t4,\n\t5,\n" \ "\t6,\n\t7,\n\t8,\n\t9,\n\tand 10\n", - @output.string ) + @output.string) end - + def test_files @input << "#{File.basename(__FILE__)[0, 7]}\n" @input.rewind - - assert_equal "test_hi\n",@input.read + + assert_equal "test_hi\n", @input.read @input.rewind file = @terminal.ask("Select a file: ", File) do |q| @@ -865,7 +893,7 @@ class TestHighLine < Minitest::Test assert_instance_of(Pathname, pathname) assert_equal(File.size(__FILE__), pathname.size) end - + def test_gather_with_integer @input << "James\nDana\nStorm\nGypsy\n\n" @input.rewind @@ -873,7 +901,7 @@ class TestHighLine < Minitest::Test answers = @terminal.ask("Enter four names:") do |q| q.gather = 4 end - assert_equal(%w{James Dana Storm Gypsy}, answers) + assert_equal(%w[James Dana Storm Gypsy], answers) assert_equal("\n", @input.gets) assert_equal("Enter four names:\n", @output.string) end @@ -885,7 +913,7 @@ class TestHighLine < Minitest::Test answers = @terminal.ask("Enter four names:") do |q| q.gather = "" end - assert_equal(%w{James Dana Storm Gypsy}, answers) + assert_equal(%w[James Dana Storm Gypsy], answers) end def test_gather_with_regexp @@ -895,7 +923,7 @@ class TestHighLine < Minitest::Test answers = @terminal.ask("Enter four names:") do |q| q.gather = /^\s*$/ end - assert_equal(%w{James Dana Storm Gypsy}, answers) + assert_equal(%w[James Dana Storm Gypsy], answers) end def test_gather_with_hash @@ -903,10 +931,10 @@ class TestHighLine < Minitest::Test @input.rewind answers = @terminal.ask("<%= key %>: ", Integer) do |q| - q.gather = { "Age" => 0, "Wife's Age" => 0, "Father's Age" => 0} + q.gather = { "Age" => 0, "Wife's Age" => 0, "Father's Age" => 0 } end - assert_equal( { "Age" => 29, "Wife's Age" => 30, "Father's Age" => 49}, - answers ) + assert_equal({ "Age" => 29, "Wife's Age" => 30, "Father's Age" => 49 }, + answers) assert_equal("Age: Father's Age: Wife's Age: ", @output.string) end @@ -929,8 +957,8 @@ class TestHighLine < Minitest::Test answer = @terminal.ask("How are things going? ") do |q| q.gather = 3 q.verify_match = true - q.responses[:mismatch] = 'Typing mismatch!' - q.responses[:ask_on_error] = '' + q.responses[:mismatch] = "Typing mismatch!" + q.responses[:ask_on_error] = "" end assert_equal("all work and no play makes jack a dull boy", answer) @@ -943,7 +971,7 @@ class TestHighLine < Minitest::Test answer = @terminal.ask("<%= key %>: ") do |q| q.verify_match = true - q.gather = {"Enter a password" => '', "Please type it again" => ''} + q.gather = { "Enter a password" => "", "Please type it again" => "" } end assert_equal("Password", answer) @@ -954,21 +982,21 @@ class TestHighLine < Minitest::Test answer = @terminal.ask("<%= key %>: ") do |q| q.verify_match = true - q.responses[:mismatch] = 'Typing mismatch!' - q.responses[:ask_on_error] = '' - q.gather = {"Enter a password" => '', "Please type it again" => ''} + q.responses[:mismatch] = "Typing mismatch!" + q.responses[:ask_on_error] = "" + q.gather = { "Enter a password" => "", "Please type it again" => "" } end assert_equal("Password", answer) - assert_equal( "Enter a password: " + - "Please type it again: " + - "Typing mismatch!\n" + - "Enter a password: " + - "Please type it again: ", @output.string ) + assert_equal("Enter a password: " \ + "Please type it again: " \ + "Typing mismatch!\n" \ + "Enter a password: " \ + "Please type it again: ", @output.string) end def test_lists - digits = %w{Zero One Two Three Four Five Six Seven Eight Nine} + digits = %w[Zero One Two Three Four Five Six Seven Eight Nine] erb_digits = digits.dup erb_digits[erb_digits.index("Five")] = "<%= color('Five', :blue) %%>" @@ -978,96 +1006,96 @@ class TestHighLine < Minitest::Test @output.truncate(@output.rewind) @terminal.say("<%= list(#{digits.inspect}, :inline) %>") - assert_equal( digits[0..-2].join(", ") + " or #{digits.last}\n", - @output.string ) + assert_equal(digits[0..-2].join(", ") + " or #{digits.last}\n", + @output.string) @output.truncate(@output.rewind) @terminal.say("<%= list(#{digits.inspect}, :inline, ' and ') %>") - assert_equal( digits[0..-2].join(", ") + " and #{digits.last}\n", - @output.string ) + assert_equal(digits[0..-2].join(", ") + " and #{digits.last}\n", + @output.string) @output.truncate(@output.rewind) @terminal.say("<%= list(#{digits.inspect}, :columns_down, 3) %>") - assert_equal( "Zero Four Eight\n" + - "One Five Nine \n" + - "Two Six \n" + + assert_equal("Zero Four Eight\n" \ + "One Five Nine \n" \ + "Two Six \n" \ "Three Seven\n", - @output.string ) + @output.string) @output.truncate(@output.rewind) @terminal.say("<%= list(#{erb_digits.inspect}, :columns_down, 3) %>") - assert_equal( "Zero Four Eight\n" + - "One \e[34mFive\e[0m Nine \n" + - "Two Six \n" + + assert_equal("Zero Four Eight\n" \ + "One \e[34mFive\e[0m Nine \n" \ + "Two Six \n" \ "Three Seven\n", - @output.string ) + @output.string) colums_of_twenty = ["12345678901234567890"] * 5 - + @output.truncate(@output.rewind) @terminal.say("<%= list(#{colums_of_twenty.inspect}, :columns_down) %>") - assert_equal( "12345678901234567890 12345678901234567890 " + - "12345678901234567890\n" + + assert_equal("12345678901234567890 12345678901234567890 " \ + "12345678901234567890\n" \ "12345678901234567890 12345678901234567890\n", - @output.string ) + @output.string) @output.truncate(@output.rewind) @terminal.say("<%= list(#{digits.inspect}, :columns_across, 3) %>") - assert_equal( "Zero One Two \n" + - "Three Four Five \n" + - "Six Seven Eight\n" + + assert_equal("Zero One Two \n" \ + "Three Four Five \n" \ + "Six Seven Eight\n" \ "Nine \n", - @output.string ) - + @output.string) + colums_of_twenty.pop @output.truncate(@output.rewind) @terminal.say("<%= list( #{colums_of_twenty.inspect}, :columns_across ) %>") - assert_equal( "12345678901234567890 12345678901234567890 " + - "12345678901234567890\n" + + assert_equal("12345678901234567890 12345678901234567890 " \ + "12345678901234567890\n" \ "12345678901234567890\n", - @output.string ) + @output.string) @output.truncate(@output.rewind) - + wide = %w[0123456789 a b c d e f g h i j k l m n o p q r s t u v w x y z] @terminal.say("<%= list( #{wide.inspect}, :uneven_columns_across ) %>") - assert_equal( "0123456789 a b c d e f g h i j k l m n o " + - "p q r s t u v w\n" + + assert_equal("0123456789 a b c d e f g h i j k l m n o " \ + "p q r s t u v w\n" \ "x y z\n", - @output.string ) + @output.string) @output.truncate(@output.rewind) @terminal.say("<%= list( #{wide.inspect}, :uneven_columns_across, 10 ) %>") - assert_equal( "0123456789 a b c d e f g h i\n" + - "j k l m n o p q r s\n" + + assert_equal("0123456789 a b c d e f g h i\n" \ + "j k l m n o p q r s\n" \ "t u v w x y z\n", - @output.string ) + @output.string) @output.truncate(@output.rewind) @terminal.say("<%= list( #{wide.inspect}, :uneven_columns_down ) %>") - assert_equal( "0123456789 b d f h j l n p r t v x z\n" + + assert_equal("0123456789 b d f h j l n p r t v x z\n" \ "a c e g i k m o q s u w y\n", - @output.string ) + @output.string) @output.truncate(@output.rewind) @terminal.say("<%= list( #{wide.inspect}, :uneven_columns_down, 10 ) %>") - assert_equal( "0123456789 c f i l o r u x\n" + - "a d g j m p s v y\n" + + assert_equal("0123456789 c f i l o r u x\n" \ + "a d g j m p s v y\n" \ "b e h k n q t w z\n", - @output.string ) + @output.string) end - + def test_lists_with_zero_items modes = [nil, :rows, :inline, :columns_across, :columns_down] modes.each do |mode| @@ -1083,70 +1111,77 @@ class TestHighLine < Minitest::Test assert_equal("\n", result) end end - + def test_lists_with_one_item - items = ['Zero'] - modes = { nil => "Zero\n", - :rows => "Zero\n", - :inline => "Zero", - :columns_across => "Zero\n", - :columns_down => "Zero\n" } - + items = ["Zero"] + modes = { nil => "Zero\n", + :rows => "Zero\n", + :inline => "Zero", + :columns_across => "Zero\n", + :columns_down => "Zero\n" } + modes.each do |mode, expected| result = @terminal.list(items, mode) assert_equal(expected, result) end end - + def test_lists_with_two_items - items = ['Zero', 'One'] - modes = { nil => "Zero\nOne\n", - :rows => "Zero\nOne\n", - :inline => "Zero or One", - :columns_across => "Zero One \n", - :columns_down => "Zero One \n" } - + items = %w[Zero One] + modes = { nil => "Zero\nOne\n", + :rows => "Zero\nOne\n", + :inline => "Zero or One", + :columns_across => "Zero One \n", + :columns_down => "Zero One \n" } + modes.each do |mode, expected| result = @terminal.list(items, mode) assert_equal(expected, result) end end - + def test_lists_with_three_items - items = ['Zero', 'One', 'Two'] - modes = { nil => "Zero\nOne\nTwo\n", - :rows => "Zero\nOne\nTwo\n", - :inline => "Zero, One or Two", - :columns_across => "Zero One Two \n", - :columns_down => "Zero One Two \n" } + items = %w[Zero One Two] + modes = { nil => "Zero\nOne\nTwo\n", + :rows => "Zero\nOne\nTwo\n", + :inline => "Zero, One or Two", + :columns_across => "Zero One Two \n", + :columns_down => "Zero One Two \n" } modes.each do |mode, expected| result = @terminal.list(items, mode) assert_equal(expected, result) end end - + def test_mode - assert(%w[HighLine::Terminal::IOConsole HighLine::Terminal::NCurses HighLine::Terminal::UnixStty].include?(@terminal.terminal.character_mode), - "#{@terminal.terminal.character_mode} not in list") + main_char_modes = + %w[ HighLine::Terminal::IOConsole + HighLine::Terminal::NCurses + HighLine::Terminal::UnixStty ] + + assert( + main_char_modes.include?(@terminal.terminal.character_mode), + "#{@terminal.terminal.character_mode} not in list" + ) end - + class NameClass - def self.parse( string ) - if string =~ /^\s*(\w+),\s*(\w+)\s+(\w+)\s*$/ - self.new($2, $3, $1) - else - raise ArgumentError, "Invalid name format." - end + def self.parse(string) + raise ArgumentError, "Invalid name format." unless + string =~ /^\s*(\w+),\s*(\w+)\s+(\w+)\s*$/ + new(Regexp.last_match(2), Regexp.last_match(3), Regexp.last_match(1)) end def initialize(first, middle, last) - @first, @middle, @last = first, middle, last + @first = first + @middle = middle + @last = last end - + attr_reader :first, :middle, :last end - + def test_my_class_conversion @input << "Gray, James Edward\n" @input.rewind @@ -1164,7 +1199,7 @@ class TestHighLine < Minitest::Test assert_equal("James", answer.first) assert_equal("Edward", answer.middle) end - + def test_no_echo @input << "password\r" @input.rewind @@ -1177,7 +1212,7 @@ class TestHighLine < Minitest::Test @input.rewind @output.truncate(@output.rewind) - + answer = @terminal.ask("Pick a letter or number: ") do |q| q.character = true q.echo = false @@ -1186,7 +1221,7 @@ class TestHighLine < Minitest::Test assert_equal("a", @input.getc.chr) assert_equal("Pick a letter or number: \n", @output.string) end - + def test_correct_string_encoding_when_echo_false @input << "ação\r" # An UTF-8 portuguese word for 'action' @input.rewind @@ -1234,7 +1269,7 @@ class TestHighLine < Minitest::Test assert_equal("Type: ****\n", @output.string) assert_equal("maçã", answer) end - + def test_range_requirements @input << "112\n-541\n28\n" @input.rewind @@ -1243,13 +1278,13 @@ class TestHighLine < Minitest::Test q.in = 0..105 end assert_equal(28, answer) - assert_equal( "Tell me your age.\n" + - "Your answer isn't within the expected range " + - "(included in 0..105).\n" + - "? " + - "Your answer isn't within the expected range " + - "(included in 0..105).\n" + - "? ", @output.string ) + assert_equal("Tell me your age.\n" \ + "Your answer isn't within the expected range " \ + "(included in 0..105).\n" \ + "? " \ + "Your answer isn't within the expected range " \ + "(included in 0..105).\n" \ + "? ", @output.string) @input.truncate(@input.rewind) @input << "1\n-541\n28\n" @@ -1260,13 +1295,13 @@ class TestHighLine < Minitest::Test q.above = 3 end assert_equal(28, answer) - assert_equal( "Tell me your age.\n" + - "Your answer isn't within the expected range " + - "(above 3).\n" + - "? " + - "Your answer isn't within the expected range " + - "(above 3).\n" + - "? ", @output.string ) + assert_equal("Tell me your age.\n" \ + "Your answer isn't within the expected range " \ + "(above 3).\n" \ + "? " \ + "Your answer isn't within the expected range " \ + "(above 3).\n" \ + "? ", @output.string) @input.truncate(@input.rewind) @input << "1\n28\n-541\n" @@ -1277,13 +1312,13 @@ class TestHighLine < Minitest::Test q.below = 0 end assert_equal(-541, answer) - assert_equal( "Lowest numer you can think of?\n" + - "Your answer isn't within the expected range " + - "(below 0).\n" + - "? " + - "Your answer isn't within the expected range " + - "(below 0).\n" + - "? ", @output.string ) + assert_equal("Lowest numer you can think of?\n" \ + "Your answer isn't within the expected range " \ + "(below 0).\n" \ + "? " \ + "Your answer isn't within the expected range " \ + "(below 0).\n" \ + "? ", @output.string) @input.truncate(@input.rewind) @input << "-541\n11\n6\n" @@ -1295,13 +1330,13 @@ class TestHighLine < Minitest::Test q.below = 10 end assert_equal(6, answer) - assert_equal( "Enter a low even number: " + - "Your answer isn't within the expected range " + - "(above 0 and below 10).\n" + - "? " + - "Your answer isn't within the expected range " + - "(above 0 and below 10).\n" + - "? ", @output.string ) + assert_equal("Enter a low even number: " \ + "Your answer isn't within the expected range " \ + "(above 0 and below 10).\n" \ + "? " \ + "Your answer isn't within the expected range " \ + "(above 0 and below 10).\n" \ + "? ", @output.string) @input.truncate(@input.rewind) @input << "1\n-541\n6\n" @@ -1314,27 +1349,26 @@ class TestHighLine < Minitest::Test q.in = [2, 4, 6, 8] end assert_equal(6, answer) - assert_equal( "Enter a low even number: " + - "Your answer isn't within the expected range " + - "(above 0, below 10, and included in [2, 4, 6, 8]).\n" + - "? " + - "Your answer isn't within the expected range " + - "(above 0, below 10, and included in [2, 4, 6, 8]).\n" + - "? ", @output.string ) - end - + assert_equal("Enter a low even number: " \ + "Your answer isn't within the expected range " \ + "(above 0, below 10, and included in [2, 4, 6, 8]).\n" \ + "? " \ + "Your answer isn't within the expected range " \ + "(above 0, below 10, and included in [2, 4, 6, 8]).\n" \ + "? ", @output.string) + end + def test_reask - number = 61676 + number = 61_676 @input << "Junk!\n" << number << "\n" @input.rewind answer = @terminal.ask("Favorite number? ", Integer) assert_kind_of(Integer, number) - assert_instance_of(Fixnum, number) assert_equal(number, answer) - assert_equal( "Favorite number? " + - "You must enter a valid Integer.\n" + - "? ", @output.string ) + assert_equal("Favorite number? " \ + "You must enter a valid Integer.\n" \ + "? ", @output.string) @input.rewind @output.truncate(@output.rewind) @@ -1344,11 +1378,10 @@ class TestHighLine < Minitest::Test q.responses[:invalid_type] = "Not a valid number!" end assert_kind_of(Integer, number) - assert_instance_of(Fixnum, number) assert_equal(number, answer) - assert_equal( "Favorite number? " + - "Not a valid number!\n" + - "Favorite number? ", @output.string ) + assert_equal("Favorite number? " \ + "Not a valid number!\n" \ + "Favorite number? ", @output.string) @input.truncate(@input.rewind) @input << "gen\ngene\n" @@ -1358,29 +1391,29 @@ class TestHighLine < Minitest::Test answer = @terminal.ask("Select a mode: ", [:generate, :gentle]) assert_instance_of(Symbol, answer) assert_equal(:generate, answer) - assert_equal( "Select a mode: " + - "Ambiguous choice. " + - "Please choose one of [generate, gentle].\n" + - "? ", @output.string ) + assert_equal("Select a mode: " \ + "Ambiguous choice. " \ + "Please choose one of [generate, gentle].\n" \ + "? ", @output.string) end - + def test_response_embedding @input << "112\n-541\n28\n" @input.rewind answer = @terminal.ask("Tell me your age.", Integer) do |q| q.in = 0..105 - q.responses[:not_in_range] = "Need a #{q.answer_type}" + + q.responses[:not_in_range] = "Need a #{q.answer_type}" \ " #{q.expected_range}." end assert_equal(28, answer) - assert_equal( "Tell me your age.\n" + - "Need a Integer included in 0..105.\n" + - "? " + - "Need a Integer included in 0..105.\n" + - "? ", @output.string ) + assert_equal("Tell me your age.\n" \ + "Need a Integer included in 0..105.\n" \ + "? " \ + "Need a Integer included in 0..105.\n" \ + "? ", @output.string) end - + def test_say @terminal.say("This will have a newline.") assert_equal("This will have a newline.\n", @output.string) @@ -1401,7 +1434,7 @@ class TestHighLine < Minitest::Test assert_equal("This will not have a newline.\t", @output.string) @output.truncate(@output.rewind) - + @terminal.say("This will not\n end with a newline. ") assert_equal("This will not\n end with a newline. ", @output.string) @@ -1430,7 +1463,7 @@ class TestHighLine < Minitest::Test def test_say_handles_non_string_argument integer = 10 - hash = { :a => 20 } + hash = { a: 20 } @terminal.say(integer) assert_equal String(integer), @output.string.chomp @@ -1442,20 +1475,19 @@ class TestHighLine < Minitest::Test end def test_terminal_size - assert_instance_of(Fixnum, @terminal.terminal.terminal_size[0]) - assert_instance_of(Fixnum, @terminal.terminal.terminal_size[1]) + assert(@terminal.terminal.terminal_size[0] > 0) + assert(@terminal.terminal.terminal_size[1] > 0) end def test_type_conversion - number = 61676 + number = 61_676 @input << number << "\n" @input.rewind answer = @terminal.ask("Favorite number? ", Integer) assert_kind_of(Integer, answer) - assert_instance_of(Fixnum, answer) assert_equal(number, answer) - + @input.truncate(@input.rewind) number = 1_000_000_000_000_000_000_000_000_000_000 @input << number << "\n" @@ -1463,7 +1495,6 @@ class TestHighLine < Minitest::Test answer = @terminal.ask("Favorite number? ", Integer) assert_kind_of(Integer, answer) - assert_instance_of(Bignum, answer) assert_equal(number, answer) @input.truncate(@input.rewind) @@ -1471,10 +1502,9 @@ class TestHighLine < Minitest::Test @input << number << "\n" @input.rewind - answer = @terminal.ask( "Favorite number? ", - lambda { |n| n.to_f.abs.round } ) + answer = @terminal.ask("Favorite number? ", + ->(n) { n.to_f.abs.round }) assert_kind_of(Integer, answer) - assert_instance_of(Fixnum, answer) assert_equal(11, answer) @input.truncate(@input.rewind) @@ -1513,7 +1543,7 @@ class TestHighLine < Minitest::Test assert_instance_of(Symbol, answer) assert_equal(:generate, answer) end - + def test_validation @input << "system 'rm -rf /'\n105\n0b101_001\n" @input.rewind @@ -1522,17 +1552,17 @@ class TestHighLine < Minitest::Test q.validate = /\A(?:0b)?[01_]+\Z/ end assert_equal("0b101_001", answer) - assert_equal( "Enter a binary number: " + - "Your answer isn't valid " + - "(must match /\\A(?:0b)?[01_]+\\Z/).\n" + - "? " + - "Your answer isn't valid " + - "(must match /\\A(?:0b)?[01_]+\\Z/).\n" + - "? ", @output.string ) + assert_equal("Enter a binary number: " \ + "Your answer isn't valid " \ + "(must match /\\A(?:0b)?[01_]+\\Z/).\n" \ + "? " \ + "Your answer isn't valid " \ + "(must match /\\A(?:0b)?[01_]+\\Z/).\n" \ + "? ", @output.string) @input.truncate(@input.rewind) - @input << "Gray II, James Edward\n" + - "Gray, Dana Ann Leslie\n" + + @input << "Gray II, James Edward\n" \ + "Gray, Dana Ann Leslie\n" \ "Gray, James Edward\n" @input.rewind @@ -1546,11 +1576,11 @@ class TestHighLine < Minitest::Test end assert_equal("Gray, James Edward", answer) end - + def test_whitespace @input << " A lot\tof \t space\t \there! \n" @input.rewind - + answer = @terminal.ask("Enter a whitespace filled string: ") do |q| q.whitespace = :chomp end @@ -1603,7 +1633,7 @@ class TestHighLine < Minitest::Test end assert_equal(" A lot\tof \t space\t \there! \n", answer) end - + def test_track_eof assert_raises(EOFError) { @terminal.ask("Any input left? ") } @@ -1612,14 +1642,16 @@ class TestHighLine < Minitest::Test HighLine.default_instance = HighLine.new(StringIO.new, StringIO.new) HighLine.track_eof = false begin - require 'highline/import' - ask("And now? ") # this will still blow up, nothing available - rescue - refute_equal(EOFError, $!.class) # but HighLine's safe guards are off + require "highline/import" + # this will still blow up, nothing available + ask("And now? ") + rescue StandardError + # but HighLine's safe guards are off + refute_equal(EOFError, $ERROR_INFO.class) end HighLine.default_instance = old_instance end - + def test_version refute_nil(HighLine::VERSION) assert_instance_of(String, HighLine::VERSION) diff --git a/test/test_import.rb b/test/test_import.rb index 40ff56d..c84c5fd 100644 --- a/test/test_import.rb +++ b/test/test_import.rb @@ -28,14 +28,14 @@ class TestImport < Minitest::Test # If correctly initialized, it will contain several ins vars. refute_empty HighLine.default_instance.instance_variables end - + def test_or_ask old_instance = HighLine.default_instance - + input = StringIO.new output = StringIO.new - HighLine.default_instance = HighLine.new(input, output) - + HighLine.default_instance = HighLine.new(input, output) + input << "10\n" input.rewind @@ -45,15 +45,15 @@ class TestImport < Minitest::Test assert_equal(20, "20".or_ask("How much? ", Integer)) assert_equal(20, 20.or_ask("How much? ", Integer)) - + assert_equal(10, 20.or_ask("How much? ", Integer) { |q| q.in = 1..10 }) ensure HighLine.default_instance = old_instance end - + def test_redirection old_instance = HighLine.default_instance - + HighLine.default_instance = HighLine.new(nil, (output = StringIO.new)) say("Testing...") assert_equal("Testing...\n", output.string) diff --git a/test/test_list.rb b/test/test_list.rb index 6e4c1de..ce982a8 100644 --- a/test/test_list.rb +++ b/test/test_list.rb @@ -7,16 +7,16 @@ require "highline/list" class TestHighLineList < Minitest::Test def setup - @items = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" ] + @items = %w[a b c d e f g h i j] end def test_in_2_cols list_in_two_cols = - [ [ "a", "b" ], - [ "c", "d" ], - [ "e", "f" ], - [ "g", "h" ], - [ "i", "j" ] ] + [%w[a b], + %w[c d], + %w[e f], + %w[g h], + %w[i j]] highline_list = HighLine::List.new(@items, cols: 2) @@ -25,11 +25,11 @@ class TestHighLineList < Minitest::Test def test_in_2_cols_col_down col_down_list = - [ [ "a", "f"], - [ "b", "g"], - [ "c", "h"], - [ "d", "i"], - [ "e", "j"] ] + [%w[a f], + %w[b g], + %w[c h], + %w[d i], + %w[e j]] highline_list = HighLine::List.new(@items, cols: 2, col_down: true) @@ -38,8 +38,8 @@ class TestHighLineList < Minitest::Test def test_in_2_cols_transposed transposed_list = - [ [ "a", "c", "e", "g", "i" ], - [ "b", "d", "f", "h", "j" ] ] + [%w[a c e g i], + %w[b d f h j]] highline_list = HighLine::List.new(@items, cols: 2, transpose: true) @@ -48,13 +48,13 @@ class TestHighLineList < Minitest::Test def test_in_3_cols list_in_three_cols = - [ [ "a", "b", "c" ], - [ "d", "e", "f" ], - [ "g", "h", "i" ], - [ "j" ] ] + [%w[a b c], + %w[d e f], + %w[g h i], + ["j"]] highline_list = HighLine::List.new(@items, cols: 3) assert_equal list_in_three_cols, highline_list.list end -end
\ No newline at end of file +end diff --git a/test/test_menu.rb b/test/test_menu.rb index 402b47d..d9c692e 100644 --- a/test/test_menu.rb +++ b/test/test_menu.rb @@ -90,7 +90,11 @@ class TestMenu < Minitest::Test # Default: menu.flow = :rows menu.choice "Unicode right single quotation mark: ’" end - assert_equal("1. Unicode right single quotation mark: ’\n? ".encode(@output.external_encoding, { :undef => :replace }), @output.string) + assert_equal( + "1. Unicode right single quotation mark: ’\n? ". + encode(@output.external_encoding, undef: :replace), + @output.string + ) end def test_text_override_index_selects_name @@ -102,8 +106,8 @@ class TestMenu < Minitest::Test menu.choice("Sample2", nil, "Sample1") end assert_equal(selected, "Sample1") - assert_equal("1. Sample2\n" + - "2. Sample1\n" + + assert_equal("1. Sample2\n" \ + "2. Sample1\n" \ "? ", @output.string) end @@ -116,8 +120,8 @@ class TestMenu < Minitest::Test menu.choice("Sample2", nil, "Sample1") end assert_equal(selected, "Sample2") - assert_equal("1. Sample2\n" + - "2. Sample1\n" + + assert_equal("1. Sample2\n" \ + "2. Sample1\n" \ "? ", @output.string) end @@ -130,8 +134,8 @@ class TestMenu < Minitest::Test menu.add_item(HighLine::Menu::Item.new("Sample2", text: "Sample1")) end assert_equal(selected, "Sample1") - assert_equal("1. Sample2\n" + - "2. Sample1\n" + + assert_equal("1. Sample2\n" \ + "2. Sample1\n" \ "? ", @output.string) end @@ -144,8 +148,8 @@ class TestMenu < Minitest::Test menu.add_item(HighLine::Menu::Item.new("Sample2", text: "Sample1")) end assert_equal(selected, "Sample2") - assert_equal("1. Sample2\n" + - "2. Sample1\n" + + assert_equal("1. Sample2\n" \ + "2. Sample1\n" \ "? ", @output.string) end @@ -158,8 +162,8 @@ class TestMenu < Minitest::Test menu.add_item(menu.build_item("Sample2", text: "Sample1")) end assert_equal(selected, "Sample2") - assert_equal("1. Sample2\n" + - "2. Sample1\n" + + assert_equal("1. Sample2\n" \ + "2. Sample1\n" \ "? ", @output.string) end @@ -178,22 +182,22 @@ class TestMenu < Minitest::Test menu.help("rules", "The rules of this system are as follows...") end end - assert_equal( "1. load\n2. save\n3. quit\n4. help\n? " + - "This command will display helpful messages about " + - "functionality, like this one. To see the help for a " + - "specific topic enter:\n" + - "\thelp [TOPIC]\n" + - "Try asking for help on any of the following:\n" + - "\nload quit rules save \n" + - "1. load\n2. save\n3. quit\n4. help\n? " + - "= load\n\n" + - "Load a file.\n" + - "1. load\n2. save\n3. quit\n4. help\n? " + - "= rules\n\n" + - "The rules of this system are as follows...\n" + - "1. load\n2. save\n3. quit\n4. help\n? " + - "= missing\n\n" + - "There's no help for that topic.\n", @output.string ) + assert_equal("1. load\n2. save\n3. quit\n4. help\n? " \ + "This command will display helpful messages about " \ + "functionality, like this one. To see the help for a " \ + "specific topic enter:\n" \ + "\thelp [TOPIC]\n" \ + "Try asking for help on any of the following:\n" \ + "\nload quit rules save \n" \ + "1. load\n2. save\n3. quit\n4. help\n? " \ + "= load\n\n" \ + "Load a file.\n" \ + "1. load\n2. save\n3. quit\n4. help\n? " \ + "= rules\n\n" \ + "The rules of this system are as follows...\n" \ + "1. load\n2. save\n3. quit\n4. help\n? " \ + "= missing\n\n" \ + "There's no help for that topic.\n", @output.string) end def test_index @@ -238,7 +242,7 @@ class TestMenu < Minitest::Test @input.rewind @terminal.choose do |menu| - menu.index = "*" + menu.index = "*" menu.choice "Sample1" menu.choice "Sample2" @@ -265,7 +269,7 @@ class TestMenu < Minitest::Test assert_equal( HighLine.color("1. ", index_color) + "Sample1\n" + HighLine.color("2. ", index_color) + "Sample2\n" + - HighLine.color("3. ", index_color) + "Sample3\n" + + HighLine.color("3. ", index_color) + "Sample3\n" \ "? ", @output.string ) @@ -323,8 +327,8 @@ class TestMenu < Minitest::Test colored_asterix = HighLine.color("* ", index_color) assert_equal( - "#{colored_asterix}Sample1\n" + - "#{colored_asterix}Sample2\n" + + "#{colored_asterix}Sample1\n" \ + "#{colored_asterix}Sample2\n" \ "#{colored_asterix}Sample3\n? ", @output.string ) @@ -343,8 +347,8 @@ class TestMenu < Minitest::Test @terminal.choose(:load, :save, :quit) do |menu| menu.header = "File Menu" end - assert_equal( "File Menu:\n" + - "1. load\n2. save\n3. quit\n? ", @output.string ) + assert_equal("File Menu:\n" \ + "1. load\n2. save\n3. quit\n? ", @output.string) @input.rewind @output.truncate(@output.rewind) @@ -354,14 +358,14 @@ class TestMenu < Minitest::Test menu.header = "File Menu" menu.prompt = "Operation? " end - assert_equal( "File Menu: Operation? " + - "(load, save or quit) ", @output.string ) + assert_equal("File Menu: Operation? " \ + "(load, save or quit) ", @output.string) @input.rewind @output.truncate(@output.rewind) @terminal.choose(:load, :save, :quit) do |menu| - menu.layout = :menu_only + menu.layout = :menu_only end assert_equal("load, save or quit? ", @output.string) @@ -369,7 +373,7 @@ class TestMenu < Minitest::Test @output.truncate(@output.rewind) @terminal.choose(:load, :save, :quit) do |menu| - menu.layout = '<%= list(menu) %>File Menu: ' + menu.layout = "<%= list(menu) %>File Menu: " end assert_equal("1. load\n2. save\n3. quit\nFile Menu: ", @output.string) end @@ -391,9 +395,9 @@ class TestMenu < Minitest::Test # Shows that by default proc results are returned. output = @terminal.choose do |menu| - menu.choice "Sample1" do "output1" end - menu.choice "Sample2" do "output2" end - menu.choice "Sample3" do "output3" end + menu.choice("Sample1") { "output1" } + menu.choice("Sample2") { "output2" } + menu.choice("Sample3") { "output3" } end assert_equal("output3", output) @@ -402,12 +406,12 @@ class TestMenu < Minitest::Test # _nil_on_handled to +true+. # output = @terminal.choose do |menu| - menu.nil_on_handled = true - menu.choice "Sample1" do "output1" end - menu.choice "Sample2" do "output2" end - menu.choice "Sample3" do "output3" end + menu.nil_on_handled = true + menu.choice("Sample1") { "output1" } + menu.choice("Sample2") { "output2" } + menu.choice("Sample3") { "output3" } end - assert_equal(nil, output) + assert_nil output # Shows that a menu item without a proc will be returned no matter what. output = @terminal.choose do |menu| @@ -445,7 +449,7 @@ class TestMenu < Minitest::Test menu.character = :getc end assert_equal(:Save, answer) - assert_equal(?a, @input.getc) + assert_equal("a", @input.getc) end def test_select_by @@ -527,7 +531,7 @@ class TestMenu < Minitest::Test @input.rewind selected = @terminal.choose do |menu| - menu.index = :letter + menu.index = :letter menu.choice :save menu.choice :load menu.choice :quit @@ -596,31 +600,32 @@ class TestMenu < Minitest::Test assert_equal(selected, 3) # Make sure paging message appeared - assert( @output.string.index('press enter/return to continue or q to stop'), - "Paging message did not appear." ) + assert(@output.string.index("press enter/return to continue or q to stop"), + "Paging message did not appear.") # Make sure it only appeared once - assert( @output.string !~ /q to stop.*q to stop/m, - "Paging message appeared more than once." ) + assert(@output.string !~ /q to stop.*q to stop/m, + "Paging message appeared more than once.") end def test_autocomplete_prompt @input << "lisp\nRuby\n" @input.rewind - answer = @terminal.choose do |menu| + # answer = + @terminal.choose do |menu| menu.choice(:Perl) menu.choice(:Python) menu.choice(:Ruby) menu.prompt = "What is your favorite programming language? " end - languages = [:Perl, :Python, :Ruby] - assert_equal("1. Perl\n" + - "2. Python\n" + - "3. Ruby\n" + - "What is your favorite programming language? " + - "You must choose one of [1, 2, 3, Perl, Python, Ruby].\n" + - "? ", @output.string ) + + assert_equal("1. Perl\n" \ + "2. Python\n" \ + "3. Ruby\n" \ + "What is your favorite programming language? " \ + "You must choose one of [1, 2, 3, Perl, Python, Ruby].\n" \ + "? ", @output.string) end # Issue #180 - https://github.com/JEG2/highline/issues/180 @@ -628,7 +633,8 @@ class TestMenu < Minitest::Test @input << "2\n1\n" @input.rewind - selected = @terminal.choose do |menu| + # selected = + @terminal.choose do |menu| menu.responses[:ask_on_error] = "> " menu.prompt = "> " menu.choice :exit, "Exit cube editor" @@ -637,7 +643,9 @@ class TestMenu < Minitest::Test prompt = "> " first_asking = "1. exit\n" error_message = "You must choose one of [1, exit].\n" - complete_interaction = first_asking + prompt + error_message + prompt # Same prompt when repeating question + + # Same prompt when repeating question + complete_interaction = first_asking + prompt + error_message + prompt assert_equal complete_interaction, @output.string end @@ -652,14 +660,14 @@ class TestMenu < Minitest::Test menu.choice "Sample2" menu.choice "last" end - assert_equal(["Sample1", "last"], selected) + assert_equal(%w[Sample1 last], selected) - assert_equal("1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + - "? 1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + + assert_equal("1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ + "? 1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ "? ", @output.string) end @@ -675,12 +683,12 @@ class TestMenu < Minitest::Test end assert_equal(["Sample1"], selected) - assert_equal("1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + - "? 1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + + assert_equal("1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ + "? 1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ "? ", @output.string) end @@ -696,12 +704,12 @@ class TestMenu < Minitest::Test end assert_equal(["Sample1"], selected) - assert_equal("1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + - "? 1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + + assert_equal("1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ + "? 1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ "? ", @output.string) end @@ -717,12 +725,12 @@ class TestMenu < Minitest::Test end assert_equal(["Sample1"], selected) - assert_equal("1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + - "? 1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + + assert_equal("1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ + "? 1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ "? ", @output.string) end @@ -738,12 +746,12 @@ class TestMenu < Minitest::Test end assert_equal({ "First" => "Sample1", second: "last" }, selected) - assert_equal("1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + - "? 1. Sample1\n" + - "2. Sample2\n" + - "3. last\n" + + assert_equal("1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ + "? 1. Sample1\n" \ + "2. Sample2\n" \ + "3. last\n" \ "? ", @output.string) end end diff --git a/test/test_paginator.rb b/test/test_paginator.rb index 6dfa15b..39036ee 100644 --- a/test/test_paginator.rb +++ b/test/test_paginator.rb @@ -19,13 +19,13 @@ class TestHighLinePaginator < Minitest::Test @input << "\n\n" @input.rewind - @terminal.say((1..50).map { |n| "This is line #{n}.\n"}.join) - assert_equal( (1..22).map { |n| "This is line #{n}.\n"}.join + + @terminal.say((1..50).map { |n| "This is line #{n}.\n" }.join) + assert_equal((1..22).map { |n| "This is line #{n}.\n" }.join + "\n-- press enter/return to continue or q to stop -- \n\n" + - (23..44).map { |n| "This is line #{n}.\n"}.join + + (23..44).map { |n| "This is line #{n}.\n" }.join + "\n-- press enter/return to continue or q to stop -- \n\n" + - (45..50).map { |n| "This is line #{n}.\n"}.join, - @output.string ) + (45..50).map { |n| "This is line #{n}.\n" }.join, + @output.string) end def test_statement_lines_count_equal_to_page_at_shouldnt_paginate @@ -70,4 +70,4 @@ class TestHighLinePaginator < Minitest::Test # expect not to raise an error on next line @terminal.say(list) end -end
\ No newline at end of file +end diff --git a/test/test_question_asker.rb b/test/test_question_asker.rb index 90eef04..28ab47a 100644 --- a/test/test_question_asker.rb +++ b/test/test_question_asker.rb @@ -1,3 +1,5 @@ +# encoding: utf-8 + require "test_helper" class TestQuestion < Minitest::Test diff --git a/test/test_simulator.rb b/test/test_simulator.rb index 5f1f305..efbebf0 100644 --- a/test/test_simulator.rb +++ b/test/test_simulator.rb @@ -1,3 +1,5 @@ +# encoding: utf-8 + require "test_helper" require "highline/import" @@ -21,4 +23,4 @@ class SimulatorTest < Minitest::Test assert_equal "18", age end end -end
\ No newline at end of file +end diff --git a/test/test_string_extension.rb b/test/test_string_extension.rb index 9f87294..125f48e 100644 --- a/test/test_string_extension.rb +++ b/test/test_string_extension.rb @@ -13,7 +13,6 @@ require "highline" require "stringio" require "string_methods" - # FakeString is here just to avoid # using HighLine.colorize_strings # on tests @@ -35,16 +34,19 @@ class TestStringExtension < Minitest::Test include StringMethods def test_Highline_String_is_yaml_serializable - require 'yaml' - unless Gem::Version.new(YAML::VERSION) < Gem::Version.new("2.0.2") - highline_string = HighLine::String.new("Yaml didn't messed with HighLine::String") - yaml_highline_string = highline_string.to_yaml - yaml_loaded_string = YAML.load(yaml_highline_string) - - assert_equal "Yaml didn't messed with HighLine::String", yaml_loaded_string - assert_equal highline_string, yaml_loaded_string - assert_instance_of HighLine::String, yaml_loaded_string - end + require "yaml" + return if Gem::Version.new(YAML::VERSION) < Gem::Version.new("2.0.2") + + highline_string = + HighLine::String.new("Yaml didn't messed with HighLine::String") + yaml_highline_string = highline_string.to_yaml + yaml_loaded_string = + YAML.safe_load(yaml_highline_string, [HighLine::String]) + + assert_equal "Yaml didn't messed with HighLine::String", + yaml_loaded_string + assert_equal highline_string, yaml_loaded_string + assert_instance_of HighLine::String, yaml_loaded_string end def test_highline_string_respond_to_color @@ -63,10 +65,16 @@ class TestStringExtension < Minitest::Test def test_String_includes_StringExtension_when_receives_colorize_strings @include_received = 0 - caller = Proc.new { @include_received += 1 } + caller = proc { @include_received += 1 } ::String.stub :include, caller do HighLine.colorize_strings end assert_equal 1, @include_received end + + def test_respond_to_dynamic_style_methods + string = HighLine::String.new("pirarucu") + assert_respond_to(string, :on_rgb_123456) + assert_respond_to(string, :rgb_abcdef) + end end diff --git a/test/test_string_highline.rb b/test/test_string_highline.rb index 87db9c6..040e1a2 100644 --- a/test/test_string_highline.rb +++ b/test/test_string_highline.rb @@ -23,19 +23,19 @@ class TestHighLineString < Minitest::Test # Basic constructor assert_equal HighLine::String, @string.class assert_equal "string", @string - + # Alternative constructor method new_string = HighLine::String("string") assert_equal HighLine::String, new_string.class assert_equal @string, new_string - + # String methods work assert_equal 6, @string.size assert_equal "STRING", @string.upcase end include StringMethods - + def test_string_class_is_unchanged assert_raises(::NoMethodError) { "string".color(:blue) } end diff --git a/test/test_style.rb b/test/test_style.rb index 2c44401..3f3e288 100755 --- a/test/test_style.rb +++ b/test/test_style.rb @@ -13,15 +13,14 @@ require "highline" require "stringio" class TestStyle < Minitest::Test - def setup HighLine.reset @input = StringIO.new @output = StringIO.new - @terminal = HighLine.new(@input, @output) - @style1 = HighLine::Style.new(:name=>:foo, :code=>"\e[99m", :rgb=>[1,2,3]) - @style2 = HighLine::Style.new(:name=>:lando, :code=>"\e[98m") - @style3 = HighLine::Style.new(:name=>[:foo, :lando], :list=>[:foo, :lando]) + @terminal = HighLine.new(@input, @output) + @style1 = HighLine::Style.new(name: :foo, code: "\e[99m", rgb: [1, 2, 3]) + @style2 = HighLine::Style.new(name: :lando, code: "\e[98m") + @style3 = HighLine::Style.new(name: [:foo, :lando], list: [:foo, :lando]) @style4 = HighLine::Style(:rgb_654321) @added_styles_on_setup = 4 # update here if added more styles @added_codes_to_index = 3 # :foo, :lando and :rgb_654321 @@ -39,15 +38,18 @@ class TestStyle < Minitest::Test def test_clear_index_reset_code_index_to_builtin code_index = HighLine::Style.code_index - code_index_array = code_index.map { |code, style_array| style_array }.flatten - expected_code_index_array_size = code_index_array.size - @added_codes_to_index + code_index_array = + code_index.map { |_code, style_array| style_array }.flatten + expected_code_index_array_size = + code_index_array.size - @added_codes_to_index HighLine::Style.clear_index cleared_code_index = HighLine::Style.code_index - cleared_code_index_array = cleared_code_index.map { |code, style_array| style_array }.flatten + cleared_code_index_array = + cleared_code_index.map { |_code, style_array| style_array }.flatten - assert_equal expected_code_index_array_size, cleared_code_index_array.size + assert_equal expected_code_index_array_size, cleared_code_index_array.size end def test_style_method @@ -55,10 +57,12 @@ class TestStyle < Minitest::Test new_style = @style1.dup # This will replace @style1 in the indexes s = HighLine.Style(@style1) assert_instance_of HighLine::Style, s - assert_same new_style, s # i.e. s===the latest style created, but not the one searched for + + # i.e. s===the latest style created, but not the one searched for + assert_same new_style, s # Retrieve a style from a new Style (no new Style created) - s2 = HighLine::Style.new(:name=>:bar, :code=>"\e[97m") + s2 = HighLine::Style.new(name: :bar, code: "\e[97m") s = HighLine.Style(s2) assert_instance_of HighLine::Style, s assert_same s2, s @@ -96,35 +100,35 @@ class TestStyle < Minitest::Test s = HighLine.Style(@style2.name) assert_instance_of HighLine::Style, s assert_same @style2, s - + # See below for color scheme tests - + # Create style from a Hash - s = HighLine.Style(:name=>:han, :code=>"blah", :rgb=>'phooey') + s = HighLine.Style(name: :han, code: "blah", rgb: "phooey") assert_instance_of HighLine::Style, s assert_equal :han, s.name assert_equal "blah", s.code assert_equal "phooey", s.rgb - + # Create style from an RGB foreground color code s = HighLine.Style(:rgb_1f2e3d) assert_instance_of HighLine::Style, s assert_equal :rgb_1f2e3d, s.name assert_equal "\e[38;5;23m", s.code # Trust me; more testing below - assert_equal [31,46,61], s.rgb # 0x1f==31, 0x2e==46, 0x3d=61 - + assert_equal [31, 46, 61], s.rgb # 0x1f==31, 0x2e==46, 0x3d=61 + # Create style from an RGB background color code s = HighLine.Style(:on_rgb_1f2e3d) assert_instance_of HighLine::Style, s assert_equal :on_rgb_1f2e3d, s.name assert_equal "\e[48;5;23m", s.code # Trust me; more testing below - assert_equal [31,46,61], s.rgb # 0x1f==31, 0x2e==46, 0x3d=61 + assert_equal [31, 46, 61], s.rgb # 0x1f==31, 0x2e==46, 0x3d=61 # Create a style list s1 = HighLine.Style(:bold, :red) assert_instance_of HighLine::Style, s1 assert_equal [:bold, :red], s1.list - + # Find an existing style list s2 = HighLine.Style(:bold, :red) assert_instance_of HighLine::Style, s2 @@ -134,16 +138,16 @@ class TestStyle < Minitest::Test s1 = HighLine.Style(:underline, nil, :blue) assert_instance_of HighLine::Style, s1 assert_equal [:underline, :blue], s1.list - + # Raise an error for an undefined style assert_raises(::NameError) { HighLine.Style(:fubar) } end - + def test_no_color_scheme HighLine.color_scheme = nil assert_raises(::NameError) { HighLine.Style(:critical) } end - + def test_with_color_scheme HighLine.color_scheme = HighLine::SampleColorScheme.new s = HighLine.Style(:critical) @@ -151,10 +155,10 @@ class TestStyle < Minitest::Test assert_equal :critical, s.name assert_equal [:yellow, :on_red], s.list end - + def test_builtin_foreground_colors_defined HighLine::COLORS.each do |color| - style = HighLine.const_get(color+'_STYLE') + style = HighLine.const_get(color + "_STYLE") assert_instance_of HighLine::Style, style assert_equal color.downcase.to_sym, style.name assert style.builtin @@ -162,21 +166,21 @@ class TestStyle < Minitest::Test assert_instance_of String, code, "Bad code for #{color}" end end - + def test_builtin_background_colors_defined HighLine::COLORS.each do |color| - style = HighLine.const_get('ON_' + color+'_STYLE') + style = HighLine.const_get("ON_" + color + "_STYLE") assert_instance_of HighLine::Style, style assert_equal "ON_#{color}".downcase.to_sym, style.name assert style.builtin - code = HighLine.const_get('ON_' + color) + code = HighLine.const_get("ON_" + color) assert_instance_of String, code, "Bad code for ON_#{color}" end end - + def test_builtin_styles_defined HighLine::STYLES.each do |style_constant| - style = HighLine.const_get(style_constant+'_STYLE') + style = HighLine.const_get(style_constant + "_STYLE") assert_instance_of HighLine::Style, style assert_equal style_constant.downcase.to_sym, style.name assert style.builtin @@ -184,98 +188,101 @@ class TestStyle < Minitest::Test assert_instance_of String, code, "Bad code for #{style_constant}" end end - + def test_index # Add a Style with a new name and code assert_nil HighLine::Style.list[:s1] - assert_nil HighLine::Style.code_index['foo'] - s1 = HighLine::Style.new(:name=>:s1, :code=>'foo') + assert_nil HighLine::Style.code_index["foo"] + s1 = HighLine::Style.new(name: :s1, code: "foo") refute_nil HighLine::Style.list[:s1] assert_same s1, HighLine::Style.list[:s1] assert_equal :s1, HighLine::Style.list[:s1].name - assert_equal 'foo', HighLine::Style.list[:s1].code + assert_equal "foo", HighLine::Style.list[:s1].code styles = HighLine::Style.list.size codes = HighLine::Style.code_index.size - assert_instance_of Array, HighLine::Style.code_index['foo'] - assert_equal 1, HighLine::Style.code_index['foo'].size - assert_same s1, HighLine::Style.code_index['foo'].last - assert_equal :s1, HighLine::Style.code_index['foo'].last.name - assert_equal 'foo', HighLine::Style.code_index['foo'].last.code + assert_instance_of Array, HighLine::Style.code_index["foo"] + assert_equal 1, HighLine::Style.code_index["foo"].size + assert_same s1, HighLine::Style.code_index["foo"].last + assert_equal :s1, HighLine::Style.code_index["foo"].last.name + assert_equal "foo", HighLine::Style.code_index["foo"].last.code # Add another Style with a new name and code assert_nil HighLine::Style.list[:s2] - assert_nil HighLine::Style.code_index['bar'] - s2 = HighLine::Style.new(:name=>:s2, :code=>'bar') - assert_equal styles+1, HighLine::Style.list.size - assert_equal codes+1, HighLine::Style.code_index.size + assert_nil HighLine::Style.code_index["bar"] + s2 = HighLine::Style.new(name: :s2, code: "bar") + assert_equal styles + 1, HighLine::Style.list.size + assert_equal codes + 1, HighLine::Style.code_index.size refute_nil HighLine::Style.list[:s2] assert_same s2, HighLine::Style.list[:s2] assert_equal :s2, HighLine::Style.list[:s2].name - assert_equal 'bar', HighLine::Style.list[:s2].code - assert_instance_of Array, HighLine::Style.code_index['bar'] - assert_equal 1, HighLine::Style.code_index['bar'].size - assert_same s2, HighLine::Style.code_index['bar'].last - assert_equal :s2, HighLine::Style.code_index['bar'].last.name - assert_equal 'bar', HighLine::Style.code_index['bar'].last.code - + assert_equal "bar", HighLine::Style.list[:s2].code + assert_instance_of Array, HighLine::Style.code_index["bar"] + assert_equal 1, HighLine::Style.code_index["bar"].size + assert_same s2, HighLine::Style.code_index["bar"].last + assert_equal :s2, HighLine::Style.code_index["bar"].last.name + assert_equal "bar", HighLine::Style.code_index["bar"].last.code + # Add a Style with an existing name s3_before = HighLine::Style.list[:s2] refute_nil HighLine::Style.list[:s2] - assert_nil HighLine::Style.code_index['baz'] - s3 = HighLine::Style.new(:name=>:s2, :code=>'baz') + assert_nil HighLine::Style.code_index["baz"] + s3 = HighLine::Style.new(name: :s2, code: "baz") refute_same s2, s3 refute_same s3_before, s3 - assert_equal styles+1, HighLine::Style.list.size - assert_equal codes+2, HighLine::Style.code_index.size + assert_equal styles + 1, HighLine::Style.list.size + assert_equal codes + 2, HighLine::Style.code_index.size refute_nil HighLine::Style.list[:s2] assert_same s3, HighLine::Style.list[:s2] refute_same s2, HighLine::Style.list[:s2] assert_equal :s2, HighLine::Style.list[:s2].name - assert_equal 'baz', HighLine::Style.list[:s2].code - assert_instance_of Array, HighLine::Style.code_index['baz'] - assert_equal 1, HighLine::Style.code_index['baz'].size - assert_same s3, HighLine::Style.code_index['baz'].last - assert_equal :s2, HighLine::Style.code_index['baz'].last.name - assert_equal 'baz', HighLine::Style.code_index['baz'].last.code + assert_equal "baz", HighLine::Style.list[:s2].code + assert_instance_of Array, HighLine::Style.code_index["baz"] + assert_equal 1, HighLine::Style.code_index["baz"].size + assert_same s3, HighLine::Style.code_index["baz"].last + assert_equal :s2, HighLine::Style.code_index["baz"].last.name + assert_equal "baz", HighLine::Style.code_index["baz"].last.code # Add a Style with an existing code - assert_equal 1, HighLine::Style.code_index['baz'].size - s4 = HighLine::Style.new(:name=>:s4, :code=>'baz') - assert_equal styles+2, HighLine::Style.list.size - assert_equal codes+2, HighLine::Style.code_index.size + assert_equal 1, HighLine::Style.code_index["baz"].size + s4 = HighLine::Style.new(name: :s4, code: "baz") + assert_equal styles + 2, HighLine::Style.list.size + assert_equal codes + 2, HighLine::Style.code_index.size refute_nil HighLine::Style.list[:s4] assert_same s4, HighLine::Style.list[:s4] assert_equal :s4, HighLine::Style.list[:s4].name - assert_equal 'baz', HighLine::Style.list[:s4].code - assert_equal 2, HighLine::Style.code_index['baz'].size - assert_same s3, HighLine::Style.code_index['baz'].first # Unchanged from last time - assert_equal :s2, HighLine::Style.code_index['baz'].first.name # Unchanged from last time - assert_equal 'baz', HighLine::Style.code_index['baz'].first.code # Unchanged from last time - assert_same s4, HighLine::Style.code_index['baz'].last - assert_equal :s4, HighLine::Style.code_index['baz'].last.name - assert_equal 'baz', HighLine::Style.code_index['baz'].last.code + assert_equal "baz", HighLine::Style.list[:s4].code + assert_equal 2, HighLine::Style.code_index["baz"].size + + # Unchanged from last time + assert_same s3, HighLine::Style.code_index["baz"].first + assert_equal :s2, HighLine::Style.code_index["baz"].first.name + assert_equal "baz", HighLine::Style.code_index["baz"].first.code + + assert_same s4, HighLine::Style.code_index["baz"].last + assert_equal :s4, HighLine::Style.code_index["baz"].last.name + assert_equal "baz", HighLine::Style.code_index["baz"].last.code end - + def test_rgb_hex assert_equal "abcdef", HighLine::Style.rgb_hex("abcdef") - assert_equal "ABCDEF", HighLine::Style.rgb_hex("AB","CD","EF") - assert_equal "010203", HighLine::Style.rgb_hex(1,2,3) - assert_equal "123456", HighLine::Style.rgb_hex(18,52,86) + assert_equal "ABCDEF", HighLine::Style.rgb_hex("AB", "CD", "EF") + assert_equal "010203", HighLine::Style.rgb_hex(1, 2, 3) + assert_equal "123456", HighLine::Style.rgb_hex(18, 52, 86) end - + def test_rgb_parts - assert_equal [1,2,3], HighLine::Style.rgb_parts("010203") - assert_equal [18,52,86], HighLine::Style.rgb_parts("123456") + assert_equal [1, 2, 3], HighLine::Style.rgb_parts("010203") + assert_equal [18, 52, 86], HighLine::Style.rgb_parts("123456") end - + def test_rgb s = HighLine::Style.rgb(1, 2, 3) assert_instance_of HighLine::Style, s assert_equal :rgb_010203, s.name - assert_equal [1,2,3], s.rgb + assert_equal [1, 2, 3], s.rgb assert_equal "\e[38;5;16m", s.code - s = HighLine::Style.rgb("12", "34","56") + s = HighLine::Style.rgb("12", "34", "56") assert_instance_of HighLine::Style, s assert_equal :rgb_123456, s.name assert_equal [0x12, 0x34, 0x56], s.rgb @@ -287,194 +294,204 @@ class TestStyle < Minitest::Test assert_equal [0xab, 0xcd, 0xef], s.rgb assert_equal "\e[38;5;189m", s.code end - + def test_rgb_number - # ANSI RGB coding splits 0..255 into equal sixths, and then the + # ANSI RGB coding splits 0..255 into equal sixths, and then the # red green and blue are encoded in base 6, plus 16, i.e. # 16 + 36*(red_level) + 6*(green_level) + blue_level, # where each of red_level, green_level, and blue_level are in # the range 0..5 - + # This test logic works because 42 is just below 1/6 of 255, # and 43 is just above - - assert_equal 16 + 0*36 + 0*6 + 0, HighLine::Style.rgb_number( 0, 0, 0) - assert_equal 16 + 0*36 + 0*6 + 0, HighLine::Style.rgb_number( 0, 0, 42) - assert_equal 16 + 0*36 + 0*6 + 1, HighLine::Style.rgb_number( 0, 0, 43) - - assert_equal 16 + 0*36 + 0*6 + 0, HighLine::Style.rgb_number( 0, 42, 0) - assert_equal 16 + 0*36 + 0*6 + 0, HighLine::Style.rgb_number( 0, 42, 42) - assert_equal 16 + 0*36 + 0*6 + 1, HighLine::Style.rgb_number( 0, 42, 43) - - assert_equal 16 + 0*36 + 1*6 + 0, HighLine::Style.rgb_number( 0, 43, 0) - assert_equal 16 + 0*36 + 1*6 + 0, HighLine::Style.rgb_number( 0, 43, 42) - assert_equal 16 + 0*36 + 1*6 + 1, HighLine::Style.rgb_number( 0, 43, 43) - - assert_equal 16 + 0*36 + 0*6 + 0, HighLine::Style.rgb_number( 42, 0, 0) - assert_equal 16 + 0*36 + 0*6 + 0, HighLine::Style.rgb_number( 42, 0, 42) - assert_equal 16 + 0*36 + 0*6 + 1, HighLine::Style.rgb_number( 42, 0, 43) - - assert_equal 16 + 0*36 + 0*6 + 0, HighLine::Style.rgb_number( 42, 42, 0) - assert_equal 16 + 0*36 + 0*6 + 0, HighLine::Style.rgb_number( 42, 42, 42) - assert_equal 16 + 0*36 + 0*6 + 1, HighLine::Style.rgb_number( 42, 42, 43) - - assert_equal 16 + 0*36 + 1*6 + 0, HighLine::Style.rgb_number( 42, 43, 0) - assert_equal 16 + 0*36 + 1*6 + 0, HighLine::Style.rgb_number( 42, 43, 42) - assert_equal 16 + 0*36 + 1*6 + 1, HighLine::Style.rgb_number( 42, 43, 43) - - assert_equal 16 + 1*36 + 0*6 + 0, HighLine::Style.rgb_number( 43, 0, 0) - assert_equal 16 + 1*36 + 0*6 + 0, HighLine::Style.rgb_number( 43, 0, 42) - assert_equal 16 + 1*36 + 0*6 + 1, HighLine::Style.rgb_number( 43, 0, 43) - - assert_equal 16 + 1*36 + 0*6 + 0, HighLine::Style.rgb_number( 43, 42, 0) - assert_equal 16 + 1*36 + 0*6 + 0, HighLine::Style.rgb_number( 43, 42, 42) - assert_equal 16 + 1*36 + 0*6 + 1, HighLine::Style.rgb_number( 43, 42, 43) - - assert_equal 16 + 1*36 + 1*6 + 0, HighLine::Style.rgb_number( 43, 43, 0) - assert_equal 16 + 1*36 + 1*6 + 0, HighLine::Style.rgb_number( 43, 43, 42) - assert_equal 16 + 1*36 + 1*6 + 1, HighLine::Style.rgb_number( 43, 43, 43) - - assert_equal 16 + 5*36 + 5*6 + 5, HighLine::Style.rgb_number(255,255,255) + + assert_equal 16 + 0 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(0, 0, 0) + assert_equal 16 + 0 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(0, 0, 42) + assert_equal 16 + 0 * 36 + 0 * 6 + 1, HighLine::Style.rgb_number(0, 0, 43) + + assert_equal 16 + 0 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(0, 42, 0) + assert_equal 16 + 0 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(0, 42, 42) + assert_equal 16 + 0 * 36 + 0 * 6 + 1, HighLine::Style.rgb_number(0, 42, 43) + + assert_equal 16 + 0 * 36 + 1 * 6 + 0, HighLine::Style.rgb_number(0, 43, 0) + assert_equal 16 + 0 * 36 + 1 * 6 + 0, HighLine::Style.rgb_number(0, 43, 42) + assert_equal 16 + 0 * 36 + 1 * 6 + 1, HighLine::Style.rgb_number(0, 43, 43) + + assert_equal 16 + 0 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(42, 0, 0) + assert_equal 16 + 0 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(42, 0, 42) + assert_equal 16 + 0 * 36 + 0 * 6 + 1, HighLine::Style.rgb_number(42, 0, 43) + + assert_equal 16 + 0 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(42, 42, 0) + assert_equal 16 + 0 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(42, 42, 42) + assert_equal 16 + 0 * 36 + 0 * 6 + 1, HighLine::Style.rgb_number(42, 42, 43) + + assert_equal 16 + 0 * 36 + 1 * 6 + 0, HighLine::Style.rgb_number(42, 43, 0) + assert_equal 16 + 0 * 36 + 1 * 6 + 0, HighLine::Style.rgb_number(42, 43, 42) + assert_equal 16 + 0 * 36 + 1 * 6 + 1, HighLine::Style.rgb_number(42, 43, 43) + + assert_equal 16 + 1 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(43, 0, 0) + assert_equal 16 + 1 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(43, 0, 42) + assert_equal 16 + 1 * 36 + 0 * 6 + 1, HighLine::Style.rgb_number(43, 0, 43) + + assert_equal 16 + 1 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(43, 42, 0) + assert_equal 16 + 1 * 36 + 0 * 6 + 0, HighLine::Style.rgb_number(43, 42, 42) + assert_equal 16 + 1 * 36 + 0 * 6 + 1, HighLine::Style.rgb_number(43, 42, 43) + + assert_equal 16 + 1 * 36 + 1 * 6 + 0, HighLine::Style.rgb_number(43, 43, 0) + assert_equal 16 + 1 * 36 + 1 * 6 + 0, HighLine::Style.rgb_number(43, 43, 42) + assert_equal 16 + 1 * 36 + 1 * 6 + 1, HighLine::Style.rgb_number(43, 43, 43) + + assert_equal 16 + 5 * 36 + 5 * 6 + 5, + HighLine::Style.rgb_number(255, 255, 255) end - + def test_ansi_rgb_to_hex - assert_equal "000000", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 0) - assert_equal "000000", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 0) - assert_equal "00002b", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 1) - - assert_equal "000000", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 0) - assert_equal "000000", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 0) - assert_equal "00002b", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 1) - - assert_equal "002b00", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 1*6 + 0) - assert_equal "002b00", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 1*6 + 0) - assert_equal "002b2b", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 1*6 + 1) - - assert_equal "000000", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 0) - assert_equal "000000", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 0) - assert_equal "00002b", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 1) - - assert_equal "000000", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 0) - assert_equal "000000", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 0) - assert_equal "00002b", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 0*6 + 1) - - assert_equal "002b00", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 1*6 + 0) - assert_equal "002b00", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 1*6 + 0) - assert_equal "002b2b", HighLine::Style.ansi_rgb_to_hex(16 + 0*36 + 1*6 + 1) - - assert_equal "2b0000", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 0*6 + 0) - assert_equal "2b0000", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 0*6 + 0) - assert_equal "2b002b", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 0*6 + 1) - - assert_equal "2b0000", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 0*6 + 0) - assert_equal "2b0000", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 0*6 + 0) - assert_equal "2b002b", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 0*6 + 1) - - assert_equal "2b2b00", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 1*6 + 0) - assert_equal "2b2b00", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 1*6 + 0) - assert_equal "2b2b2b", HighLine::Style.ansi_rgb_to_hex(16 + 1*36 + 1*6 + 1) - + ansi_rgb_to_hex = ->(rgb) { HighLine::Style.ansi_rgb_to_hex(rgb) } + + assert_equal "000000", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 0) + assert_equal "000000", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 0) + assert_equal "00002b", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 1) + + assert_equal "000000", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 0) + assert_equal "000000", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 0) + assert_equal "00002b", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 1) + + assert_equal "002b00", ansi_rgb_to_hex.call(16 + 0 * 36 + 1 * 6 + 0) + assert_equal "002b00", ansi_rgb_to_hex.call(16 + 0 * 36 + 1 * 6 + 0) + assert_equal "002b2b", ansi_rgb_to_hex.call(16 + 0 * 36 + 1 * 6 + 1) + + assert_equal "000000", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 0) + assert_equal "000000", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 0) + assert_equal "00002b", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 1) + + assert_equal "000000", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 0) + assert_equal "000000", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 0) + assert_equal "00002b", ansi_rgb_to_hex.call(16 + 0 * 36 + 0 * 6 + 1) + + assert_equal "002b00", ansi_rgb_to_hex.call(16 + 0 * 36 + 1 * 6 + 0) + assert_equal "002b00", ansi_rgb_to_hex.call(16 + 0 * 36 + 1 * 6 + 0) + assert_equal "002b2b", ansi_rgb_to_hex.call(16 + 0 * 36 + 1 * 6 + 1) + + assert_equal "2b0000", ansi_rgb_to_hex.call(16 + 1 * 36 + 0 * 6 + 0) + assert_equal "2b0000", ansi_rgb_to_hex.call(16 + 1 * 36 + 0 * 6 + 0) + assert_equal "2b002b", ansi_rgb_to_hex.call(16 + 1 * 36 + 0 * 6 + 1) + + assert_equal "2b0000", ansi_rgb_to_hex.call(16 + 1 * 36 + 0 * 6 + 0) + assert_equal "2b0000", ansi_rgb_to_hex.call(16 + 1 * 36 + 0 * 6 + 0) + assert_equal "2b002b", ansi_rgb_to_hex.call(16 + 1 * 36 + 0 * 6 + 1) + + assert_equal "2b2b00", ansi_rgb_to_hex.call(16 + 1 * 36 + 1 * 6 + 0) + assert_equal "2b2b00", ansi_rgb_to_hex.call(16 + 1 * 36 + 1 * 6 + 0) + assert_equal "2b2b2b", ansi_rgb_to_hex.call(16 + 1 * 36 + 1 * 6 + 1) + # 0xd5 is the smallest number where n/255.0*6.0 > 5 - assert_equal "d5d5d5", HighLine::Style.ansi_rgb_to_hex(16 + 5*36 + 5*6 + 5) + assert_equal "d5d5d5", ansi_rgb_to_hex.call(16 + 5 * 36 + 5 * 6 + 5) end - + def test_list list_size = HighLine::Style.list.size # Add a Style with a new name and code assert_nil HighLine::Style.list[:s5] - s5 = HighLine::Style.new(:name=>:s5, :code=>'foo') + s5 = HighLine::Style.new(name: :s5, code: "foo") refute_nil HighLine::Style.list[:s5] - assert_equal list_size+1, HighLine::Style.list.size + assert_equal list_size + 1, HighLine::Style.list.size refute_nil HighLine::Style.list[:s5] assert_same s5, HighLine::Style.list[:s5] assert_equal :s5, HighLine::Style.list[:s5].name - assert_equal 'foo', HighLine::Style.list[:s5].code + assert_equal "foo", HighLine::Style.list[:s5].code # Add another Style with a new name and code assert_nil HighLine::Style.list[:s6] - s6 = HighLine::Style.new(:name=>:s6, :code=>'bar') - assert_equal list_size+2, HighLine::Style.list.size + s6 = HighLine::Style.new(name: :s6, code: "bar") + assert_equal list_size + 2, HighLine::Style.list.size refute_nil HighLine::Style.list[:s6] assert_same s6, HighLine::Style.list[:s6] assert_equal :s6, HighLine::Style.list[:s6].name - assert_equal 'bar', HighLine::Style.list[:s6].code - + assert_equal "bar", HighLine::Style.list[:s6].code + # Add a Style with an existing name - s7 = HighLine::Style.new(:name=>:s6, :code=>'baz') - assert_equal list_size+2, HighLine::Style.list.size # No net addition to list + s7 = HighLine::Style.new(name: :s6, code: "baz") + # No net addition to list + assert_equal list_size + 2, HighLine::Style.list.size refute_nil HighLine::Style.list[:s6] assert_same s7, HighLine::Style.list[:s6] # New one replaces old one refute_same s6, HighLine::Style.list[:s6] assert_equal :s6, HighLine::Style.list[:s6].name - assert_equal 'baz', HighLine::Style.list[:s6].code + assert_equal "baz", HighLine::Style.list[:s6].code end - + def test_code_index list_size = HighLine::Style.code_index.size - + # Add a Style with a new name and code - assert_nil HighLine::Style.code_index['chewie'] - HighLine::Style.new(:name=>:s8, :code=>'chewie') - assert_equal list_size+1, HighLine::Style.code_index.size - assert_instance_of Array, HighLine::Style.code_index['chewie'] - assert_equal 1, HighLine::Style.code_index['chewie'].size - assert_equal :s8, HighLine::Style.code_index['chewie'].last.name - assert_equal 'chewie', HighLine::Style.code_index['chewie'].last.code + assert_nil HighLine::Style.code_index["chewie"] + HighLine::Style.new(name: :s8, code: "chewie") + assert_equal list_size + 1, HighLine::Style.code_index.size + assert_instance_of Array, HighLine::Style.code_index["chewie"] + assert_equal 1, HighLine::Style.code_index["chewie"].size + assert_equal :s8, HighLine::Style.code_index["chewie"].last.name + assert_equal "chewie", HighLine::Style.code_index["chewie"].last.code # Add another Style with a new name and code - assert_nil HighLine::Style.code_index['c3po'] - HighLine::Style.new(:name=>:s9, :code=>'c3po') - assert_equal list_size+2, HighLine::Style.code_index.size - assert_instance_of Array, HighLine::Style.code_index['c3po'] - assert_equal 1, HighLine::Style.code_index['c3po'].size - assert_equal :s9, HighLine::Style.code_index['c3po'].last.name - assert_equal 'c3po', HighLine::Style.code_index['c3po'].last.code + assert_nil HighLine::Style.code_index["c3po"] + HighLine::Style.new(name: :s9, code: "c3po") + assert_equal list_size + 2, HighLine::Style.code_index.size + assert_instance_of Array, HighLine::Style.code_index["c3po"] + assert_equal 1, HighLine::Style.code_index["c3po"].size + assert_equal :s9, HighLine::Style.code_index["c3po"].last.name + assert_equal "c3po", HighLine::Style.code_index["c3po"].last.code # Add a Style with an existing code - assert_equal 1, HighLine::Style.code_index['c3po'].size - HighLine::Style.new(:name=>:s10, :code=>'c3po') - assert_equal list_size+2, HighLine::Style.code_index.size - assert_equal 2, HighLine::Style.code_index['c3po'].size - assert_equal :s10, HighLine::Style.code_index['c3po'].last.name - assert_equal 'c3po', HighLine::Style.code_index['c3po'].last.code + assert_equal 1, HighLine::Style.code_index["c3po"].size + HighLine::Style.new(name: :s10, code: "c3po") + assert_equal list_size + 2, HighLine::Style.code_index.size + assert_equal 2, HighLine::Style.code_index["c3po"].size + assert_equal :s10, HighLine::Style.code_index["c3po"].last.name + assert_equal "c3po", HighLine::Style.code_index["c3po"].last.code end - + def test_uncolor # Normal color - assert_equal "This should be reverse underlined magenta!\n", - HighLine::Style.uncolor("This should be \e[7m\e[4m\e[35mreverse underlined magenta\e[0m!\n" ) + assert_equal( + "This should be reverse underlined magenta!\n", + HighLine::Style.uncolor( + "This should be \e[7m\e[4m\e[35mreverse underlined magenta\e[0m!\n" + ) + ) # RGB color - assert_equal "This should be rgb_906030!\n", - HighLine::Style.uncolor("This should be \e[38;5;137mrgb_906030\e[0m!\n" ) + assert_equal( + "This should be rgb_906030!\n", + HighLine::Style.uncolor("This should be \e[38;5;137mrgb_906030\e[0m!\n") + ) end - + def test_color assert_equal "\e[99mstring\e[0m", @style1.color("string") # simple style assert_equal "\e[99m\e[98mstring\e[0m", @style3.color("string") # Style list end - + def test_code assert_equal "\e[99m", @style1.code # simple style assert_equal "\e[99m\e[98m", @style3.code # Style list end - + def test_red assert_equal 0x65, @style4.red assert_equal 0, HighLine::Style(:none).red # Probably reliable assert_equal 0, HighLine::Style(:black).red # Probably reliable - assert_equal 255, HighLine::Style(:bright_magenta).red # Seems to be reliable + assert_equal 255, HighLine::Style(:bright_magenta).red # Seems reliable assert_equal 255, HighLine::Style(:on_none).red # Probably reliable end - + def test_green assert_equal 0x43, @style4.green assert_equal 0, HighLine::Style(:none).green # Probably reliable assert_equal 0, HighLine::Style(:black).green # Probably reliable - assert 240 <= HighLine::Style(:bright_cyan).green # Probably reliable + assert HighLine::Style(:bright_cyan).green >= 240 # Probably reliable assert_equal 255, HighLine::Style(:on_none).green # Probably reliable end - + def test_blue assert_equal 0x21, @style4.blue assert_equal 0, HighLine::Style(:none).blue # Probably reliable @@ -482,122 +499,125 @@ class TestStyle < Minitest::Test assert_equal 255, HighLine::Style(:bright_blue).blue # Probably reliable assert_equal 255, HighLine::Style(:on_none).blue # Probably reliable end - + def test_builtin assert HighLine::Style(:red).builtin assert !@style1.builtin end - + def test_variant style1_name = @style1.name style1_code = @style1.code style1_rgb = @style1.rgb - - s1 = @style1.variant(:new_foo1, :code=>'abracadabra') + + s1 = @style1.variant(:new_foo1, code: "abracadabra") assert_instance_of HighLine::Style, s1 refute_same @style1, s1 # This is a copy assert_equal :new_foo1, s1.name # Changed - assert_equal 'abracadabra', s1.code # Changed - assert_equal [1,2,3], s1.rgb # Unchanged - - s2 = @style1.variant(:new_foo2, :increment=>-15) + assert_equal "abracadabra", s1.code # Changed + assert_equal [1, 2, 3], s1.rgb # Unchanged + + s2 = @style1.variant(:new_foo2, increment: -15) assert_instance_of HighLine::Style, s2 - refute_same @style1, s2 # This is a copy + refute_same @style1, s2 # This is a copy assert_equal :new_foo2, s2.name # Changed assert_equal "\e[84m", s2.code # 99 (original code) - 15 - assert_equal [1,2,3], s2.rgb # Unchanged - - s3 = @style1.variant(:new_foo3, :code=>"\e[55m", :increment=>15) + assert_equal [1, 2, 3], s2.rgb # Unchanged + + s3 = @style1.variant(:new_foo3, code: "\e[55m", increment: 15) assert_instance_of HighLine::Style, s3 - refute_same @style1, s3 # This is a copy + refute_same @style1, s3 # This is a copy assert_equal :new_foo3, s3.name # Changed assert_equal "\e[70m", s3.code # 99 (new code) + 15 - assert_equal [1,2,3], s3.rgb # Unchanged - - s4 = @style1.variant(:new_foo4, :code=>"\e[55m", :increment=>15, :rgb=>"blah") + assert_equal [1, 2, 3], s3.rgb # Unchanged + + s4 = @style1.variant(:new_foo4, code: "\e[55m", increment: 15, rgb: "blah") assert_instance_of HighLine::Style, s4 - refute_same @style1, s4 # This is a copy + refute_same @style1, s4 # This is a copy assert_equal :new_foo4, s4.name # Changed assert_equal "\e[70m", s4.code # 99 (new code) + 15 - assert_equal 'blah', s4.rgb # Changed + assert_equal "blah", s4.rgb # Changed s5 = @style1.variant(:new_foo5) assert_instance_of HighLine::Style, s5 - refute_same @style1, s5 # This is a copy + refute_same @style1, s5 # This is a copy assert_equal :new_foo5, s5.name # Changed assert_equal "\e[99m", s5.code # Unchanged - assert_equal [1,2,3], s5.rgb # Unchanged + assert_equal [1, 2, 3], s5.rgb # Unchanged # No @style1's have been harmed in the running of this test assert_equal style1_name, @style1.name assert_equal style1_code, @style1.code assert_equal style1_rgb, @style1.rgb - - assert_raises(::RuntimeError) { @style3.variant(:new_foo6) } # Can't create a variant of a list style + + # Can't create a variant of a list style + assert_raises(::RuntimeError) { @style3.variant(:new_foo6) } end - + def test_on style1_name = @style1.name style1_code = @style1.code style1_rgb = @style1.rgb - + s1 = @style1.on assert_instance_of HighLine::Style, s1 - refute_same @style1, s1 # This is a copy + refute_same @style1, s1 # This is a copy assert_equal :on_foo, s1.name # Changed assert_equal "\e[109m", s1.code # Changed - assert_equal [1,2,3], s1.rgb # Unchanged + assert_equal [1, 2, 3], s1.rgb # Unchanged # No @style1's have been harmed in the running of this test assert_equal style1_name, @style1.name assert_equal style1_code, @style1.code assert_equal style1_rgb, @style1.rgb - - assert_raises(::RuntimeError) { @style3.on } # Can't create a variant of a list style + + # Can't create a variant of a list style + assert_raises(::RuntimeError) { @style3.on } end - + def test_bright style1_name = @style1.name style1_code = @style1.code style1_rgb = @style1.rgb - + s1 = @style1.bright assert_instance_of HighLine::Style, s1 - refute_same @style1, s1 # This is a copy + refute_same @style1, s1 # This is a copy assert_equal :bright_foo, s1.name # Changed assert_equal "\e[159m", s1.code # Changed - assert_equal [129,130,131], s1.rgb # Changed + assert_equal [129, 130, 131], s1.rgb # Changed # No @style1's have been harmed in the running of this test assert_equal style1_name, @style1.name assert_equal style1_code, @style1.code assert_equal style1_rgb, @style1.rgb - - s2_base = HighLine::Style.new(:name=>:leia, :code=>"\e[92m", :rgb=>[0,0,14]) + + s2_base = HighLine::Style.new(name: :leia, code: "\e[92m", rgb: [0, 0, 14]) s2 = s2_base.bright assert_instance_of HighLine::Style, s2 - refute_same s2_base, s2 # This is a copy + refute_same s2_base, s2 # This is a copy assert_equal :bright_leia, s2.name # Changed assert_equal "\e[152m", s2.code # Changed - assert_equal [0,0,142], s2.rgb # Changed - - s3_base = HighLine::Style.new(:name=>:luke, :code=>"\e[93m", :rgb=>[20,21,0]) + assert_equal [0, 0, 142], s2.rgb # Changed + + s3_base = HighLine::Style.new(name: :luke, code: "\e[93m", rgb: [20, 21, 0]) s3 = s3_base.bright assert_instance_of HighLine::Style, s3 - refute_same s3_base, s3 # This is a copy + refute_same s3_base, s3 # This is a copy assert_equal :bright_luke, s3.name # Changed assert_equal "\e[153m", s3.code # Changed - assert_equal [148,149,0], s3.rgb # Changed - - s4_base = HighLine::Style.new(:name=>:r2d2, :code=>"\e[94m", :rgb=>[0,0,0]) + assert_equal [148, 149, 0], s3.rgb # Changed + + s4_base = HighLine::Style.new(name: :r2d2, code: "\e[94m", rgb: [0, 0, 0]) s4 = s4_base.bright assert_instance_of HighLine::Style, s4 - refute_same s4_base, s4 # This is a copy + refute_same s4_base, s4 # This is a copy assert_equal :bright_r2d2, s4.name # Changed assert_equal "\e[154m", s4.code # Changed - assert_equal [128,128,128], s4.rgb # Changed; special case - - assert_raises(::RuntimeError) { @style3.bright } # Can't create a variant of a list style + assert_equal [128, 128, 128], s4.rgb # Changed; special case + + # Can't create a variant of a list style + assert_raises(::RuntimeError) { @style3.bright } end def test_light_do_the_same_as_bright diff --git a/test/test_wrapper.rb b/test/test_wrapper.rb index f7e4871..4f3a4a9 100644 --- a/test/test_wrapper.rb +++ b/test/test_wrapper.rb @@ -21,18 +21,16 @@ class TestHighLineWrapper < Minitest::Test def test_wrap_long_lines_correctly long_line = - "This is a long flowing paragraph meant to span " + - "several lines. This text should definitely be " + - "wrapped at the set limit, in the result. Your code " + + "This is a long flowing paragraph meant to span " \ + "several lines. This text should definitely be " \ + "wrapped at the set limit, in the result. Your code " \ "does well with things like this.\n\n" wrapped_long_line = - "This is a long flowing paragraph meant to span " + - "several lines. This text should\n" + - - "definitely be wrapped at the set limit, in the " + - "result. Your code does well with\n" + - + "This is a long flowing paragraph meant to span " \ + "several lines. This text should\n" \ + "definitely be wrapped at the set limit, in the " \ + "result. Your code does well with\n" \ "things like this.\n\n" wrapped = wrap(long_line) @@ -41,13 +39,13 @@ class TestHighLineWrapper < Minitest::Test def test_dont_wrap_already_well_wrapped_text well_formatted_text = - " * This is a simple embedded list.\n" + - " * You're code should not mess with this...\n" + - " * Because it's already formatted correctly and does not\n" + + " * This is a simple embedded list.\n" \ + " * You're code should not mess with this...\n" \ + " * Because it's already formatted correctly and does not\n" \ " exceed the limit!\n" wrapped = wrap(well_formatted_text) - assert_equal well_formatted_text, wrapped + assert_equal well_formatted_text, wrapped end def test_wrap_single_word_longer_than_wrap_at @@ -185,4 +183,4 @@ class TestHighLineWrapper < Minitest::Test end end end -end
\ No newline at end of file +end |