diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000000..2f7a23b713 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,20 @@ +Metrics/LineLength: + Enabled: false +Metrics/MethodLength: + Enabled: false +Metrics/ClassLength: + Enabled: false +Metrics/BlockLength: + Enabled: false +Metrics/AbcSize: + Enabled: false +Metrics/PerceivedComplexity: + Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false +Style/Documentation: + Enabled: false +Style/DateTime: + Enabled: false +Lint/UnifiedInteger: + Enabled: false diff --git a/Gemfile b/Gemfile index 2133c99bea..d85a14c69c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,11 +1,4 @@ -source "https://rubygems.org" +source 'https://rubygems.org' # Specify your gem's dependencies in faker.gemspec gemspec - -group :development, :test do - gem "test-unit" - gem "rake" - gem "minitest" - gem "timecop" -end diff --git a/Gemfile.lock b/Gemfile.lock index e300ecf23b..9f57a1abf4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -7,15 +7,30 @@ PATH GEM remote: https://rubygems.org/ specs: + ast (2.4.0) concurrent-ruby (1.0.5) i18n (0.9.1) concurrent-ruby (~> 1.0) minitest (5.10.3) + parallel (1.12.1) + parser (2.5.1.0) + ast (~> 2.4.0) power_assert (1.1.1) + powerpack (0.1.1) + rainbow (3.0.0) rake (12.3.0) + rubocop (0.55.0) + parallel (~> 1.10) + parser (>= 2.5) + powerpack (~> 0.1) + rainbow (>= 2.2.2, < 4.0) + ruby-progressbar (~> 1.7) + unicode-display_width (~> 1.0, >= 1.0.1) + ruby-progressbar (1.9.0) test-unit (3.2.6) power_assert timecop (0.9.1) + unicode-display_width (1.3.2) PLATFORMS ruby @@ -24,8 +39,9 @@ DEPENDENCIES faker! minitest rake + rubocop test-unit timecop BUNDLED WITH - 1.16.0 + 1.16.1.pre1 diff --git a/Rakefile b/Rakefile index a296670b72..7a5ce39912 100644 --- a/Rakefile +++ b/Rakefile @@ -1,4 +1,4 @@ -$:.unshift File.dirname(__FILE__) +$LOAD_PATH.unshift File.dirname(__FILE__) Dir['tasks/**/*.rake'].each { |rake| load rake } @@ -13,4 +13,7 @@ task :console do IRB.start end -task default: %w[test] +require 'rubocop/rake_task' +RuboCop::RakeTask.new + +task default: %w[test rubocop] diff --git a/faker.gemspec b/faker.gemspec index 1211bc9863..0ae1b657c8 100644 --- a/faker.gemspec +++ b/faker.gemspec @@ -1,20 +1,25 @@ -$:.push File.expand_path("../lib", __FILE__) -require "faker/version" +$LOAD_PATH.push File.expand_path('lib', __dir__) +require 'faker/version' Gem::Specification.new do |s| - s.name = "faker" + s.name = 'faker' s.version = Faker::VERSION s.platform = Gem::Platform::RUBY - s.authors = ["Benjamin Curtis"] - s.email = ["benjamin.curtis@gmail.com"] - s.homepage = "https://github.com/stympy/faker" - s.summary = %q{Easily generate fake data} - s.description = %q{Faker, a port of Data::Faker from Perl, is used to easily generate fake data: names, addresses, phone numbers, etc.} + s.authors = ['Benjamin Curtis'] + s.email = ['benjamin.curtis@gmail.com'] + s.homepage = 'https://github.com/stympy/faker' + s.summary = 'Easily generate fake data' + s.description = 'Faker, a port of Data::Faker from Perl, is used to easily generate fake data: names, addresses, phone numbers, etc.' s.license = 'MIT' s.add_runtime_dependency('i18n', '>= 0.7') + s.add_development_dependency('minitest') + s.add_development_dependency('rake') + s.add_development_dependency('rubocop') + s.add_development_dependency('test-unit') + s.add_development_dependency('timecop') s.required_ruby_version = '>= 2.1' - s.files = Dir['lib/**/*'] + %w(History.md License.txt CHANGELOG.md README.md) - s.require_paths = ["lib"] + s.files = Dir['lib/**/*'] + %w[History.md License.txt CHANGELOG.md README.md] + s.require_paths = ['lib'] end diff --git a/lib/extensions/array.rb b/lib/extensions/array.rb index c8cf8a8a33..7024d26e08 100644 --- a/lib/extensions/array.rb +++ b/lib/extensions/array.rb @@ -1,21 +1,21 @@ class Array - unless self.method_defined? :sample - def sample(n = nil) - #based on code from https://github.com/marcandre/backports - size = self.length - return self[Kernel.rand(size)] if n.nil? + unless method_defined? :sample + def sample(arr = nil) + # based on code from https://github.com/marcandre/backports + size = length + return self[Kernel.rand(size)] if arr.nil? - n = n.to_int - raise ArgumentError, "negative array size" if n < 0 + arr = arr.to_int + raise ArgumentError, 'negative array size' if arr < 0 - n = size if n > size + arr = size if arr > size result = Array.new(self) - n.times do |i| + arr.times do |i| r = i + Kernel.rand(size - i) result[i], result[r] = result[r], result[i] end - result[n..size] = [] + result[arr..size] = [] result end end diff --git a/lib/extensions/symbol.rb b/lib/extensions/symbol.rb index 90fa0d68d8..d302ee63ab 100644 --- a/lib/extensions/symbol.rb +++ b/lib/extensions/symbol.rb @@ -6,4 +6,3 @@ def downcase end end end - diff --git a/lib/faker.rb b/lib/faker.rb index f6d8645c9b..d311b458af 100644 --- a/lib/faker.rb +++ b/lib/faker.rb @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- -mydir = File.expand_path(File.dirname(__FILE__)) +mydir = __dir__ begin require 'psych' -rescue LoadError end require 'i18n' @@ -15,7 +13,6 @@ I18n.load_path += Dir[File.join(mydir, 'locales', '**/*.yml')] I18n.reload! if I18n.backend.initialized? - module Faker class Config @locale = nil @@ -45,9 +42,9 @@ class Base Letters = ULetters + Array('a'..'z') class << self - ## make sure numerify results doesn’t start with a zero + ## make sure numerify results do not start with a zero def numerify(number_string) - number_string.sub(/#/) { (rand(9)+1).to_s }.gsub(/#/) { rand(10).to_s } + number_string.sub(/#/) { rand(1..9).to_s }.gsub(/#/) { rand(10).to_s } end def letterify(letter_string) @@ -77,26 +74,26 @@ def bothify(string) # # "U3V 3TP" # - def regexify(re) - re = re.source if re.respond_to?(:source) # Handle either a Regexp or a String that looks like a Regexp - re. - gsub(/^\/?\^?/, '').gsub(/\$?\/?$/, ''). # Ditch the anchors - gsub(/\{(\d+)\}/, '{\1,\1}').gsub(/\?/, '{0,1}'). # All {2} become {2,2} and ? become {0,1} - gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # [12]{1,2} becomes [12] or [12][12] - gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # (12|34){1,2} becomes (12|34) or (12|34)(12|34) - gsub(/(\\?.)\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # A{1,2} becomes A or AA or \d{3} becomes \d\d\d - gsub(/\((.*?)\)/) {|match| sample(match.gsub(/[\(\)]/, '').split('|')) }. # (this|that) becomes 'this' or 'that' - gsub(/\[([^\]]+)\]/) {|match| match.gsub(/(\w\-\w)/) {|range| sample(Array(Range.new(*range.split('-')))) } }. # All A-Z inside of [] become C (or X, or whatever) - gsub(/\[([^\]]+)\]/) {|match| sample($1.split('')) }. # All [ABC] become B (or A or C) - gsub('\d') {|match| sample(Numbers) }. - gsub('\w') {|match| sample(Letters) } + def regexify(reg) + reg = reg.source if reg.respond_to?(:source) # Handle either a Regexp or a String that looks like a Regexp + reg + .gsub(%r{^\/?\^?}, '').gsub(%r{\$?\/?$}, '') # Ditch the anchors + .gsub(/\{(\d+)\}/, '{\1,\1}').gsub(/\?/, '{0,1}') # All {2} become {2,2} and ? become {0,1} + .gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # [12]{1,2} becomes [12] or [12][12] + .gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # (12|34){1,2} becomes (12|34) or (12|34)(12|34) + .gsub(/(\\?.)\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # A{1,2} becomes A or AA or \d{3} becomes \d\d\d + .gsub(/\((.*?)\)/) { |match| sample(match.gsub(/[\(\)]/, '').split('|')) } # (this|that) becomes 'this' or 'that' + .gsub(/\[([^\]]+)\]/) { |match| match.gsub(/(\w\-\w)/) { |range| sample(Array(Range.new(*range.split('-')))) } } # All A-Z inside of [] become C (or X, or whatever) + .gsub(/\[([^\]]+)\]/) { |_match| sample(Regexp.last_match(1).split('')) } # All [ABC] become B (or A or C) + .gsub('\d') { |_match| sample(Numbers) } + .gsub('\w') { |_match| sample(Letters) } end # Helper for the common approach of grabbing a translation # with an array of values and selecting one of them. def fetch(key) fetched = sample(translate("faker.#{key}")) - if fetched && fetched.match(/^\//) && fetched.match(/\/$/) # A regex + if fetched && fetched.match(%r{^\/}) && fetched.match(%r{\/$}) # A regex regexify(fetched) else fetched @@ -108,7 +105,7 @@ def fetch(key) def fetch_all(key) fetched = translate("faker.#{key}") fetched = fetched.last if fetched.size <= 1 - if !fetched.respond_to?(:sample) && fetched.match(/^\//) && fetched.match(/\/$/) # A regex + if !fetched.respond_to?(:sample) && fetched.match(%r{^\/}) && fetched.match(%r{\/$}) # A regex regexify(fetched) else fetched @@ -120,7 +117,7 @@ def fetch_all(key) # formatted translation: e.g., "#{first_name} #{last_name}". def parse(key) fetched = fetch(key) - parts = fetched.scan(/(\(?)#\{([A-Za-z]+\.)?([^\}]+)\}([^#]+)?/).map {|prefix, kls, meth, etc| + parts = fetched.scan(/(\(?)#\{([A-Za-z]+\.)?([^\}]+)\}([^#]+)?/).map do |prefix, kls, meth, etc| # If the token had a class Prefix (e.g., Name.first_name) # grab the constant, otherwise use self cls = kls ? Faker.const_get(kls.chop) : self @@ -134,8 +131,8 @@ def parse(key) text += cls.respond_to?(meth) ? cls.send(meth) : fetch("#{(kls || self).to_s.split('::').last.downcase}.#{meth.downcase}") # And tack on spaces, commas, etc. left over in the string - text += etc.to_s - } + text + etc.to_s + end # If the fetched key couldn't be parsed, then fallback to numerify parts.any? ? parts.join : numerify(fetched) end @@ -146,7 +143,7 @@ def translate(*args) opts = args.last.is_a?(Hash) ? args.pop : {} opts[:locale] ||= Faker::Config.locale opts[:raise] = true - I18n.translate(*(args.push(opts))) + I18n.translate(*args.push(opts)) rescue I18n::MissingTranslationData opts = args.last.is_a?(Hash) ? args.pop : {} opts[:locale] = :en @@ -154,7 +151,7 @@ def translate(*args) # Super-simple fallback -- fallback to en if the # translation was missing. If the translation isn't # in en either, then it will raise again. - I18n.translate(*(args.push(opts))) + I18n.translate(*args.push(opts)) end # Executes block with given locale set. @@ -175,17 +172,21 @@ def flexible(key) # name: # girls_name: ["Alice", "Cheryl", "Tatiana"] # Then you can call Faker::Name.girls_name and it will act like #first_name - def method_missing(m, *args, &block) + def method_missing(mth, *args, &block) super unless @flexible_key # Use the alternate form of translate to get a nil rather than a "missing translation" string - if translation = translate(:faker)[@flexible_key][m] + if (translation = translate(:faker)[@flexible_key][mth]) sample(translation) else super end end + def respond_to_missing?(method_name, include_private = false) + super + end + # Generates a random value between the interval def rand_in_range(from, to) from, to = to, from if to < from @@ -193,7 +194,7 @@ def rand_in_range(from, to) end def unique(max_retries = 10_000) - @unique_generator ||= UniqueGenerator.new(self, max_retries) + @unique ||= UniqueGenerator.new(self, max_retries) end def sample(list) @@ -217,7 +218,7 @@ def rand(max = nil) end end -Dir.glob(File.join(File.dirname(__FILE__), 'faker','*.rb')).sort.each {|f| require f } +Dir.glob(File.join(File.dirname(__FILE__), 'faker', '*.rb')).sort.each { |f| require f } require 'extensions/array' require 'extensions/symbol' diff --git a/lib/faker/address.rb b/lib/faker/address.rb index f74f455db1..c7af355f58 100644 --- a/lib/faker/address.rb +++ b/lib/faker/address.rb @@ -28,7 +28,7 @@ def community end def zip_code(state_abbreviation = '') - return bothify(fetch('address.postcode')) if state_abbreviation === '' + return bothify(fetch('address.postcode')) if state_abbreviation.empty? # provide a zip code that is valid for the state provided # see http://www.fincen.gov/forms/files/us_state_territory_zip_codes.pdf @@ -39,17 +39,40 @@ def time_zone fetch('address.time_zone') end - alias_method :zip, :zip_code - alias_method :postcode, :zip_code + alias zip zip_code + alias postcode zip_code - def street_suffix; fetch('address.street_suffix'); end - def city_suffix; fetch('address.city_suffix'); end - def city_prefix; fetch('address.city_prefix'); end - def state_abbr; fetch('address.state_abbr'); end - def state; fetch('address.state'); end - def country; fetch('address.country'); end - def country_code; fetch('address.country_code'); end - def country_code_long; fetch('address.country_code_long'); end + def street_suffix + fetch('address.street_suffix') + end + + def city_suffix + fetch('address.city_suffix') + end + + def city_prefix + fetch('address.city_prefix') + end + + def state_abbr + fetch('address.state_abbr') + end + + def state + fetch('address.state') + end + + def country + fetch('address.country') + end + + def country_code + fetch('address.country_code') + end + + def country_code_long + fetch('address.country_code_long') + end def latitude ((rand * 180) - 90).to_s diff --git a/lib/faker/app.rb b/lib/faker/app.rb index 3be17c4393..b0d503d88f 100644 --- a/lib/faker/app.rb +++ b/lib/faker/app.rb @@ -1,7 +1,6 @@ module Faker class App < Base class << self - def name fetch('app.name') end @@ -15,9 +14,8 @@ def author end def semantic_version(major: 0..9, minor: 0..9, patch: 1..9) - [ major, minor, patch ].map {|chunk| sample(Array(chunk)) }.join('.') + [major, minor, patch].map { |chunk| sample(Array(chunk)) }.join('.') end - end end end diff --git a/lib/faker/avatar.rb b/lib/faker/avatar.rb index 614451d25c..cdf839be44 100644 --- a/lib/faker/avatar.rb +++ b/lib/faker/avatar.rb @@ -1,10 +1,10 @@ module Faker class Avatar < Base class << self - SUPPORTED_FORMATS = %w(png jpg bmp) + SUPPORTED_FORMATS = %w[png jpg bmp].freeze def image(slug = nil, size = '300x300', format = 'png', set = 'set1', bgset = nil) - raise ArgumentError, "Size should be specified in format 300x300" unless size.match(/^[0-9]+x[0-9]+$/) + raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/ raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format) slug ||= Faker::Lorem.words.join bgset_query = "&bgset=#{bgset}" if bgset diff --git a/lib/faker/bank.rb b/lib/faker/bank.rb index 658619e6e2..c8550d3a70 100644 --- a/lib/faker/bank.rb +++ b/lib/faker/bank.rb @@ -34,12 +34,12 @@ def iban(country_code = 'GB') # source: https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN def iban_checksum(country_code, account) # Converts letters to numbers according the iban rules, A=10..Z=35 - account_to_number = "#{account}#{country_code}00".upcase.chars.map { |d| - d.match(/[A-Z]/) ? (d.ord - 55).to_s : d - }.join.to_i + account_to_number = "#{account}#{country_code}00".upcase.chars.map do |d| + d =~ /[A-Z]/ ? (d.ord - 55).to_s : d + end.join.to_i # This is answer to (iban_to_num + checksum) % 97 == 1 - checksum = ( 1 - account_to_number ) % 97 + checksum = (1 - account_to_number) % 97 # Use leftpad to make the size always to 2 checksum.to_s.rjust(2, '0') diff --git a/lib/faker/beer.rb b/lib/faker/beer.rb index d87f4bd35e..74280c8023 100644 --- a/lib/faker/beer.rb +++ b/lib/faker/beer.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + module Faker class Beer < Base flexible :beer diff --git a/lib/faker/bitcoin.rb b/lib/faker/bitcoin.rb index 0542d1dd5f..f084365eed 100644 --- a/lib/faker/bitcoin.rb +++ b/lib/faker/bitcoin.rb @@ -4,11 +4,10 @@ module Faker class Bitcoin < Base class << self - PROTOCOL_VERSIONS = { main: 0, testnet: 111 - } + }.freeze def address address_for(:main) @@ -25,16 +24,16 @@ def base58(str) base = alphabet.size lv = 0 - str.split('').reverse.each_with_index { |v,i| lv += v.unpack('C')[0] * 256**i } + str.split('').reverse.each_with_index { |v, i| lv += v.unpack('C')[0] * 256**i } ret = '' - while lv > 0 do + while lv > 0 lv, mod = lv.divmod(base) ret << alphabet[mod] end npad = str.match(/^#{0.chr}*/)[0].to_s.size - '1'*npad + ret.reverse + '1' * npad + ret.reverse end def address_for(network) diff --git a/lib/faker/breaking_bad.rb b/lib/faker/breaking_bad.rb index 9797200f94..628463e092 100644 --- a/lib/faker/breaking_bad.rb +++ b/lib/faker/breaking_bad.rb @@ -1,9 +1,7 @@ -# encoding: utf-8 # frozen_string_literal: true module Faker class BreakingBad < Base - def self.character fetch('breaking_bad.character') end @@ -11,6 +9,5 @@ def self.character def self.episode fetch('breaking_bad.episode') end - end end diff --git a/lib/faker/business.rb b/lib/faker/business.rb index 4b5385789f..a19843345f 100644 --- a/lib/faker/business.rb +++ b/lib/faker/business.rb @@ -10,13 +10,12 @@ def credit_card_number end def credit_card_expiry_date - ::Date.today + (365 * (rand(4) + 1)) + ::Date.today + (365 * rand(1..4)) end def credit_card_type fetch('business.credit_card_types') end end - end end diff --git a/lib/faker/chuck_norris.rb b/lib/faker/chuck_norris.rb index a52b917b24..07d4efefe6 100644 --- a/lib/faker/chuck_norris.rb +++ b/lib/faker/chuck_norris.rb @@ -4,8 +4,9 @@ class ChuckNorris < Base class << self # from: https://github.com/jenkinsci/chucknorris-plugin/blob/master/src/main/java/hudson/plugins/chucknorris/FactGenerator.java - def fact; fetch('chuck_norris.fact'); end - + def fact + fetch('chuck_norris.fact') + end end end end diff --git a/lib/faker/code.rb b/lib/faker/code.rb index 61fa92fd7a..b99c4de354 100644 --- a/lib/faker/code.rb +++ b/lib/faker/code.rb @@ -2,11 +2,10 @@ module Faker class Code < Base flexible :code class << self - # Generates a 10 digit NPI (National Provider Identifier # issued to health care providers in the United States) def npi - rand(10 ** 10).to_s.rjust(10, '0') + rand(10**10).to_s.rjust(10, '0') end # By default generates 10 sign isbn code in format 123456789-X @@ -49,20 +48,19 @@ def asin fetch('code.asin') end - private + private # Reporting body identifier - RBI = %w(01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99).freeze + RBI = %w[01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99].freeze def generate_imei - pos = 0 str = Array.new(15, 0) sum = 0 t = 0 len_offset = 0 len = 15 - # Fill in the first two values of the string based with the specified prefix. + # Fill in the first two values of the string based with the specified prefix. # Reporting Body Identifier list: http://en.wikipedia.org/wiki/Reporting_Body_Identifier arr = sample(RBI) str[0] = arr[0].to_i @@ -78,12 +76,10 @@ def generate_imei # Calculate the Luhn checksum of the values thus far len_offset = (len + 1) % 2 (0..(len - 1)).each do |position| - if (position + len_offset) % 2 != 0 + if (position + len_offset).odd? t = str[position] * 2 - if t > 9 - t -= 9 - end + t -= 9 if t > 9 sum += t else @@ -110,37 +106,37 @@ def generate_base13_isbn values << "-#{((10 - remainder) % 10)}" end - def sum(values, &block) + def sum(values) values.split(//).each_with_index.inject(0) do |sum, (value, index)| - sum + block.call(value, index) + sum + yield(value, index) end end def generate_base8_ean values = regexify(/\d{7}/) - check_digit = 10 - values.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT8[i] } % 10 + check_digit = 10 - values.split(//).each_with_index.inject(0) { |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT8[i] } % 10 values << (check_digit == 10 ? 0 : check_digit).to_s end def generate_base13_ean values = regexify(/\d{12}/) - check_digit = 10 - values.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT13[i] } % 10 + check_digit = 10 - values.split(//).each_with_index.inject(0) { |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT13[i] } % 10 values << (check_digit == 10 ? 0 : check_digit).to_s end - EAN_CHECK_DIGIT8 = [3, 1, 3, 1, 3, 1, 3] - EAN_CHECK_DIGIT13 = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3] + EAN_CHECK_DIGIT8 = [3, 1, 3, 1, 3, 1, 3].freeze + EAN_CHECK_DIGIT13 = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3].freeze def rut_verificator_digit(rut) - total = rut.to_s.rjust(8, '0').split(//).zip(%w(3 2 7 6 5 4 3 2)).collect{|a, b| a.to_i * b.to_i}.inject(:+) + total = rut.to_s.rjust(8, '0').split(//).zip(%w[3 2 7 6 5 4 3 2]).collect { |a, b| a.to_i * b.to_i }.inject(:+) (11 - total % 11).to_s.gsub(/10/, 'k').gsub(/11/, '0') end def generate_nric_check_alphabet(values, prefix) - weight = %w(2 7 6 5 4 3 2) + weight = %w[2 7 6 5 4 3 2] total = values.split(//).zip(weight).collect { |a, b| a.to_i * b.to_i }.inject(:+) - total = total + 4 if prefix == 'T' - %w(A B C D E F G H I Z J)[10 - total % 11] + total += 4 if prefix == 'T' + %w[A B C D E F G H I Z J][10 - total % 11] end end end diff --git a/lib/faker/color.rb b/lib/faker/color.rb index e9e48ef854..9bf18ca544 100644 --- a/lib/faker/color.rb +++ b/lib/faker/color.rb @@ -2,7 +2,7 @@ module Faker class Color < Base class << self def hex_color - '#%06x' % (rand * 0xffffff) + format('#%06x', (rand * 0xffffff)) end def color_name @@ -14,7 +14,7 @@ def single_rgb_color end def rgb_color - 3.times.collect { single_rgb_color } + Array.new(3) { single_rgb_color } end # returns [hue, saturation, lightness] diff --git a/lib/faker/commerce.rb b/lib/faker/commerce.rb index b6288d009d..40a3012c31 100644 --- a/lib/faker/commerce.rb +++ b/lib/faker/commerce.rb @@ -1,6 +1,5 @@ module Faker class Commerce < Base - class << self def color fetch('color.name') @@ -32,11 +31,11 @@ def material fetch('commerce.product_name.material') end - def price(range=0..100.0, as_string=false) - price = (rand(range) * 100).floor/100.0 + def price(range = 0..100.0, as_string = false) + price = (rand(range) * 100).floor / 100.0 if as_string price_parts = price.to_s.split('.') - price = price_parts[0] + '.' + price_parts[-1].ljust(2, "0") + price = price_parts[0] + '.' + price_parts[-1].ljust(2, '0') end price end diff --git a/lib/faker/company.rb b/lib/faker/company.rb index 1a849b15ed..d061a8b4bc 100644 --- a/lib/faker/company.rb +++ b/lib/faker/company.rb @@ -17,7 +17,7 @@ def industry # Generate a buzzword-laden catch phrase. def catch_phrase - translate('faker.company.buzzwords').collect {|list| sample(list) }.join(' ') + translate('faker.company.buzzwords').collect { |list| sample(list) }.join(' ') end def buzzword @@ -26,29 +26,31 @@ def buzzword # When a straight answer won't do, BS to the rescue! def bs - translate('faker.company.bs').collect {|list| sample(list) }.join(' ') + translate('faker.company.bs').collect { |list| sample(list) }.join(' ') end def ein - ('%09d' % rand(10 ** 9)).gsub(/(\d{2})(\d{7})/, '\\1-\\2') + format('%09d', rand(10**9)).gsub(/(\d{2})(\d{7})/, '\\1-\\2') end def duns_number - ('%09d' % rand(10 ** 9)).gsub(/(\d{2})(\d{3})(\d{4})/, '\\1-\\2-\\3') + format('%09d', rand(10**9)).gsub(/(\d{2})(\d{3})(\d{4})/, '\\1-\\2-\\3') end # Get a random company logo url in PNG format. def logo - rand_num = rand(13) + 1 + rand_num = rand(1..13) "https://pigment.github.io/fake-logos/logos/medium/color/#{rand_num}.png" end + # rubocop:disable Style/AsciiComments # Get a random Spanish organization number. See more here https://es.wikipedia.org/wiki/Número_de_identificación_fiscal + # rubocop:enable Style/AsciiComments def spanish_organisation_number # Valid leading character: A, B, C, D, E, F, G, H, J, N, P, Q, R, S, U, V, W # 7 digit numbers - letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'N', 'P', 'Q', 'R', 'S', 'U', 'V', 'W'] - base = [sample(letters), ('%07d' % rand(10 ** 7))].join + letters = %w[A B C D E F G H J N P Q R S U V W] + base = [sample(letters), format('%07d', rand(10**7))].join base end @@ -57,7 +59,7 @@ def swedish_organisation_number # Valid leading digit: 1, 2, 3, 5, 6, 7, 8, 9 # Valid third digit: >= 2 # Last digit is a control digit - base = [sample([1, 2, 3, 5, 6, 7, 8, 9]), sample((0..9).to_a), sample((2..9).to_a), ('%06d' % rand(10 ** 6))].join + base = [sample([1, 2, 3, 5, 6, 7, 8, 9]), sample((0..9).to_a), sample((2..9).to_a), format('%06d', rand(10**6))].join base + luhn_algorithm(base).to_s end @@ -78,14 +80,14 @@ def norwegian_organisation_number # Valid leading digit: 8, 9 mod11_check = nil while mod11_check.nil? - base = [sample([8, 9]), ('%07d' % rand(10 ** 7))].join + base = [sample([8, 9]), format('%07d', rand(10**7))].join mod11_check = mod11(base) end base + mod11_check.to_s end def australian_business_number - base = ('%09d' % rand(10 ** 9)) + base = format('%09d', rand(10**9)) abn = "00#{base}" (99 - (abn_checksum(abn) % 89)).to_s + base @@ -95,7 +97,7 @@ def profession fetch('company.profession') end - private + private # Mod11 functionality from https://github.com/badmanski/mod11/blob/master/lib/mod11.rb def mod11(number) @@ -122,11 +124,11 @@ def luhn_algorithm(number) multiplications = [] number.split(//).each_with_index do |digit, i| - if i.even? - multiplications << digit.to_i * 2 - else - multiplications << digit.to_i - end + multiplications << if i.even? + digit.to_i * 2 + else + digit.to_i + end end sum = 0 @@ -137,17 +139,17 @@ def luhn_algorithm(number) end end - if sum % 10 == 0 - control_digit = 0 - else - control_digit = (sum / 10 + 1) * 10 - sum - end + control_digit = if (sum % 10).zero? + 0 + else + (sum / 10 + 1) * 10 - sum + end control_digit end def abn_checksum(abn) - abn_weights = [10,1,3,5,7,9,11,13,15,17,19] + abn_weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19] sum = 0 abn_weights.each_with_index do |weight, i| @@ -156,7 +158,6 @@ def abn_checksum(abn) sum end - end end end diff --git a/lib/faker/currency.rb b/lib/faker/currency.rb index f76e3f1450..9b2f5bf12d 100644 --- a/lib/faker/currency.rb +++ b/lib/faker/currency.rb @@ -1,7 +1,6 @@ module Faker class Currency < Base class << self - def name fetch('currency.name') end diff --git a/lib/faker/date.rb b/lib/faker/date.rb index c5601af209..7c8345c877 100644 --- a/lib/faker/date.rb +++ b/lib/faker/date.rb @@ -9,7 +9,7 @@ def between(from, to) end def between_except(from, to, excepted) - raise ArgumentError, "From date, to date and excepted date must not be the same" if from == to && to == excepted + raise ArgumentError, 'From date, to date and excepted date must not be the same' if from == to && to == excepted excepted = get_date_object(excepted) loop do diff --git a/lib/faker/demographic.rb b/lib/faker/demographic.rb index 666a940e01..cf3051d982 100644 --- a/lib/faker/demographic.rb +++ b/lib/faker/demographic.rb @@ -25,9 +25,9 @@ def height(unit = :metric) case unit when :imperial inches = rand_in_range(57, 86) - return "#{inches / 12} ft, #{inches % 12} in" + "#{inches / 12} ft, #{inches % 12} in" when :metric - return rand_in_range(1.45, 2.13).round(2).to_s + rand_in_range(1.45, 2.13).round(2).to_s end end end diff --git a/lib/faker/dr_who.rb b/lib/faker/dr_who.rb index 81fc96ad3b..05f6b69be7 100644 --- a/lib/faker/dr_who.rb +++ b/lib/faker/dr_who.rb @@ -1,10 +1,7 @@ -#encoding: utf-8 -#frozen_string_literal: true +# frozen_string_literal: true module Faker - class DrWho < Base - def self.character fetch('dr_who.character') end @@ -28,7 +25,5 @@ def self.villian def self.specie fetch('dr_who.species') end - - end #class DrWho - -end #module Faker + end +end diff --git a/lib/faker/dumb_and_dumber.rb b/lib/faker/dumb_and_dumber.rb index 5d49201c9b..cb92bd1ef6 100644 --- a/lib/faker/dumb_and_dumber.rb +++ b/lib/faker/dumb_and_dumber.rb @@ -4,7 +4,7 @@ class << self def actor fetch('dumb_and_dumber.actors') end - + def character fetch('dumb_and_dumber.characters') end diff --git a/lib/faker/dune.rb b/lib/faker/dune.rb index 5d8b5e2cac..4b5461f995 100644 --- a/lib/faker/dune.rb +++ b/lib/faker/dune.rb @@ -26,11 +26,11 @@ def quote(character = nil) unless quoted_characters.include?(character.to_sym) raise ArgumentError, - "Characters quoted can be left blank or #{quoted_characters.join(', ')}" + "Characters quoted can be left blank or #{quoted_characters.join(', ')}" end end - return fetch('dune.quotes.' + character) + fetch('dune.quotes.' + character) end def saying(source = nil) @@ -43,11 +43,11 @@ def saying(source = nil) unless sourced_sayings.include?(source.to_sym) raise ArgumentError, - "Sources quoted in sayings can be left blank or #{sourced_sayings.join(', ')}" + "Sources quoted in sayings can be left blank or #{sourced_sayings.join(', ')}" end end - return fetch('dune.sayings.' + source) + fetch('dune.sayings.' + source) end end end diff --git a/lib/faker/file.rb b/lib/faker/file.rb index aeb2bde832..1a7791bcce 100644 --- a/lib/faker/file.rb +++ b/lib/faker/file.rb @@ -1,7 +1,6 @@ module Faker class File < Base class << self - def extension fetch('file.extension') end @@ -11,14 +10,12 @@ def mime_type end def file_name(dir = nil, name = nil, ext = nil, directory_separator = '/') - - dir = Faker::Internet::slug unless dir - name = Faker::Lorem::word.downcase unless name + dir ||= Faker::Internet.slug + name ||= Faker::Lorem.word.downcase ext ||= extension [dir, name].join(directory_separator) + ".#{ext}" end - end end end diff --git a/lib/faker/fillmurray.rb b/lib/faker/fillmurray.rb index 9c26d510fe..3b8c3e8fd8 100644 --- a/lib/faker/fillmurray.rb +++ b/lib/faker/fillmurray.rb @@ -1,11 +1,10 @@ module Faker class Fillmurray < Base class << self - def image(grayscale = false, width = 200, height = 200) - raise ArgumentError, "Width should be a number" unless width.to_s.match(/^\d+$/) - raise ArgumentError, "Height should be a number" unless height.to_s.match(/^\d+$/) - raise ArgumentError, "Grayscale should be a boolean" unless [true, false].include?(grayscale) + raise ArgumentError, 'Width should be a number' unless width.to_s =~ /^\d+$/ + raise ArgumentError, 'Height should be a number' unless height.to_s =~ /^\d+$/ + raise ArgumentError, 'Grayscale should be a boolean' unless [true, false].include?(grayscale) grayscale == true ? "https://fillmurray.com/g/#{width}/#{height}" : "https://fillmurray.com/#{width}/#{height}" end diff --git a/lib/faker/finance.rb b/lib/faker/finance.rb index c2f32945f2..51b70db399 100644 --- a/lib/faker/finance.rb +++ b/lib/faker/finance.rb @@ -1,9 +1,8 @@ module Faker class Finance < Base - - CREDIT_CARD_TYPES = [:visa, :mastercard, :discover, :american_express, - :diners_club, :jcb, :switch, :solo, :dankort, - :maestro, :forbrugsforeningen, :laser].freeze + CREDIT_CARD_TYPES = %i[visa mastercard discover american_express + diners_club jcb switch solo dankort + maestro forbrugsforeningen laser].freeze class << self def credit_card(*types) diff --git a/lib/faker/food.rb b/lib/faker/food.rb index f44035f465..b3de3f54a6 100644 --- a/lib/faker/food.rb +++ b/lib/faker/food.rb @@ -20,7 +20,7 @@ def spice def measurement fetch('food.measurement_sizes') + ' ' + fetch('food.measurements') end - + def metric_measurement fetch('food.metric_measurements') end diff --git a/lib/faker/hacker.rb b/lib/faker/hacker.rb index eec38fea1b..99dfc3e649 100644 --- a/lib/faker/hacker.rb +++ b/lib/faker/hacker.rb @@ -1,4 +1,4 @@ -#Port of http://shinytoylabs.com/jargon/ +# Port of http://shinytoylabs.com/jargon/ module Faker class Hacker < Base flexible :hacker @@ -29,17 +29,15 @@ def ingverb end def phrases - [ "If we #{verb} the #{noun}, we can get to the #{abbreviation} #{noun} through the #{adjective} #{abbreviation} #{noun}!", - "We need to #{verb} the #{adjective} #{abbreviation} #{noun}!", - "Try to #{verb} the #{abbreviation} #{noun}, maybe it will #{verb} the #{adjective} #{noun}!", - "You can't #{verb} the #{noun} without #{ingverb} the #{adjective} #{abbreviation} #{noun}!", - "Use the #{adjective} #{abbreviation} #{noun}, then you can #{verb} the #{adjective} #{noun}!", - "The #{abbreviation} #{noun} is down, #{verb} the #{adjective} #{noun} so we can #{verb} the #{abbreviation} #{noun}!", - "#{ingverb} the #{noun} won't do anything, we need to #{verb} the #{adjective} #{abbreviation} #{noun}!".capitalize, - "I'll #{verb} the #{adjective} #{abbreviation} #{noun}, that should #{noun} the #{abbreviation} #{noun}!" - ] + ["If we #{verb} the #{noun}, we can get to the #{abbreviation} #{noun} through the #{adjective} #{abbreviation} #{noun}!", + "We need to #{verb} the #{adjective} #{abbreviation} #{noun}!", + "Try to #{verb} the #{abbreviation} #{noun}, maybe it will #{verb} the #{adjective} #{noun}!", + "You can't #{verb} the #{noun} without #{ingverb} the #{adjective} #{abbreviation} #{noun}!", + "Use the #{adjective} #{abbreviation} #{noun}, then you can #{verb} the #{adjective} #{noun}!", + "The #{abbreviation} #{noun} is down, #{verb} the #{adjective} #{noun} so we can #{verb} the #{abbreviation} #{noun}!", + "#{ingverb} the #{noun} won't do anything, we need to #{verb} the #{adjective} #{abbreviation} #{noun}!".capitalize, + "I'll #{verb} the #{adjective} #{abbreviation} #{noun}, that should #{noun} the #{abbreviation} #{noun}!"] end end - end end diff --git a/lib/faker/hipster.rb b/lib/faker/hipster.rb index 0757d1c9c9..78e6d34d08 100644 --- a/lib/faker/hipster.rb +++ b/lib/faker/hipster.rb @@ -3,7 +3,7 @@ class Hipster < Base class << self def word random_word = sample(translate('faker.hipster.words')) - random_word.match(/\s/) ? word : random_word + random_word =~ /\s/ ? word : random_word end def words(num = 3, supplemental = false, spaces_allowed = false) @@ -12,11 +12,11 @@ def words(num = 3, supplemental = false, spaces_allowed = false) translate('faker.hipster.words') + (supplemental ? translate('faker.lorem.words') : []) ) - word_list = word_list * ((resolved_num / word_list.length) + 1) + word_list *= ((resolved_num / word_list.length) + 1) return shuffle(word_list)[0, resolved_num] if spaces_allowed words = shuffle(word_list)[0, resolved_num] - words.each_with_index { |w, i| words[i] = word if w.match(/\s/) } + words.each_with_index { |w, i| words[i] = word if w =~ /\s/ } end def sentence(word_count = 4, supplemental = false, random_words_to_add = 6) @@ -43,7 +43,7 @@ def paragraphs(paragraph_count = 3, supplemental = false) end end - private + private # If an array or range is passed, a random value will be selected. # All other values are simply returned. diff --git a/lib/faker/id_number.rb b/lib/faker/id_number.rb index 796dff65ef..39eba247e1 100644 --- a/lib/faker/id_number.rb +++ b/lib/faker/id_number.rb @@ -1,16 +1,14 @@ module Faker class IDNumber < Base - INVALID_SSN = [ - /0{3}-\d{2}-\d{4}/, - /\d{3}-0{2}-\d{4}/, - /\d{3}-\d{2}-0{4}/, - /666-\d{2}-\d{4}/, - /9\d{2}-\d{2}-\d{4}/ - ] + /0{3}-\d{2}-\d{4}/, + /\d{3}-0{2}-\d{4}/, + /\d{3}-\d{2}-0{4}/, + /666-\d{2}-\d{4}/, + /9\d{2}-\d{2}-\d{4}/ + ].freeze class << self - def valid _translate('valid') end @@ -31,6 +29,5 @@ def _translate(key) parse("id_number.#{key}") end end - end end diff --git a/lib/faker/internet.rb b/lib/faker/internet.rb index 47d68ba87e..57b843fe38 100644 --- a/lib/faker/internet.rb +++ b/lib/faker/internet.rb @@ -1,7 +1,6 @@ module Faker class Internet < Base class << self - def email(name = nil) [user_name(name), domain_name].join('@') end @@ -11,37 +10,40 @@ def free_email(name = nil) end def safe_email(name = nil) - [user_name(name), 'example.'+ sample(%w[org com net])].join('@') + [user_name(name), 'example.' + sample(%w[org com net])].join('@') end - def user_name(specifier = nil, separators = %w(. _)) + def user_name(specifier = nil, separators = %w[. _]) with_locale(:en) do - if specifier.respond_to?(:scan) - return shuffle(specifier.scan(/\w+/)).join(sample(separators)).downcase - elsif specifier.kind_of?(Integer) + return shuffle(specifier.scan(/\w+/)).join(sample(separators)).downcase if specifier.respond_to?(:scan) + if specifier.is_a?(Integer) # If specifier is Integer and has large value, Argument error exception is raised to overcome memory full error - raise ArgumentError, "Given argument is too large" if specifier > 10**6 + raise ArgumentError, 'Given argument is too large' if specifier > 10**6 tries = 0 # Don't try forever in case we get something like 1_000_000. - begin + result = nil + loop do result = user_name(nil, separators) tries += 1 - end while result.length < specifier && tries < 7 - return result * (specifier/result.length + 1) if specifier > 0 - elsif specifier.kind_of?(Range) + break unless result.length < specifier && tries < 7 + end + return result * (specifier / result.length + 1) if specifier > 0 + elsif specifier.is_a?(Range) tries = 0 - begin + result = nil + loop do result = user_name(specifier.min, separators) tries += 1 - end while !specifier.include?(result.length) && tries < 7 + break unless !specifier.include?(result.length) && tries < 7 + end return result[0...specifier.max] end sample([ - Char.prepare(Name.first_name), - [Name.first_name, Name.last_name].map{ |name| - Char.prepare(name) - }.join(sample(separators)) - ]) + Char.prepare(Name.first_name), + [Name.first_name, Name.last_name].map do |name| + Char.prepare(name) + end.join(sample(separators)) + ]) end end @@ -60,7 +62,7 @@ def password(min_length = 8, max_length = 16, mix_case = true, special_chars = f end if special_chars - chars = %w(! @ # $ % ^ & *) + chars = %w[! @ # $ % ^ & *] rand(1..min_length).times do |i| temp[i] = chars[rand(chars.length)] end @@ -73,7 +75,7 @@ def domain_name with_locale(:en) { [Char.prepare(domain_word), domain_suffix].join('.') } end - def fix_umlauts(string='') + def fix_umlauts(string = '') Char.fix_umlauts(string) end @@ -85,74 +87,78 @@ def domain_suffix fetch('internet.domain_suffix') end - def mac_address(prefix='') - prefix_digits = prefix.split(':').map{ |d| d.to_i(16) } - address_digits = (6 - prefix_digits.size).times.map{ rand(256) } - (prefix_digits + address_digits).map{ |d| '%02x' % d }.join(':') + def mac_address(prefix = '') + prefix_digits = prefix.split(':').map { |d| d.to_i(16) } + address_digits = Array.new((6 - prefix_digits.size)) { rand(256) } + (prefix_digits + address_digits).map { |d| format('%02x', d) }.join(':') end def ip_v4_address ary = (2..254).to_a - [ sample(ary), sample(ary), sample(ary), sample(ary) ].join('.') + [sample(ary), sample(ary), sample(ary), sample(ary)].join('.') end def private_ip_v4_address - begin + addr = nil + loop do addr = ip_v4_address - end while !private_net_checker[addr] + break if private_net_checker[addr] + end addr end def public_ip_v4_address - begin + addr = nil + loop do addr = ip_v4_address - end while reserved_net_checker[addr] + break unless reserved_net_checker[addr] + end addr end def private_nets_regex [ - /^10\./, # 10.0.0.0 – 10.255.255.255 - /^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 – 100.127.255.255 - /^127\./, # 127.0.0.0 – 127.255.255.255 - /^169\.254\./, # 169.254.0.0 – 169.254.255.255 - /^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 – 172.31.255.255 - /^192\.0\.0\./, # 192.0.0.0 – 192.0.0.255 - /^192\.168\./, # 192.168.0.0 – 192.168.255.255 - /^198\.(1[8-9])\./ # 198.18.0.0 – 198.19.255.255 + /^10\./, # 10.0.0.0 - 10.255.255.255 + /^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 - 100.127.255.255 + /^127\./, # 127.0.0.0 - 127.255.255.255 + /^169\.254\./, # 169.254.0.0 - 169.254.255.255 + /^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 - 172.31.255.255 + /^192\.0\.0\./, # 192.0.0.0 - 192.0.0.255 + /^192\.168\./, # 192.168.0.0 - 192.168.255.255 + /^198\.(1[8-9])\./ # 198.18.0.0 - 198.19.255.255 ] end def private_net_checker - lambda { |addr| private_nets_regex.any? { |net| net =~ addr } } + ->(addr) { private_nets_regex.any? { |net| net =~ addr } } end def reserved_nets_regex [ - /^0\./, # 0.0.0.0 – 0.255.255.255 - /^192\.0\.2\./, # 192.0.2.0 – 192.0.2.255 - /^192\.88\.99\./, # 192.88.99.0 – 192.88.99.255 - /^198\.51\.100\./, # 198.51.100.0 – 198.51.100.255 - /^203\.0\.113\./, # 203.0.113.0 – 203.0.113.255 - /^(22[4-9]|23\d)\./, # 224.0.0.0 – 239.255.255.255 - /^(24\d|25[0-5])\./ # 240.0.0.0 – 255.255.255.254 and 255.255.255.255 + /^0\./, # 0.0.0.0 - 0.255.255.255 + /^192\.0\.2\./, # 192.0.2.0 - 192.0.2.255 + /^192\.88\.99\./, # 192.88.99.0 - 192.88.99.255 + /^198\.51\.100\./, # 198.51.100.0 - 198.51.100.255 + /^203\.0\.113\./, # 203.0.113.0 - 203.0.113.255 + /^(22[4-9]|23\d)\./, # 224.0.0.0 - 239.255.255.255 + /^(24\d|25[0-5])\./ # 240.0.0.0 - 255.255.255.254 and 255.255.255.255 ] end def reserved_net_checker - ->(addr){ (private_nets_regex + reserved_nets_regex).any? { |net| net =~ addr } } + ->(addr) { (private_nets_regex + reserved_nets_regex).any? { |net| net =~ addr } } end def ip_v4_cidr - "#{ip_v4_address}/#{1 + rand(31)}" + "#{ip_v4_address}/#{rand(1..31)}" end def ip_v6_address - (1..8).map { rand(65536).to_s(16) }.join(':') + (1..8).map { rand(65_536).to_s(16) }.join(':') end def ip_v6_cidr - "#{ip_v6_address}/#{1 + rand(127)}" + "#{ip_v6_address}/#{rand(1..127)}" end def url(host = domain_name, path = "/#{user_name}", scheme = 'http') @@ -161,11 +167,11 @@ def url(host = domain_name, path = "/#{user_name}", scheme = 'http') def slug(words = nil, glue = nil) glue ||= sample(%w[- _ .]) - (words || Faker::Lorem::words(2).join(' ')).gsub(' ', glue).downcase + (words || Faker::Lorem.words(2).join(' ')).gsub(' ', glue).downcase end def device_token - shuffle(rand(16 ** 64).to_s(16).rjust(64, '0').chars.to_a).join + shuffle(rand(16**64).to_s(16).rjust(64, '0').chars.to_a).join end def user_agent(vendor = nil) diff --git a/lib/faker/job.rb b/lib/faker/job.rb index e5ac2d516a..891e64cfaa 100644 --- a/lib/faker/job.rb +++ b/lib/faker/job.rb @@ -3,14 +3,17 @@ class Job < Base flexible :job class << self - def title parse('job.title') end - def field; fetch('job.field'); end - def key_skill; fetch('job.key_skills'); end + def field + fetch('job.field') + end + def key_skill + fetch('job.key_skills') + end end end end diff --git a/lib/faker/lebowski.rb b/lib/faker/lebowski.rb index a879993f5b..aa76e9de3b 100644 --- a/lib/faker/lebowski.rb +++ b/lib/faker/lebowski.rb @@ -4,7 +4,7 @@ class << self def actor fetch('lebowski.actors') end - + def character fetch('lebowski.characters') end @@ -14,4 +14,4 @@ def quote end end end -end \ No newline at end of file +end diff --git a/lib/faker/lorem.rb b/lib/faker/lorem.rb index e8d3c6dbe9..ab99a2ae11 100644 --- a/lib/faker/lorem.rb +++ b/lib/faker/lorem.rb @@ -14,7 +14,7 @@ def words(num = 3, supplemental = false) translate('faker.lorem.words') + (supplemental ? translate('faker.lorem.supplemental') : []) ) - word_list = word_list * ((resolved_num / word_list.length) + 1) + word_list *= ((resolved_num / word_list.length) + 1) shuffle(word_list)[0, resolved_num] end @@ -52,7 +52,7 @@ def questions(question_count = 3, supplemental = false) 1.upto(resolve(question_count)).collect { question(3, supplemental) } end - private + private # If an array or range is passed, a random value will be selected. # All other values are simply returned. diff --git a/lib/faker/lorem_pixel.rb b/lib/faker/lorem_pixel.rb index 31078f2a09..5e23edf7ba 100644 --- a/lib/faker/lorem_pixel.rb +++ b/lib/faker/lorem_pixel.rb @@ -1,13 +1,26 @@ module Faker class LoremPixel < Base class << self - SUPPORTED_CATEGORIES = %w(abstract animals business cats city food nightlife fashion people nature sports technics transport) + SUPPORTED_CATEGORIES = %w[abstract + animals + business + cats + city + food + nightlife + fashion + people + nature + sports + technics + transport].freeze + # rubocop:disable Metrics/ParameterLists def image(size = '300x300', is_gray = false, category = nil, number = nil, text = nil, secure: true) - raise ArgumentError, 'Size should be specified in format 300x300' unless size.match(/^[0-9]+x[0-9]+$/) + raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/ raise ArgumentError, "Supported categories are #{SUPPORTED_CATEGORIES.join(', ')}" unless category.nil? || SUPPORTED_CATEGORIES.include?(category) raise ArgumentError, 'Category required when number is passed' if !number.nil? && category.nil? - raise ArgumentError, 'Number must be between 1 and 10' unless number.nil? || (1..10).include?(number) + raise ArgumentError, 'Number must be between 1 and 10' unless number.nil? || (1..10).cover?(number) raise ArgumentError, 'Category and number must be passed when text is passed' if !text.nil? && number.nil? && category.nil? url_parts = secure ? ['https:/'] : ['http:/'] @@ -17,6 +30,7 @@ def image(size = '300x300', is_gray = false, category = nil, number = nil, text url_parts += [category, number, text].compact url_parts.join('/') end + # rubocop:enable Metrics/ParameterLists end end end diff --git a/lib/faker/lovecraft.rb b/lib/faker/lovecraft.rb index f23f417f55..961d6d9d06 100644 --- a/lib/faker/lovecraft.rb +++ b/lib/faker/lovecraft.rb @@ -6,7 +6,7 @@ def location end def fhtagn(number_of = 1) - number_of.times.collect { fetch('lovecraft.fhtagn') }.join(". ") + Array.new(number_of) { fetch('lovecraft.fhtagn') }.join('. ') end def deity @@ -23,20 +23,19 @@ def sentence(word_count = 4, random_words_to_add = 6) def word random_word = sample(translate('faker.lovecraft.words')) - random_word.match(/\s/) ? word : random_word + random_word =~ /\s/ ? word : random_word end def words(num = 3, spaces_allowed = false) resolved_num = resolve(num) word_list = translate('faker.lovecraft.words') - word_list = word_list * ((resolved_num / word_list.length) + 1) + word_list *= ((resolved_num / word_list.length) + 1) return shuffle(word_list)[0, resolved_num] if spaces_allowed words = shuffle(word_list)[0, resolved_num] - words.each_with_index { |w, i| words[i] = word if w.match(/\s/) } + words.each_with_index { |w, i| words[i] = word if w =~ /\s/ } end - def sentences(sentence_count = 3) [].tap do |sentences| 1.upto(resolve(sentence_count)) do diff --git a/lib/faker/markdown.rb b/lib/faker/markdown.rb index ae22902a95..ae27f19b43 100644 --- a/lib/faker/markdown.rb +++ b/lib/faker/markdown.rb @@ -1,7 +1,6 @@ module Faker class Markdown < Base class << self - def headers "#{fetch('markdown.headers')} #{Lorem.word.capitalize}" end @@ -20,7 +19,7 @@ def ordered_list result = [] number.times do |i| - result << "#{i.to_s}. #{Faker::Lorem.sentence(1)} \n" + result << "#{i}. #{Faker::Lorem.sentence(1)} \n" end result.join('') end @@ -29,7 +28,7 @@ def unordered_list number = rand(1..10) result = [] - number.times do |i| + number.times do |_i| result << "* #{Faker::Lorem.sentence(1)} \n" end result.join('') @@ -61,7 +60,6 @@ def random def available_methods Markdown.public_methods(false) - Base.methods end - end end end diff --git a/lib/faker/measurement.rb b/lib/faker/measurement.rb index fb50aadc2b..bd9b7e6c38 100644 --- a/lib/faker/measurement.rb +++ b/lib/faker/measurement.rb @@ -1,8 +1,8 @@ module Faker class Measurement < Base class << self - ALL = "all" - NONE = "none" + ALL = 'all'.freeze + NONE = 'none'.freeze def height(amount = rand(10)) ensure_valid_amount(amount) @@ -11,7 +11,7 @@ def height(amount = rand(10)) elsif amount == NONE fetch('measurement.height') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.height'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.height'), amount)}" end end @@ -22,7 +22,7 @@ def length(amount = rand(10)) elsif amount == NONE fetch('measurement.length') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.length'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.length'), amount)}" end end @@ -33,7 +33,7 @@ def volume(amount = rand(10)) elsif amount == NONE fetch('measurement.volume') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.volume'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.volume'), amount)}" end end @@ -44,7 +44,7 @@ def weight(amount = rand(10)) elsif amount == NONE fetch('measurement.weight') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.weight'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.weight'), amount)}" end end @@ -55,7 +55,7 @@ def metric_height(amount = rand(10)) elsif amount == NONE fetch('measurement.height') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.height'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.height'), amount)}" end end @@ -66,7 +66,7 @@ def metric_length(amount = rand(10)) elsif amount == NONE fetch('measurement.length') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.length'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.length'), amount)}" end end @@ -77,7 +77,7 @@ def metric_volume(amount = rand(10)) elsif amount == NONE fetch('measurement.volume') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.volume'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.volume'), amount)}" end end @@ -88,16 +88,14 @@ def metric_weight(amount = rand(10)) elsif amount == NONE fetch('measurement.weight') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.weight'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.weight'), amount)}" end end private def ensure_valid_amount(amount) - unless amount == NONE || amount == ALL || amount.is_a?(Integer) || amount.is_a?(Float) - raise ArgumentError, 'invalid amount' - end + raise ArgumentError, 'invalid amount' unless amount == NONE || amount == ALL || amount.is_a?(Integer) || amount.is_a?(Float) end def check_for_plural(text, number) @@ -110,14 +108,14 @@ def check_for_plural(text, number) def make_plural(text) case text - when "foot" - "feet" - when "inch" - "inches" - when "fluid ounce" - "fluid ounces" - when "metric ton" - "metric tons" + when 'foot' + 'feet' + when 'inch' + 'inches' + when 'fluid ounce' + 'fluid ounces' + when 'metric ton' + 'metric tons' else "#{text}s" end diff --git a/lib/faker/michael_scott.rb b/lib/faker/michael_scott.rb index 21cc05b910..5a68c9fff8 100644 --- a/lib/faker/michael_scott.rb +++ b/lib/faker/michael_scott.rb @@ -6,4 +6,4 @@ def quote end end end -end \ No newline at end of file +end diff --git a/lib/faker/music.rb b/lib/faker/music.rb index 5c41901bc2..f2f135e261 100644 --- a/lib/faker/music.rb +++ b/lib/faker/music.rb @@ -14,7 +14,7 @@ def instrument end def keys - ['C', 'D', 'E', 'F', 'G', 'A', 'B'] + %w[C D E F G A B] end def key_variants diff --git a/lib/faker/name.rb b/lib/faker/name.rb index be88ba2a1e..4bf3b72c37 100644 --- a/lib/faker/name.rb +++ b/lib/faker/name.rb @@ -3,7 +3,6 @@ class Name < Base flexible :name class << self - def name parse('name.name') end @@ -34,8 +33,8 @@ def title "#{fetch('name.title.descriptor')} #{fetch('name.title.level')} #{fetch('name.title.job')}" end - def initials(character_count=3) - (0...character_count).map { (65 + rand(26)).chr }.join + def initials(character_count = 3) + (0...character_count).map { rand(65..90).chr }.join end def job_titles diff --git a/lib/faker/number.rb b/lib/faker/number.rb index f28ca25ddf..a7319226a2 100644 --- a/lib/faker/number.rb +++ b/lib/faker/number.rb @@ -1,7 +1,7 @@ module Faker class Number < Base class << self - def number(digits=10) + def number(digits = 10) num = '' if digits > 1 num = non_zero_digit @@ -10,11 +10,11 @@ def number(digits=10) num + leading_zero_number(digits) end - def leading_zero_number(digits=10) - (1..digits).collect {digit}.join + def leading_zero_number(digits = 10) + (1..digits).collect { digit }.join end - def decimal_part(digits=10) + def decimal_part(digits = 10) num = '' if digits > 1 num = non_zero_digit @@ -23,27 +23,27 @@ def decimal_part(digits=10) leading_zero_number(digits) + num end - def decimal(l_digits=5, r_digits=2) - l_d = self.number(l_digits) - r_d = self.decimal_part(r_digits) + def decimal(l_digits = 5, r_digits = 2) + l_d = number(l_digits) + r_d = decimal_part(r_digits) "#{l_d}.#{r_d}" end def non_zero_digit - (rand(9) + 1).to_s + rand(1..9).to_s end def digit rand(10).to_s end - def hexadecimal(digits=6) - hex = "" + def hexadecimal(digits = 6) + hex = '' digits.times { hex += rand(15).to_s(16) } hex end - def normal(mean=1, standard_deviation=1) + def normal(mean = 1, standard_deviation = 1) theta = 2 * Math::PI * rand rho = Math.sqrt(-2 * Math.log(1 - rand)) scale = standard_deviation * rho @@ -51,7 +51,7 @@ def normal(mean=1, standard_deviation=1) end def between(from = 1.00, to = 5000.00) - Faker::Base::rand_in_range(from, to) + Faker::Base.rand_in_range(from, to) end def positive(from = 1.00, to = 5000.00) diff --git a/lib/faker/omniauth.rb b/lib/faker/omniauth.rb index 94dfaf4a80..d1c43b9352 100644 --- a/lib/faker/omniauth.rb +++ b/lib/faker/omniauth.rb @@ -16,7 +16,7 @@ class << self def google(name: nil, email: nil, uid: Number.number(9)) auth = Omniauth.new(name: name, email: email) { - provider: "google_oauth2", + provider: 'google_oauth2', uid: uid, info: { name: auth.name, @@ -42,22 +42,22 @@ def google(name: nil, email: nil, uid: Number.number(9)) profile: "https://plus.google.com/#{uid}", picture: image, gender: gender, - birthday: Date.backward(36400).strftime("%Y-%m-%d"), - local: "en", + birthday: Date.backward(36_400).strftime('%Y-%m-%d'), + local: 'en', hd: "#{Company.name.downcase}.com" - }, + } }, id_info: { - "iss" => "accounts.google.com", - "at_hash" => Crypto.md5, - "email_verified" => "true", - "sub" => Number.number(28).to_s, - "azp" => "APP_ID", - "email" => auth.email, - "aud" => "APP_ID", - "iat" => Number.number(10), - "exp" => Time.forward.to_i.to_s, - "openid_id" => "https://www.google.com/accounts/o8/id?id=#{uid}" + 'iss' => 'accounts.google.com', + 'at_hash' => Crypto.md5, + 'email_verified' => 'true', + 'sub' => Number.number(28).to_s, + 'azp' => 'APP_ID', + 'email' => auth.email, + 'aud' => 'APP_ID', + 'iat' => Number.number(10), + 'exp' => Time.forward.to_i.to_s, + 'openid_id' => "https://www.google.com/accounts/o8/id?id=#{uid}" } } end @@ -66,7 +66,7 @@ def facebook(name: nil, email: nil, username: nil, uid: Number.number(7)) auth = Omniauth.new(name: name, email: email) username ||= "#{auth.first_name.downcase[0]}#{auth.last_name.downcase}" { - provider: "facebook", + provider: 'facebook', uid: uid, info: { email: auth.email, @@ -106,11 +106,11 @@ def facebook(name: nil, email: nil, username: nil, uid: Number.number(7)) def twitter(name: nil, nickname: nil, uid: Number.number(6)) auth = Omniauth.new(name: name) - nickname ||= auth.name.downcase.gsub(' ', '') + nickname ||= auth.name.downcase.delete(' ') location = city_state description = Lorem.sentence { - provider: "twitter", + provider: 'twitter', uid: uid, info: { nickname: nickname, @@ -128,7 +128,7 @@ def twitter(name: nil, nickname: nil, uid: Number.number(6)) secret: Crypto.md5 }, extra: { - access_token: "", + access_token: '', raw_info: { name: auth.name, listed_count: random_number_from_range(1..10), @@ -144,7 +144,7 @@ def twitter(name: nil, nickname: nil, uid: Number.number(6)) id: uid, profile_background_tile: random_boolean, profile_sidebar_fill_color: Color.hex_color, - followers_count: random_number_from_range(1..10000), + followers_count: random_number_from_range(1..10_000), default_profile_image: random_boolean, screen_name: '', following: random_boolean, @@ -153,14 +153,14 @@ def twitter(name: nil, nickname: nil, uid: Number.number(6)) favourites_count: random_number_from_range(1..10), profile_background_color: Color.hex_color, is_translator: random_boolean, - friends_count: random_number_from_range(1..10000), + friends_count: random_number_from_range(1..10_000), notifications: random_boolean, geo_enabled: random_boolean, profile_background_image_url: image, protected: random_boolean, description: description, profile_link_color: Color.hex_color, - created_at: Time.backward.strftime("%a %b %d %H:%M:%S %z %Y"), + created_at: Time.backward.strftime('%a %b %d %H:%M:%S %z %Y'), id_str: uid, profile_image_url_https: image, default_profile: random_boolean, @@ -188,53 +188,53 @@ def linkedin(name: nil, email: nil, uid: Number.number(6)) industry = Commerce.department url = "http://www.linkedin.com/in/#{first_name}#{last_name}" { - "provider" => "linkedin", - "uid" => uid, - "info" => { - "name" => auth.name, - "email" => auth.email, - "nickname" => auth.name, - "first_name" => auth.first_name, - "last_name" => auth.last_name, - "location" => location, - "description" => description, - "image" => image, - "phone" => PhoneNumber.phone_number, - "headline" => description, - "industry" => industry, - "urls" => { - "public_profile" => url + 'provider' => 'linkedin', + 'uid' => uid, + 'info' => { + 'name' => auth.name, + 'email' => auth.email, + 'nickname' => auth.name, + 'first_name' => auth.first_name, + 'last_name' => auth.last_name, + 'location' => location, + 'description' => description, + 'image' => image, + 'phone' => PhoneNumber.phone_number, + 'headline' => description, + 'industry' => industry, + 'urls' => { + 'public_profile' => url } }, - "credentials" => { - "token" => token, - "secret" => secret + 'credentials' => { + 'token' => token, + 'secret' => secret }, - "extra" => { - "access_token" => { - "token" => token, - "secret" => secret, - "consumer" => nil, - "params" => { + 'extra' => { + 'access_token' => { + 'token' => token, + 'secret' => secret, + 'consumer' => nil, + 'params' => { oauth_token: token, oauth_token_secret: secret, oauth_expires_in: Time.forward.to_i, - oauth_authorization_expires_in: Time.forward.to_i, + oauth_authorization_expires_in: Time.forward.to_i }, - "response" => nil + 'response' => nil }, - "raw_info" => { - "firstName" => auth.first_name, - "headline" => description, - "id" => uid, - "industry" => industry, - "lastName" => auth.last_name, - "location" => { - "country" => { "code" => Address.country_code.downcase }, - "name" => city_state.split(', ').first, + 'raw_info' => { + 'firstName' => auth.first_name, + 'headline' => description, + 'id' => uid, + 'industry' => industry, + 'lastName' => auth.last_name, + 'location' => { + 'country' => { 'code' => Address.country_code.downcase }, + 'name' => city_state.split(', ').first }, - "pictureUrl" => image, - "publicProfileUrl" => url + 'pictureUrl' => image, + 'publicProfileUrl' => url } } } @@ -242,18 +242,18 @@ def linkedin(name: nil, email: nil, uid: Number.number(6)) def github(name: nil, email: nil, uid: Number.number(8)) auth = Omniauth.new(name: name, email: email) - login = auth.name.downcase.gsub(' ','-') + login = auth.name.downcase.tr(' ', '-') html_url = "https://github.com/#{login}" api_url = "https://api.github.com/users/#{login}" { - provider: "github", + provider: 'github', uid: uid, info: { nickname: login, email: auth.email, name: auth.name, image: image, - urls:{ + urls: { GitHub: html_url } }, @@ -266,7 +266,7 @@ def github(name: nil, email: nil, uid: Number.number(8)) login: login, id: uid, avatar_url: image, - gravatar_id: "", + gravatar_id: '', url: api_url, html_url: html_url, followers_url: "#{api_url}/followers", @@ -278,7 +278,7 @@ def github(name: nil, email: nil, uid: Number.number(8)) repos_url: "#{api_url}/repos", events_url: "#{api_url}/events{/privacy}", received_events_url: "#{api_url}/received_events", - type: "User", + type: 'User', site_admin: random_boolean, name: auth.name, company: nil, @@ -291,7 +291,7 @@ def github(name: nil, email: nil, uid: Number.number(8)) public_gists: random_number_from_range(1..1000), followers: random_number_from_range(1..1000), following: random_number_from_range(1..1000), - created_at: Time.backward(36400).iso8601, + created_at: Time.backward(36_400).iso8601, updated_at: Time.backward(2).iso8601 } } @@ -300,29 +300,29 @@ def github(name: nil, email: nil, uid: Number.number(8)) private - def gender - shuffle(["male", "female"]).pop - end + def gender + shuffle(%w[male female]).pop + end - def timezone - shuffle((-12..12).to_a).pop - end + def timezone + shuffle((-12..12).to_a).pop + end - def image - Placeholdit.image - end + def image + Placeholdit.image + end - def city_state - "#{Address.city}, #{Address.state}" - end + def city_state + "#{Address.city}, #{Address.state}" + end - def random_number_from_range(range) - shuffle(range.to_a).pop - end + def random_number_from_range(range) + shuffle(range.to_a).pop + end - def random_boolean - shuffle([true, false]).pop - end + def random_boolean + shuffle([true, false]).pop + end end end end diff --git a/lib/faker/phone_number.rb b/lib/faker/phone_number.rb index 689f39dbdf..ddedfe56de 100644 --- a/lib/faker/phone_number.rb +++ b/lib/faker/phone_number.rb @@ -11,34 +11,28 @@ def cell_phone # US and Canada only def area_code - begin - fetch('phone_number.area_code') - rescue I18n::MissingTranslationData - nil - end + fetch('phone_number.area_code') + rescue I18n::MissingTranslationData + nil end # US and Canada only def exchange_code - begin - fetch('phone_number.exchange_code') - rescue I18n::MissingTranslationData - nil - end + fetch('phone_number.exchange_code') + rescue I18n::MissingTranslationData + nil end # US and Canada only # Can be used for both extensions and last four digits of phone number. # Since extensions can be of variable length, this method taks a length parameter def subscriber_number(length = 4) - begin - rand.to_s[2..(1 + length)] - rescue I18n::MissingTranslationData - nil - end + rand.to_s[2..(1 + length)] + rescue I18n::MissingTranslationData + nil end - alias_method :extension, :subscriber_number + alias extension subscriber_number end end end diff --git a/lib/faker/placeholdit.rb b/lib/faker/placeholdit.rb index b0c6eb2474..fdaa25beea 100644 --- a/lib/faker/placeholdit.rb +++ b/lib/faker/placeholdit.rb @@ -1,10 +1,10 @@ module Faker class Placeholdit < Base class << self - SUPPORTED_FORMATS = %w(png jpg gif jpeg) + SUPPORTED_FORMATS = %w[png jpg gif jpeg].freeze def image(size = '300x300', format = 'png', background_color = nil, text_color = nil, text = nil) - raise ArgumentError, "Size should be specified in format 300x300" unless size.match(/^[0-9]+x[0-9]+$/) + raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/ raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format) raise ArgumentError, "background_color must be a hex value without '#'" unless background_color.nil? || background_color.match(/((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/) raise ArgumentError, "text_color must be a hex value without '#'" unless text_color.nil? || text_color.match(/((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/) diff --git a/lib/faker/rick_and_morty.rb b/lib/faker/rick_and_morty.rb index e8512b9eaa..7cbea59481 100644 --- a/lib/faker/rick_and_morty.rb +++ b/lib/faker/rick_and_morty.rb @@ -14,4 +14,4 @@ def quote end end end -end \ No newline at end of file +end diff --git a/lib/faker/science.rb b/lib/faker/science.rb index 7c3bc65d2e..744c01c430 100644 --- a/lib/faker/science.rb +++ b/lib/faker/science.rb @@ -1,7 +1,6 @@ module Faker class Science < Base class << self - def element fetch('science.element') end @@ -9,7 +8,6 @@ def element def scientist fetch('science.scientist') end - end end end diff --git a/lib/faker/seinfeld.rb b/lib/faker/seinfeld.rb index 137c79a392..775fd62a8e 100644 --- a/lib/faker/seinfeld.rb +++ b/lib/faker/seinfeld.rb @@ -8,6 +8,6 @@ def character def quote fetch('seinfeld.quote') end - end + end end end diff --git a/lib/faker/shakespeare.rb b/lib/faker/shakespeare.rb index 993fac39f9..8bd43a7049 100644 --- a/lib/faker/shakespeare.rb +++ b/lib/faker/shakespeare.rb @@ -1,7 +1,6 @@ module Faker class Shakespeare < Base class << self - def hamlet_quote sample(hamlet) end @@ -26,7 +25,6 @@ def as_you_like_it fetch('shakespeare.as_you_like_it') end - def king_richard_iii fetch('shakespeare.king_richard_iii') end @@ -34,7 +32,6 @@ def king_richard_iii def romeo_and_juliet fetch('shakespeare.romeo_and_juliet') end - end end end diff --git a/lib/faker/simpsons.rb b/lib/faker/simpsons.rb index 5641e43e46..5fcdaf1197 100644 --- a/lib/faker/simpsons.rb +++ b/lib/faker/simpsons.rb @@ -1,10 +1,7 @@ -#encoding: utf-8 -#frozen_string_literal: true +# frozen_string_literal: true module Faker - class Simpsons < Base - def self.character fetch('simpsons.characters') end @@ -16,7 +13,5 @@ def self.location def self.quote fetch('simpsons.quotes') end - - end #class Simpsons - -end #module Faker + end +end diff --git a/lib/faker/slack_emoji.rb b/lib/faker/slack_emoji.rb index e6c5285b2d..52d55a76b7 100644 --- a/lib/faker/slack_emoji.rb +++ b/lib/faker/slack_emoji.rb @@ -1,7 +1,6 @@ module Faker class SlackEmoji < Base class << self - def people fetch('slack_emoji.people') end @@ -37,7 +36,6 @@ def custom def emoji parse('slack_emoji.emoji') end - end end end diff --git a/lib/faker/star_trek.rb b/lib/faker/star_trek.rb index 6cc36343d1..0745651a94 100644 --- a/lib/faker/star_trek.rb +++ b/lib/faker/star_trek.rb @@ -12,10 +12,10 @@ def location def specie fetch('star_trek.specie') end - + def villain fetch('star_trek.villain') end end end -end \ No newline at end of file +end diff --git a/lib/faker/star_wars.rb b/lib/faker/star_wars.rb index 6773129d96..f2db5a7d4e 100644 --- a/lib/faker/star_wars.rb +++ b/lib/faker/star_wars.rb @@ -36,9 +36,9 @@ def vehicle def wookiee_sentence sentence = sample(wookiee_words).capitalize - rand(0..10).times { sentence += " " + sample(wookiee_words)} + rand(0..10).times { sentence += ' ' + sample(wookiee_words) } - sentence + sample(['.','?','!']) + sentence + sample(['.', '?', '!']) end def call_numbers @@ -94,9 +94,8 @@ def wookiee_words fetch_all('star_wars.wookiee_words') end - alias_method :wookie_sentence, :wookiee_sentence - alias_method :wookie_words, :wookiee_words - + alias wookie_sentence wookiee_sentence + alias wookie_words wookiee_words end end end diff --git a/lib/faker/string.rb b/lib/faker/string.rb index 1f34046e4c..f394daf7f4 100644 --- a/lib/faker/string.rb +++ b/lib/faker/string.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + module Faker class String < Base class << self @@ -6,7 +7,7 @@ def random(length = 32) utf8string select_a length end - private + private def select_a(length) if length.class.included_modules.include? Enumerable @@ -24,20 +25,20 @@ def utf8string(length) end def space_or_utf8_char(ratio) - sample [ 32.chr(Encoding::UTF_8), [utf8character]* ratio ].flatten + sample [32.chr(Encoding::UTF_8), [utf8character] * ratio].flatten end def char_space_ratio - sample [ 2, [3]*5, [5]*17, [7]*11, 11, 191, ].flatten + sample [2, [3] * 5, [5] * 17, [7] * 11, 11, 191].flatten end def utf8character sample([ - rand(59)+ 32, # latin alphabet - rand(128), # 7-bit ASCII - rand(0xd800), # utf-8 codepoints below utf-16 surrogate halves - rand(0x102000)+ 0xe000 # utf-8 codepoints above utf-16 surrogate halves - ]).chr(Encoding::UTF_8) + rand(32..90), # latin alphabet + rand(128), # 7-bit ASCII + rand(0xd800), # utf-8 codepoints below utf-16 surrogate halves + rand(57_344..1_114_111) # utf-8 codepoints above utf-16 surrogate halves + ]).chr(Encoding::UTF_8) end end end diff --git a/lib/faker/stripe.rb b/lib/faker/stripe.rb index 29580a792b..8ddcc3d3ea 100644 --- a/lib/faker/stripe.rb +++ b/lib/faker/stripe.rb @@ -9,11 +9,11 @@ def valid_card(card_type = nil) else unless valid_cards.include?(card_type.to_sym) raise ArgumentError, - "Valid credit cards argument can be left blank or include #{valid_cards.join(', ')}" + "Valid credit cards argument can be left blank or include #{valid_cards.join(', ')}" end end - return fetch('stripe.valid_cards.' + card_type) + fetch('stripe.valid_cards.' + card_type) end def invalid_card(card_error = nil) @@ -24,15 +24,15 @@ def invalid_card(card_error = nil) else unless invalid_cards.include?(card_error.to_sym) raise ArgumentError, - "Invalid credit cards argument can be left blank or include #{invalid_cards.join(', ')}" + "Invalid credit cards argument can be left blank or include #{invalid_cards.join(', ')}" end end - return fetch('stripe.invalid_cards.' + card_error) + fetch('stripe.invalid_cards.' + card_error) end def month - "%02d" % rand_in_range(1, 12) + format('%02d', rand_in_range(1, 12)) end def year @@ -41,9 +41,8 @@ def year end def ccv(card_type = nil) - (card_type.to_s == "amex" ? rand_in_range(1000, 9999) : rand_in_range(100, 999)).to_s + (card_type.to_s == 'amex' ? rand_in_range(1000, 9999) : rand_in_range(100, 999)).to_s end - end end end diff --git a/lib/faker/team.rb b/lib/faker/team.rb index a24b030428..df3ff74ed9 100644 --- a/lib/faker/team.rb +++ b/lib/faker/team.rb @@ -19,6 +19,5 @@ def mascot fetch('team.mascot') end end - end end diff --git a/lib/faker/time.rb b/lib/faker/time.rb index cf722a3728..658ec1ca19 100755 --- a/lib/faker/time.rb +++ b/lib/faker/time.rb @@ -1,14 +1,14 @@ module Faker class Time < Faker::Date TIME_RANGES = { - :all => (0..23), - :day => (9..17), - :night => (18..23), - :morning => (6..11), - :afternoon => (12..17), - :evening => (17..21), - :midnight => (0..4) - } + all: (0..23), + day: (9..17), + night: (18..23), + morning: (6..11), + afternoon: (12..17), + evening: (17..21), + midnight: (0..4) + }.freeze class << self def between(from, to, period = :all, format = nil) @@ -31,11 +31,11 @@ def date_with_random_time(date, period) end def time_with_format(time, format) - format.nil? ? time : I18n.l( DateTime.parse(time.to_s), :format => format ) + format.nil? ? time : I18n.l(DateTime.parse(time.to_s), format: format) end def hours(period) - raise ArgumentError, 'invalid period' unless TIME_RANGES.has_key? period + raise ArgumentError, 'invalid period' unless TIME_RANGES.key? period sample(TIME_RANGES[period].to_a) end diff --git a/lib/faker/twin_peaks.rb b/lib/faker/twin_peaks.rb index 4e46bae447..e420ef8a45 100644 --- a/lib/faker/twin_peaks.rb +++ b/lib/faker/twin_peaks.rb @@ -4,11 +4,11 @@ class << self def character fetch('twin_peaks.characters') end - + def location fetch('twin_peaks.locations') end - + def quote fetch('twin_peaks.quotes') end diff --git a/lib/faker/types.rb b/lib/faker/types.rb index 92dba29717..6d2d1bf9ed 100644 --- a/lib/faker/types.rb +++ b/lib/faker/types.rb @@ -1,47 +1,47 @@ module Faker class Types < Base CHARACTERS = ('0'..'9').to_a + ('a'..'z').to_a - SIMPLE_TYPES = [:string, :fixnum] - COMPLEX_TYPES = [:hash, :array] + SIMPLE_TYPES = %i[string fixnum].freeze + COMPLEX_TYPES = %i[hash array].freeze class << self - def string(words=1) + def string(words = 1) resolved_num = resolve(words) - word_list = ( + word_list = translate('faker.lorem.words') - ) - word_list = word_list * ((resolved_num / word_list.length) + 1) - shuffle(word_list)[0, resolved_num].join(" ") + + word_list *= ((resolved_num / word_list.length) + 1) + shuffle(word_list)[0, resolved_num].join(' ') end def character sample(CHARACTERS) end - def integer(from=0, to=100) + def integer(from = 0, to = 100) rand(from..to).to_i end - def hash(key_count=1) - Hash.new.tap do |hsh| + def hash(key_count = 1) + {}.tap do |hsh| Lorem.words(key_count * 2).uniq.first(key_count).each do |s| - hsh.merge!({s.to_sym => self.random_type}) + hsh.merge!(s.to_sym => random_type) end end end - def complex_hash(key_count=1) - Hash.new.tap do |hsh| + def complex_hash(key_count = 1) + {}.tap do |hsh| Lorem.words(key_count * 2).uniq.first(key_count).each do |s| - hsh.merge!({s.to_sym => self.random_complex_type}) + hsh.merge!(s.to_sym => random_complex_type) end end end - def array(len=1) - Array.new.tap do |ar| + def array(len = 1) + [].tap do |ar| len.times do - ar.push self.random_type + ar.push random_type end end end @@ -50,11 +50,11 @@ def random_type type_to_use = SIMPLE_TYPES[rand(0..SIMPLE_TYPES.length - 1)] case type_to_use when :string - self.string + string when :fixnum - self.integer + integer else - self.integer + integer end end @@ -63,15 +63,15 @@ def random_complex_type type_to_use = types[rand(0..types.length - 1)] case type_to_use when :string - self.string + string when :fixnum - self.integer + integer when :hash - self.hash + hash when :array - self.array + array else - self.integer + integer end end diff --git a/lib/faker/university.rb b/lib/faker/university.rb index c8aa07ce22..9941a9de70 100644 --- a/lib/faker/university.rb +++ b/lib/faker/university.rb @@ -16,12 +16,12 @@ def suffix end def greek_organization - 3.times.map { |_| sample(greek_alphabet) }.join + Array.new(3) { |_| sample(greek_alphabet) }.join end def greek_alphabet - ['Α', 'B', 'Γ', 'Δ', 'E', 'Z', 'H', 'Θ', 'I', 'K', 'Λ', 'M', 'N', 'Ξ', - 'O', 'Π', 'P', 'Σ', 'T', 'Y', 'Φ', 'X', 'Ψ', 'Ω'] + %w[Α B Γ Δ E Z H Θ I K Λ M N Ξ + O Π P Σ T Y Φ X Ψ Ω] end end end diff --git a/lib/faker/vehicle.rb b/lib/faker/vehicle.rb index 3b0cf13b4d..acbb1a01cd 100644 --- a/lib/faker/vehicle.rb +++ b/lib/faker/vehicle.rb @@ -2,17 +2,17 @@ module Faker class Vehicle < Base flexible :vehicle - VIN_CHARS = '0123456789.ABCDEFGH..JKLMN.P.R..STUVWXYZ' - VIN_MAP = '0123456789X' - VIN_WEIGHTS = '8765432X098765432' + VIN_CHARS = '0123456789.ABCDEFGH..JKLMN.P.R..STUVWXYZ'.freeze + VIN_MAP = '0123456789X'.freeze + VIN_WEIGHTS = '8765432X098765432'.freeze class << self - #ISO 3779 + # ISO 3779 def vin _, wmi, wmi_ext = sample(fetch_all('vehicle.manufacture')) - c = VIN_CHARS.split('').reject{ |n| n == '.'} - vehicle_identification_number = wmi.split('').concat( Array.new(14) { sample(c) } ) + c = VIN_CHARS.split('').reject { |n| n == '.' } + vehicle_identification_number = wmi.split('').concat(Array.new(14) { sample(c) }) (12..14).to_a.each_with_index { |n, i| vehicle_identification_number[n] = wmi_ext[i] } unless wmi_ext.nil? vehicle_identification_number[10] = fetch('vehicle.year') vehicle_identification_number[8] = vin_checksum(vehicle_identification_number) @@ -24,16 +24,15 @@ def manufacture sample(fetch_all('vehicle.manufacture')).first end - private + private - def calculate_vin_weight(character, i) - (VIN_CHARS.index(character) % 10) * VIN_MAP.index(VIN_WEIGHTS[i]) + def calculate_vin_weight(character, idx) + (VIN_CHARS.index(character) % 10) * VIN_MAP.index(VIN_WEIGHTS[idx]) end def vin_checksum(vehicle_identification_number) VIN_MAP[vehicle_identification_number.each_with_index.map(&method(:calculate_vin_weight)).inject(:+) % 11] end - end end end diff --git a/lib/faker/verb.rb b/lib/faker/verb.rb index cfef042858..2ebbc6fbf6 100644 --- a/lib/faker/verb.rb +++ b/lib/faker/verb.rb @@ -16,7 +16,7 @@ def past_participle def simple_present fetch('verbs.simple_present') end - + def ing_form fetch('verbs.ing_form') end diff --git a/lib/faker/version.rb b/lib/faker/version.rb index db48b847f1..2a9ebe8f9a 100644 --- a/lib/faker/version.rb +++ b/lib/faker/version.rb @@ -1,3 +1,3 @@ module Faker #:nodoc: - VERSION = "1.8.7" + VERSION = '1.8.7'.freeze end diff --git a/lib/helpers/char.rb b/lib/helpers/char.rb index 9c010d7668..19efa9a972 100644 --- a/lib/helpers/char.rb +++ b/lib/helpers/char.rb @@ -1,4 +1,4 @@ -# coding: utf-8 + module Faker module Char def self.prepare(string) @@ -10,16 +10,16 @@ def self.prepare(string) def self.fix_umlauts(string) string.gsub(/[äöüß]/i) do |match| case match.downcase - when "ä" 'ae' - when "ö" 'oe' - when "ü" 'ue' - when "ß" 'ss' + when 'ä' then 'ae' + when 'ö' then 'oe' + when 'ü' then 'ue' + when 'ß' then 'ss' end end end def self.romanize_cyrillic(string) - if Faker::Config.locale == "uk" + if Faker::Config.locale == 'uk' # Based on conventions abopted by BGN/PCGN for Ukrainian uk_chars = { 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'ґ' => 'g', 'д' => 'd', @@ -39,22 +39,22 @@ def self.romanize_cyrillic(string) return string.gsub(/[а-яА-ЯіїєґІЇЄҐ]/, uk_chars) end - if Faker::Config.locale == "ru" + if Faker::Config.locale == 'ru' # Based on conventions abopted by BGN/PCGN for Russian ru_chars = { - 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'д' => 'd', 'е' => 'e', - 'ё' => 'ye', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', - 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', - 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'kh', 'ц' => 'ts', - 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ы' => 'у', 'э' => 'e', 'ю' => 'yu', - 'я' => 'ya', - 'А' => 'a', 'Б' => 'b', 'В' => 'v', 'Г' => 'h', 'Д' => 'd', 'Е' => 'e', - 'Ё' => 'ye', 'Ж' => 'zh', 'З' => 'z', 'И' => 'i', 'Й' => 'y', 'К' => 'k', - 'Л' => 'l', 'М' => 'm', 'Н' => 'n', 'О' => 'o', 'П' => 'p', 'Р' => 'r', - 'С' => 's', 'Т' => 't', 'У' => 'u', 'Ф' => 'f', 'Х' => 'kh', 'Ц' => 'ts', - 'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'shch', 'Ы' => 'у', 'Э' => 'e', 'Ю' => 'yu', - 'Я' => 'ya', - 'ь' => '', 'ъ' => '' # Ignore symbols, because its standard presentation is not allowed in URLs + 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'д' => 'd', 'е' => 'e', + 'ё' => 'ye', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', + 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', + 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'kh', 'ц' => 'ts', + 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ы' => 'у', 'э' => 'e', 'ю' => 'yu', + 'я' => 'ya', + 'А' => 'a', 'Б' => 'b', 'В' => 'v', 'Г' => 'h', 'Д' => 'd', 'Е' => 'e', + 'Ё' => 'ye', 'Ж' => 'zh', 'З' => 'z', 'И' => 'i', 'Й' => 'y', 'К' => 'k', + 'Л' => 'l', 'М' => 'm', 'Н' => 'n', 'О' => 'o', 'П' => 'p', 'Р' => 'r', + 'С' => 's', 'Т' => 't', 'У' => 'u', 'Ф' => 'f', 'Х' => 'kh', 'Ц' => 'ts', + 'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'shch', 'Ы' => 'у', 'Э' => 'e', 'Ю' => 'yu', + 'Я' => 'ya', + 'ь' => '', 'ъ' => '' # Ignore symbols, because its standard presentation is not allowed in URLs } return string.gsub(/[а-яА-Я]/, ru_chars) end diff --git a/lib/helpers/unique_generator.rb b/lib/helpers/unique_generator.rb index cec47be4fc..35ea0f2772 100644 --- a/lib/helpers/unique_generator.rb +++ b/lib/helpers/unique_generator.rb @@ -6,6 +6,7 @@ def initialize(generator, max_retries) @previous_results = Hash.new { |hash, key| hash[key] = Set.new } end + # rubocop:disable Style/MethodMissing def method_missing(name, *arguments) @max_retries.times do result = @generator.public_send(name, *arguments) @@ -18,6 +19,11 @@ def method_missing(name, *arguments) raise RetryLimitExceeded end + # rubocop:enable Style/MethodMissing + + def respond_to_missing?(method_name, include_private = false) + method_name.to_s.start_with?('faker_') || super + end RetryLimitExceeded = Class.new(StandardError) diff --git a/script/destroy b/script/destroy index 5fa7e10e71..97d99e9921 100755 --- a/script/destroy +++ b/script/destroy @@ -10,5 +10,5 @@ end require 'rubigen/scripts/destroy' ARGV.shift if ['--help', '-h'].include?(ARGV[0]) -RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Base.use_component_sources! %i[rubygems newgem newgem_theme test_unit] RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/script/generate b/script/generate index 230a186856..b4ddfdf4ae 100755 --- a/script/generate +++ b/script/generate @@ -10,5 +10,5 @@ end require 'rubigen/scripts/generate' ARGV.shift if ['--help', '-h'].include?(ARGV[0]) -RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Base.use_component_sources! %i[rubygems newgem newgem_theme test_unit] RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/script/txt2html b/script/txt2html index 9da3e23bf6..c04abe574e 100755 --- a/script/txt2html +++ b/script/txt2html @@ -19,33 +19,36 @@ download = 'http://rubyforge.org/projects/faker' class Fixnum def ordinal # teens - return 'th' if (10..19).include?(self % 100) + return 'th' if (10..19).cover?(self % 100) # others case self % 10 - when 1: return 'st' - when 2: return 'nd' - when 3: return 'rd' - else return 'th' + when 1 + return 'st' + when 2 + return 'nd' + when 3 + return 'rd' end + 'th' end end class Time def pretty - return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" + "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" end end def convert_syntax(syntax, source) - return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^
|$!,'') + Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r{^
|$}, '') end if ARGV.length >= 1 src, template = ARGV template ||= File.join(File.dirname(__FILE__), '/../website/template.rhtml') - + else - puts("Usage: #{File.split($0).last} source.txt [template.rhtml] > output.html") + puts("Usage: #{File.split($PROGRAM_NAME).last} source.txt [template.rhtml] > output.html") exit! end @@ -57,15 +60,17 @@ File.open(src) do |fsrc| title_text = fsrc.readline body_text = fsrc.read syntax_items = [] - body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)\1>!m){ + body_text.gsub!(%r{<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)\1>}m) do ident = syntax_items.length - element, syntax, source = $1, $2, $3 + element = Regexp.last_match(1) + syntax = Regexp.last_match(2) + source = Regexp.last_match(3) syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}#{element}>" "syntax-temp-#{ident}" - } - title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip + end + title = RedCloth.new(title_text).to_html.gsub(/<.*?>/, '').strip body = RedCloth.new(body_text).to_html - body.gsub!(%r!(?:
)?syntax-temp-(\d+)(?:
)?!){ syntax_items[$1.to_i] }
+ body.gsub!(%r{(?:)?syntax-temp-(\d+)(?:
)?}) { syntax_items[Regexp.last_match(1).to_i] }
end
stat = File.stat(src)
created = stat.ctime
diff --git a/tasks/test.rake b/tasks/test.rake
index 217217f699..eda89c3211 100644
--- a/tasks/test.rake
+++ b/tasks/test.rake
@@ -1,11 +1,11 @@
require 'rake/testtask'
Rake::TestTask.new do |t|
- t.libs << "test"
- t.libs << "."
+ t.libs << 'test'
+ t.libs << '.'
t.test_files = FileList['test/test*.rb']
t.verbose = true
t.warning = true
end
-task :default => :test
+task default: :test
diff --git a/tasks/website.rake b/tasks/website.rake
index 5b0960b8d2..667e078b3c 100644
--- a/tasks/website.rake
+++ b/tasks/website.rake
@@ -1,16 +1,16 @@
desc 'Generate website files'
task :website_generate do
(Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt|
- sh %{ ./script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} }
+ sh %( ./script/txt2html #{txt} > #{txt.gsub(/txt$/, 'html')} )
end
end
desc 'Upload website files to rubyforge'
task :website_upload do
- remote_dir = "/var/www/gforge-projects/faker/"
+ remote_dir = '/var/www/gforge-projects/faker/'
local_dir = 'website'
- sh %{rsync -acCv #{local_dir}/ #{ENV['USER']}@rubyforge.org:#{remote_dir}}
+ sh %(rsync -acCv #{local_dir}/ #{ENV['USER']}@rubyforge.org:#{remote_dir})
end
desc 'Generate and upload website files'
-task :website => [:website_generate, :website_upload, :publish_docs]
+task website: %i[website_generate website_upload publish_docs]
diff --git a/test/test_array_sample_method_compat.rb b/test/test_array_sample_method_compat.rb
index e0dd74ec85..c1cf1e69e1 100644
--- a/test/test_array_sample_method_compat.rb
+++ b/test/test_array_sample_method_compat.rb
@@ -5,7 +5,6 @@
# behaves as the built-in Array#sample method from Ruby 1.9 or greater.
# Under Ruby 1.9, they simply use the built-in Array#sample method
class TestArraySampleMethodCompatibility < Test::Unit::TestCase
-
def test_returns_nil_or_empty_array_with_empty_source
source = []
@@ -17,19 +16,19 @@ def test_returns_nil_or_empty_array_with_empty_source
end
def test_returns_one_array_elem_without_param
- source = ['foo', 'bar']
+ source = %w[foo bar]
result = source.sample
assert source.include? result
end
def test_returns_empty_array_with_param_zero
- source = ['foo', 'bar']
+ source = %w[foo bar]
result = source.sample(0)
assert_equal result, []
end
def test_returns_an_array_with_integer_param
- source = ['foo', 'bar', 'baz']
+ source = %w[foo bar baz]
result = source.sample(2)
assert result.is_a? Array
assert result.length == 2
@@ -37,18 +36,18 @@ def test_returns_an_array_with_integer_param
end
def test_returns_source_array_with_integer_param_equal_or_bigger_than_source_length
- source = ['foo','bar']
+ source = %w[foo bar]
result = source.sample(2)
assert result.is_a? Array
- assert((source.sort <=> result.sort) == 0)
+ assert((source.sort <=> result.sort).zero?)
result = source.sample(3)
assert result.is_a? Array
- assert((source.sort <=> result.sort) == 0)
+ assert((source.sort <=> result.sort).zero?)
end
- def test_raises_Argument_Error_with_negative_param
- source = ['foo','bar']
+ def test_raises_argument_error_with_negative_param
+ source = %w[foo bar]
assert_raise ArgumentError do
source.sample(-1)
end
diff --git a/test/test_avatar.rb b/test/test_avatar.rb
index aa1bb0c32a..5e43043362 100644
--- a/test/test_avatar.rb
+++ b/test/test_avatar.rb
@@ -6,15 +6,15 @@ def setup
end
def test_avatar
- assert @tester.image.match(/https:\/\/robohash\.org\/(.+)\.png/)[1] != nil
+ assert !@tester.image.match(%r{https:\/\/robohash\.org\/(.+)\.png})[1].nil?
end
def test_avatar_with_param
- assert @tester.image('faker').match(/https:\/\/robohash\.org\/(.+)\.png/)[1] == 'faker'
+ assert @tester.image('faker').match(%r{https:\/\/robohash\.org\/(.+)\.png})[1] == 'faker'
end
def test_avatar_with_correct_size
- assert @tester.image('faker', '150x320').match(/https:\/\/robohash\.org\/faker\.png\?size=(.+)&.*/)[1] == '150x320'
+ assert @tester.image('faker', '150x320').match(%r{https:\/\/robohash\.org\/faker\.png\?size=(.+)&.*})[1] == '150x320'
end
def test_avatar_with_incorrect_size
@@ -24,7 +24,7 @@ def test_avatar_with_incorrect_size
end
def test_avatar_with_supported_format
- assert @tester.image('faker', '300x300', 'jpg').match(/https:\/\/robohash\.org\/faker\.jpg/)
+ assert @tester.image('faker', '300x300', 'jpg').match(%r{https:\/\/robohash\.org\/faker\.jpg})
end
def test_avatar_with_incorrect_format
@@ -34,10 +34,10 @@ def test_avatar_with_incorrect_format
end
def test_avatar_with_set
- assert @tester.image('faker', '300x300', 'jpg', 'set2').match(/https:\/\/robohash\.org\/faker\.jpg.*set=set2/)
+ assert @tester.image('faker', '300x300', 'jpg', 'set2').match(%r{https:\/\/robohash\.org\/faker\.jpg.*set=set2})
end
def test_avatar_with_bgset
- assert @tester.image('faker', '300x300', 'jpg', 'set1', 'bg1').match(/https:\/\/robohash\.org\/faker\.jpg.*bgset=bg1/)
+ assert @tester.image('faker', '300x300', 'jpg', 'set1', 'bg1').match(%r{https:\/\/robohash\.org\/faker\.jpg.*bgset=bg1})
end
end
diff --git a/test/test_ca_cat_locale.rb b/test/test_ca_cat_locale.rb
index 1c26f088df..1265a10f5f 100644
--- a/test/test_ca_cat_locale.rb
+++ b/test/test_ca_cat_locale.rb
@@ -24,12 +24,12 @@ def test_ca_methods
end
def test_phone_numbers_start_with_9
- mobile = Faker::PhoneNumber.phone_number.gsub(/\D/,'')
+ mobile = Faker::PhoneNumber.phone_number.gsub(/\D/, '')
assert_equal '9', mobile[0]
end
def test_cell_numbers_start_with_6
- mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'')
+ mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '')
assert_equal '6', mobile[0]
end
end
diff --git a/test/test_country_code.rb b/test/test_country_code.rb
index 7cf7e076bc..f378001fef 100644
--- a/test/test_country_code.rb
+++ b/test/test_country_code.rb
@@ -17,5 +17,4 @@ def test_country_code_expected_length
def test_country_code_long_expected_length
assert_equal(3, Faker::Address.country_code_long.length)
end
-
end
diff --git a/test/test_de_at_locale.rb b/test/test_de_at_locale.rb
index f3d8e92d4c..b22a8d09ea 100644
--- a/test/test_de_at_locale.rb
+++ b/test/test_de_at_locale.rb
@@ -1,5 +1,3 @@
-# encoding: utf-8
-
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
class TestDeAtLocale < Test::Unit::TestCase
diff --git a/test/test_de_locale.rb b/test/test_de_locale.rb
index 45f9b80b16..a6a168252e 100644
--- a/test/test_de_locale.rb
+++ b/test/test_de_locale.rb
@@ -35,12 +35,10 @@ def test_de_methods
assert Faker::Book.author.is_a? String
assert Faker::Book.publisher.is_a? String
-
-
assert Faker::Food.ingredient.is_a? String
assert Faker::Food.spice.is_a? String
assert Faker::Food.measurement.is_a? String
-
+
assert Faker::Music.instrument.is_a? String
assert Faker::Pokemon.name.is_a? String
@@ -57,7 +55,7 @@ def test_de_methods
end
def test_de_cell_phone_countrycode
- mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'')
+ mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '')
assert_equal '4', mobile[0]
assert_equal '9', mobile[1]
end
diff --git a/test/test_determinism.rb b/test/test_determinism.rb
index 0d2a7cf88d..f1ae3a66bf 100644
--- a/test/test_determinism.rb
+++ b/test/test_determinism.rb
@@ -1,11 +1,9 @@
-# frozen_string_literal: true
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
-
+# rubocop:disable Security/Eval,Style/EvalWithLocation
class TestDeterminism < Test::Unit::TestCase
-
def setup
- @all_methods= all_methods.freeze
- @first_run= []
+ @all_methods = all_methods.freeze
+ @first_run = []
end
def test_determinism
@@ -20,21 +18,19 @@ def test_determinism
end
end
-private
+ private
- def deterministic_random? first, method_name
- second= eval(method_name)
- (first== second) || raise(
+ def deterministic_random?(first, method_name)
+ second = eval(method_name)
+ (first == second) || raise(
"#{method_name} has an entropy leak; use \"Faker::Config.random.rand\" or \"Array#sample(random: Faker::Config.random)\". Method to lookup for: sample, shuffle, rand"
)
end
- def store_result method_name
- begin
- @first_run<< eval(method_name)
- rescue => exception
- raise %Q[#{method_name} raised "#{exception}"]
- end
+ def store_result(method_name)
+ @first_run << eval(method_name)
+ rescue StandardError => exception
+ raise %(#{method_name} raised "#{exception}")
end
def all_methods
@@ -45,7 +41,7 @@ def all_methods
def subclasses
Faker.constants.delete_if do |subclass|
- [:Base, :Char, :Config, :Date, :Internet, :Time, :VERSION].include?(subclass)
+ %i[Base Char Config Date Internet Time VERSION].include?(subclass)
end.sort
end
@@ -54,4 +50,5 @@ def subclass_methods(subclass)
"Faker::#{subclass}.#{method}"
end.sort
end
-end
\ No newline at end of file
+end
+# rubocop:enable Security/Eval,Style/EvalWithLocation
diff --git a/test/test_en_au_locale.rb b/test/test_en_au_locale.rb
index d878080a65..c363eb44c3 100644
--- a/test/test_en_au_locale.rb
+++ b/test/test_en_au_locale.rb
@@ -25,7 +25,7 @@ def test_en_au_default_country
end
def test_aussie_mobiles_start_with_04
- mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'')
+ mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '')
assert_equal '0', mobile[0]
assert_equal '4', mobile[1]
end
diff --git a/test/test_en_au_ocker_locale.rb b/test/test_en_au_ocker_locale.rb
index d6e2c57c98..fbd73724ff 100644
--- a/test/test_en_au_ocker_locale.rb
+++ b/test/test_en_au_ocker_locale.rb
@@ -18,7 +18,7 @@ def test_au_ocker_methods_with_en_au_ocker_locale
end
def test_aussie_mobiles_start_with_04
- mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'')
+ mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '')
assert_equal '0', mobile[0]
assert_equal '4', mobile[1]
end
diff --git a/test/test_en_ca_locale.rb b/test/test_en_ca_locale.rb
index 4d4a56d29f..809d8e6df8 100644
--- a/test/test_en_ca_locale.rb
+++ b/test/test_en_ca_locale.rb
@@ -44,5 +44,4 @@ def test_ca_postcode
expected = /[A-VX-Y][0-9][A-CEJ-NPR-TV-Z] ?[0-9][A-CEJ-NPR-TV-Z][0-9]/
assert_match(expected, Faker::Address.postcode)
end
-
end
diff --git a/test/test_en_gb_locale.rb b/test/test_en_gb_locale.rb
index 634a926c81..ee2555c2fd 100644
--- a/test/test_en_gb_locale.rb
+++ b/test/test_en_gb_locale.rb
@@ -18,12 +18,12 @@ def test_en_gb_methods
end
def test_gb_phone_starts_with_zero
- phone = Faker::PhoneNumber.phone_number.gsub(/\D/,'')
+ phone = Faker::PhoneNumber.phone_number.gsub(/\D/, '')
assert_equal '0', phone[0]
end
def test_gb_cell_phone_starts_with_zero
- mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'')
+ mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '')
assert_equal '0', mobile[0]
end
@@ -33,7 +33,7 @@ def test_gb_postcode_has_outcode_and_incode
end
def test_gb_postcode_incode_is_valid
- #The letters C I K M O V are not used in the second part of the Postcode.
+ # The letters C I K M O V are not used in the second part of the Postcode.
incode = Faker::Address.postcode.split(' ')[1]
assert_match(/\d[ABDEFGHJLNPQRSTUWXYZ]{2}/, incode)
end
@@ -41,8 +41,8 @@ def test_gb_postcode_incode_is_valid
def test_gb_postcode_outcode_is_valid
outcode = Faker::Address.postcode.split(' ')[0]
assert_includes(2..4, outcode.length)
- assert_match(/\w{1,2}\d{1,2}\w?/,outcode)
- assert_match(/^[A-PR-UWYZ][A-HK-Y0-9]/,outcode)
- assert_match(/\w{1,2}\d{1,2}|\w\d[ABCDEFGHJKPSTUW]|\w\w\d[ABEHMNPRVWXY]/,outcode)
+ assert_match(/\w{1,2}\d{1,2}\w?/, outcode)
+ assert_match(/^[A-PR-UWYZ][A-HK-Y0-9]/, outcode)
+ assert_match(/\w{1,2}\d{1,2}|\w\d[ABCDEFGHJKPSTUW]|\w\w\d[ABEHMNPRVWXY]/, outcode)
end
end
diff --git a/test/test_en_ind_locale.rb b/test/test_en_ind_locale.rb
index bff56c2921..ba8e421629 100644
--- a/test/test_en_ind_locale.rb
+++ b/test/test_en_ind_locale.rb
@@ -28,5 +28,4 @@ def test_en_ind_postal_code
def test_en_ind_city
assert_match(/(\w+\.? ?){2,3}/, Faker::Address.city)
end
-
end
diff --git a/test/test_en_locale.rb b/test/test_en_locale.rb
index ad07d0d6dd..56133b9889 100644
--- a/test/test_en_locale.rb
+++ b/test/test_en_locale.rb
@@ -10,8 +10,8 @@ def teardown
end
def test_us_states_only_include_states
- assert_equal I18n.translate("faker.address.state"), ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
- assert_equal I18n.translate("faker.address.state_abbr"), ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']
+ assert_equal I18n.translate('faker.address.state'), ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
+ assert_equal I18n.translate('faker.address.state_abbr'), %w[AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY]
end
def test_us_zip_codes
@@ -21,12 +21,12 @@ def test_us_zip_codes
def test_valid_id_number
id_num = Faker::IDNumber.valid
- assert Faker::IDNumber::INVALID_SSN.none? { |regex| id_num =~ regex }
+ assert(Faker::IDNumber::INVALID_SSN.none? { |regex| id_num =~ regex })
end
def test_invalid_id_number
id_num = Faker::IDNumber.invalid
- assert Faker::IDNumber::INVALID_SSN.any? { |regex| id_num =~ regex }
+ assert(Faker::IDNumber::INVALID_SSN.any? { |regex| id_num =~ regex })
end
def test_values_trimmed
@@ -34,8 +34,8 @@ def test_values_trimmed
check_hash(en_file)
end
- def check_hash(myHash)
- myHash.each { |key, value| check_value(value) unless (key == 'separator') }
+ def check_hash(hash)
+ hash.each { |key, value| check_value(value) unless key == 'separator' }
end
def check_value(value)
diff --git a/test/test_en_nz_locale.rb b/test/test_en_nz_locale.rb
index 4f7d52280f..8677f76276 100644
--- a/test/test_en_nz_locale.rb
+++ b/test/test_en_nz_locale.rb
@@ -17,7 +17,7 @@ def test_nz_methods_with_en_nz_locale
end
def test_nz_cellphones_start_with_02
- cellphone = Faker::PhoneNumber.cell_phone.gsub(/\D/,'')
+ cellphone = Faker::PhoneNumber.cell_phone.gsub(/\D/, '')
assert_equal '0', cellphone[0]
assert_equal '2', cellphone[1]
end
@@ -42,4 +42,4 @@ def test_team_names_with_en_nz_locale
def test_university_names_with_en_nz_locale
assert Faker::University.name.is_a? String
end
-end
\ No newline at end of file
+end
diff --git a/test/test_en_ug_locale.rb b/test/test_en_ug_locale.rb
index 892fd68a98..d0acaa770b 100644
--- a/test/test_en_ug_locale.rb
+++ b/test/test_en_ug_locale.rb
@@ -12,12 +12,11 @@ def teardown
def test_validity_of_phone_number
validation_regex = /^((0)|(256)|(\+256))((39)|(41))\d{7}$/
- assert_match(validation_regex, Faker::PhoneNumber.phone_number.gsub(' ',''))
+ assert_match(validation_regex, Faker::PhoneNumber.phone_number.delete(' '))
end
def test_validity_of_cell_phone
validation_regex = /^((0)|(256)|(\+256))((70)|(71)|(72)|(74)|(75)|(77)|(78)|(79))\d{7}$/
- assert_match(validation_regex, Faker::PhoneNumber.cell_phone.gsub(' ',''))
+ assert_match(validation_regex, Faker::PhoneNumber.cell_phone.delete(' '))
end
-
-end
\ No newline at end of file
+end
diff --git a/test/test_en_us_locale.rb b/test/test_en_us_locale.rb
index 1f5788e188..063d60e54f 100644
--- a/test/test_en_us_locale.rb
+++ b/test/test_en_us_locale.rb
@@ -40,7 +40,7 @@ def test_validity_of_phone_method_output
end
def test_us_invalid_state_raises_exception
- assert_raise I18n::MissingTranslationData do Faker::Address.zip_code('NA') end
+ assert_raise(I18n::MissingTranslationData) { Faker::Address.zip_code('NA') }
end
def test_us_zip_codes_match_state
@@ -72,11 +72,11 @@ def test_us_zip_codes_match_state
def test_valid_id_number
id_num = Faker::IDNumber.valid
- assert Faker::IDNumber::INVALID_SSN.none? { |regex| id_num =~ regex }
+ assert(Faker::IDNumber::INVALID_SSN.none? { |regex| id_num =~ regex })
end
def test_invalid_id_number
id_num = Faker::IDNumber.invalid
- assert Faker::IDNumber::INVALID_SSN.any? { |regex| id_num =~ regex }
+ assert(Faker::IDNumber::INVALID_SSN.any? { |regex| id_num =~ regex })
end
end
diff --git a/test/test_es_locale.rb b/test/test_es_locale.rb
index bd7ac0f386..c4b59e3048 100644
--- a/test/test_es_locale.rb
+++ b/test/test_es_locale.rb
@@ -1,8 +1,7 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
-LoadedEsYaml = ['en', 'es'].inject({}) do |h, locale|
+LoadedEsYaml = %w[en es].each_with_object({}) do |locale, h|
h[locale] = YAML.load_file(File.expand_path(File.dirname(__FILE__) + "/../lib/locales/#{locale}.yml"))[locale]['faker']
- h
end
class TestEsLocale < Test::Unit::TestCase
@@ -24,7 +23,7 @@ def test_configured_locale_translation
end
def test_locale_override_when_calling_translate
- assert_equal Faker::Base.translate('faker.separator', :locale => :en), LoadedEsYaml['en']['separator']
+ assert_equal Faker::Base.translate('faker.separator', locale: :en), LoadedEsYaml['en']['separator']
end
def test_translation_fallback
diff --git a/test/test_es_mx_locale.rb b/test/test_es_mx_locale.rb
index 9b322f491c..ba8cfcfc0e 100644
--- a/test/test_es_mx_locale.rb
+++ b/test/test_es_mx_locale.rb
@@ -43,5 +43,4 @@ def test_es_mx_methods
assert Faker::Name.prefix.is_a? String
assert Faker::Name.name.is_a? String
end
-
end
diff --git a/test/test_fa_locale.rb b/test/test_fa_locale.rb
index 4046c12ca4..4990be9789 100644
--- a/test/test_fa_locale.rb
+++ b/test/test_fa_locale.rb
@@ -14,5 +14,4 @@ def test_fa_methods
assert Faker::Name.last_name.is_a? String
assert Faker::Name.prefix.is_a? String
end
-
end
diff --git a/test/test_faker.rb b/test/test_faker.rb
index 5e81e31990..5e83e718c9 100644
--- a/test/test_faker.rb
+++ b/test/test_faker.rb
@@ -1,9 +1,7 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
class TestFaker < Test::Unit::TestCase
-
- def setup
- end
+ def setup; end
def test_numerify
100.times do
@@ -91,7 +89,7 @@ def test_rand_for_range
end
def test_unique
- unique_numbers = 8.times.map do
+ unique_numbers = Array.new(8) do
Faker::Base.unique.numerify('#')
end
diff --git a/test/test_faker_address.rb b/test/test_faker_address.rb
index 6823f233ca..9dd96205a7 100644
--- a/test/test_faker_address.rb
+++ b/test/test_faker_address.rb
@@ -1,7 +1,6 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
class TestFakerAddress < Test::Unit::TestCase
-
def setup
@tester = Faker::Address
end
@@ -31,7 +30,7 @@ def test_zip_code
end
def test_time_zone
- assert @tester.time_zone.match(/\w+\/\w+/)
+ assert @tester.time_zone.match(%r{\w+\/\w+})
end
def test_street_suffix
diff --git a/test/test_faker_ancient.rb b/test/test_faker_ancient.rb
index 84795e4ef0..b6dee236b6 100644
--- a/test/test_faker_ancient.rb
+++ b/test/test_faker_ancient.rb
@@ -20,5 +20,4 @@ def test_titan
def test_hero
assert @tester.hero.match(/\w+/)
end
-
end
diff --git a/test/test_faker_app.rb b/test/test_faker_app.rb
index f1d9d4c979..1142eb21a9 100644
--- a/test/test_faker_app.rb
+++ b/test/test_faker_app.rb
@@ -10,8 +10,8 @@ def test_name
end
def test_basic_semantic_version
- 10.times do |digits|
- test_sem_vers = @tester.semantic_version().split(".")
+ 10.times do |_digits|
+ test_sem_vers = @tester.semantic_version.split('.')
assert test_sem_vers[0].match(/[0-9]{1}/)
assert test_sem_vers[1].match(/[0-9]{1}/)
assert test_sem_vers[2].match(/[1-9]{1}/)
@@ -19,8 +19,8 @@ def test_basic_semantic_version
end
def test_major_semantic_version
- 10.times do |digits|
- test_sem_vers = @tester.semantic_version(major: (1000..9999)).split(".")
+ 10.times do |_digits|
+ test_sem_vers = @tester.semantic_version(major: (1000..9999)).split('.')
assert test_sem_vers[0].match(/[0-9]{4}/)
assert test_sem_vers[1].match(/[0-9]{1}/)
assert test_sem_vers[2].match(/[1-9]{1}/)
@@ -28,8 +28,8 @@ def test_major_semantic_version
end
def test_minor_semantic_version
- 10.times do |digits|
- test_sem_vers = @tester.semantic_version(minor: (1000..9999)).split(".")
+ 10.times do |_digits|
+ test_sem_vers = @tester.semantic_version(minor: (1000..9999)).split('.')
assert test_sem_vers[0].match(/[0-9]{1}/)
assert test_sem_vers[1].match(/[0-9]{4}/)
assert test_sem_vers[2].match(/[1-9]{1}/)
@@ -37,8 +37,8 @@ def test_minor_semantic_version
end
def test_patch_semantic_version
- 10.times do |digits|
- test_sem_vers = @tester.semantic_version(patch: (1000..9999)).split(".")
+ 10.times do |_digits|
+ test_sem_vers = @tester.semantic_version(patch: (1000..9999)).split('.')
assert test_sem_vers[0].match(/[0-9]{1}/)
assert test_sem_vers[1].match(/[0-9]{1}/)
assert test_sem_vers[2].match(/[0-9]{4}/)
@@ -46,8 +46,8 @@ def test_patch_semantic_version
end
def test_all_semantic_version
- 10.times do |digits|
- test_sem_vers = @tester.semantic_version(major: (1000..9999), minor: (1000..9999), patch: (1000..9999)).split(".")
+ 10.times do |_digits|
+ test_sem_vers = @tester.semantic_version(major: (1000..9999), minor: (1000..9999), patch: (1000..9999)).split('.')
assert test_sem_vers[0].match(/[0-9]{4}/)
assert test_sem_vers[1].match(/[0-9]{4}/)
assert test_sem_vers[2].match(/[0-9]{4}/)
@@ -57,5 +57,4 @@ def test_all_semantic_version
def test_specific_major_version
assert @tester.semantic_version(major: 42).match(/42\.[0-9]\.[0-9]/)
end
-
end
diff --git a/test/test_faker_aqua_teen_hunger_force.rb b/test/test_faker_aqua_teen_hunger_force.rb
index 0649472ccf..276fae5043 100644
--- a/test/test_faker_aqua_teen_hunger_force.rb
+++ b/test/test_faker_aqua_teen_hunger_force.rb
@@ -1,13 +1,11 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
- class TestFakerAquaTeenHungerForce < Test::Unit::TestCase
-
- def setup
- @tester = Faker::AquaTeenHungerForce
- end
-
- def test_character
- assert @tester.character.match(/\w/)
- end
-
- end
+class TestFakerAquaTeenHungerForce < Test::Unit::TestCase
+ def setup
+ @tester = Faker::AquaTeenHungerForce
+ end
+
+ def test_character
+ assert @tester.character.match(/\w/)
+ end
+end
diff --git a/test/test_faker_bank.rb b/test/test_faker_bank.rb
index ce07fb262c..d7fc3898a4 100644
--- a/test/test_faker_bank.rb
+++ b/test/test_faker_bank.rb
@@ -1,8 +1,7 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
class TestFakerBank < Test::Unit::TestCase
-
- IBAN_HEADER = '[A-Z]{2}[0-9]{2}'
+ IBAN_HEADER = '[A-Z]{2}[0-9]{2}'.freeze
def setup
@tester = Faker::Bank
@@ -498,8 +497,8 @@ def test_iban_xk
end
def test_iban_invalid
- assert_raise ArgumentError.new("Could not find iban details for bad") do
- @tester.iban("bad")
+ assert_raise ArgumentError.new('Could not find iban details for bad') do
+ @tester.iban('bad')
end
end
end
diff --git a/test/test_faker_beer.rb b/test/test_faker_beer.rb
index ab5f827dc7..854a684c55 100644
--- a/test/test_faker_beer.rb
+++ b/test/test_faker_beer.rb
@@ -1,7 +1,6 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
class TestFakerBeer < Test::Unit::TestCase
-
def setup
@tester = Faker::Beer
end
@@ -37,5 +36,4 @@ def test_alcohol
def test_blg
assert @tester.blg.match(/(\w+\.? ?){2,3}/)
end
-
-end
\ No newline at end of file
+end
diff --git a/test/test_faker_birthday_in_leap_year.rb b/test/test_faker_birthday_in_leap_year.rb
index 4dc91aaaf8..5e5e35c437 100644
--- a/test/test_faker_birthday_in_leap_year.rb
+++ b/test/test_faker_birthday_in_leap_year.rb
@@ -3,7 +3,7 @@
class TestFakerBirthdayInLeapYear < Test::Unit::TestCase
def setup
@tester = Faker::Date
- @today = Date.parse("2016-02-29")
+ @today = Date.parse('2016-02-29')
@min = 18
@max = 65
end
@@ -19,11 +19,11 @@ def test_birthday_in_leap_year
end
assert_raise ArgumentError do
- ::Date.new(@today.year - @min, @today.month, @today.day)
+ ::Date.new(@today.year - @min, @today.month, @today.day)
end
assert_raise ArgumentError do
- ::Date.new(@today.year - @max, @today.month, @today.day)
+ ::Date.new(@today.year - @max, @today.month, @today.day)
end
end
end
diff --git a/test/test_faker_bitcoin.rb b/test/test_faker_bitcoin.rb
index 4993c9f954..cd3a00ef17 100644
--- a/test/test_faker_bitcoin.rb
+++ b/test/test_faker_bitcoin.rb
@@ -1,7 +1,6 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
class TestFakerBitcoin < Test::Unit::TestCase
-
def test_address
assert Faker::Bitcoin.address.match(/^[13][1-9A-Za-z][^OIl]{20,40}/)
end
@@ -17,5 +16,4 @@ def test_testnet_address
assert_match(/\A[mn][1-9A-Za-z]{32,34}\Z/, Faker::Bitcoin.testnet_address)
assert_not_match(/[OIl]/, Faker::Bitcoin.testnet_address)
end
-
end
diff --git a/test/test_faker_book.rb b/test/test_faker_book.rb
index eb5ad8c5cb..b3c7619a3f 100644
--- a/test/test_faker_book.rb
+++ b/test/test_faker_book.rb
@@ -1,7 +1,6 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
class TestFakerBook < Test::Unit::TestCase
-
def setup
@tester = Faker::Book
end
diff --git a/test/test_faker_breaking_bad.rb b/test/test_faker_breaking_bad.rb
index c513d22079..cfd8087f98 100644
--- a/test/test_faker_breaking_bad.rb
+++ b/test/test_faker_breaking_bad.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
# frozen_string_literal: true
require File.expand_path(File.dirname(__FILE__) + '/test_helper')
diff --git a/test/test_faker_business.rb b/test/test_faker_business.rb
index 90aaea2fb0..7b587ba2ef 100644
--- a/test/test_faker_business.rb
+++ b/test/test_faker_business.rb
@@ -1,7 +1,6 @@
require File.dirname(__FILE__) + '/test_helper.rb'
class TestFakerBusiness < Test::Unit::TestCase
-
def setup
@tester = Faker::Business
@credit_card_number_list = I18n.translate('faker.business.credit_card_numbers')
@@ -30,5 +29,4 @@ def test_credit_card_type
assert @credit_card_types.include?(type1)
assert @credit_card_types.include?(type2)
end
-
end
diff --git a/test/test_faker_cat.rb b/test/test_faker_cat.rb
index abc61dcab2..a1053d0e9e 100644
--- a/test/test_faker_cat.rb
+++ b/test/test_faker_cat.rb
@@ -16,5 +16,4 @@ def test_breed
def test_registry
assert @tester.registry.match(/\w+\.?/)
end
-
end
diff --git a/test/test_faker_chuck_norris.rb b/test/test_faker_chuck_norris.rb
index 3953916cc6..cc090f6494 100644
--- a/test/test_faker_chuck_norris.rb
+++ b/test/test_faker_chuck_norris.rb
@@ -1,7 +1,6 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb')
class TestFakerChuckNorris < Test::Unit::TestCase
-
def setup
@tester = Faker::ChuckNorris
end
diff --git a/test/test_faker_city.rb b/test/test_faker_city.rb
index a27a2ff19a..4dc6411999 100644
--- a/test/test_faker_city.rb
+++ b/test/test_faker_city.rb
@@ -4,27 +4,29 @@ class TestFakerCity < Test::Unit::TestCase
def setup
@old_locales = I18n.config.available_locales
xx = {
- :faker => {
- :name => {:first_name => ['alice'], :last_name => ['smith']},
- :address => {:city_prefix => ['west'], :city_suffix => ['burg']}
+ faker: {
+ name: { first_name: ['alice'], last_name: ['smith'] },
+ address: { city_prefix: ['west'], city_suffix: ['burg'] }
}
}
I18n.backend.store_translations(:xx, xx)
- I18n.config.available_locales += [ :xx ]
+ I18n.config.available_locales += [:xx]
+ # rubocop:disable Lint/InterpolationCheck
xy = {
- :faker => {
- :address => {
- :city_prefix => ['big'],
- :city_root => ['rock'],
- :city_root_suffix => ['ing'],
- :city_suffix => ['town'],
- :city => ['#{city_prefix} #{city_root}#{city_root_suffix} #{city_suffix}']
+ faker: {
+ address: {
+ city_prefix: ['big'],
+ city_root: ['rock'],
+ city_root_suffix: ['ing'],
+ city_suffix: ['town'],
+ city: ['#{city_prefix} #{city_root}#{city_root_suffix} #{city_suffix}']
}
}
}
+ # rubocop:enable Lint/InterpolationCheck
I18n.backend.store_translations(:xy, xy)
- I18n.config.available_locales += [ :xy ]
+ I18n.config.available_locales += [:xy]
end
def teardown
@@ -34,7 +36,7 @@ def teardown
def test_default_city_formats
I18n.with_locale(:xx) do
100.times do
- cities = ["west alice", "west smith", "west aliceburg", "west smithburg", "aliceburg", "smithburg"]
+ cities = ['west alice', 'west smith', 'west aliceburg', 'west smithburg', 'aliceburg', 'smithburg']
city = Faker::Address.city
assert cities.include?(city), "Expected <#{cities.join(' / ')}>, but got #{city}"
end
@@ -48,5 +50,4 @@ def test_city_formats_are_flexible
assert cities.include?(city), "Expected <#{cities.join(' / ')}>, but got #{city}"
end
end
-
end
diff --git a/test/test_faker_coffee.rb b/test/test_faker_coffee.rb
index c983a6b3d8..a4976e3f17 100644
--- a/test/test_faker_coffee.rb
+++ b/test/test_faker_coffee.rb
@@ -16,7 +16,8 @@ def setup
def test_origin
assert origin = @tester.origin.match(/\A(?