Skip to content

Commit

Permalink
Rubocop + fixes (faker-ruby#924)
Browse files Browse the repository at this point in the history
* Rubocop + fixes

still has some errors

* Readd travis script
  • Loading branch information
stephengroat authored and vbrazo committed May 15, 2018
1 parent 17994e1 commit 7df1cd4
Show file tree
Hide file tree
Showing 182 changed files with 1,117 additions and 1,180 deletions.
20 changes: 20 additions & 0 deletions .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
9 changes: 1 addition & 8 deletions 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
18 changes: 17 additions & 1 deletion Gemfile.lock
Expand Up @@ -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
Expand All @@ -24,8 +39,9 @@ DEPENDENCIES
faker!
minitest
rake
rubocop
test-unit
timecop

BUNDLED WITH
1.16.0
1.16.1.pre1
7 changes: 5 additions & 2 deletions Rakefile
@@ -1,4 +1,4 @@
$:.unshift File.dirname(__FILE__)
$LOAD_PATH.unshift File.dirname(__FILE__)

Dir['tasks/**/*.rake'].each { |rake| load rake }

Expand All @@ -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]
25 changes: 15 additions & 10 deletions 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
20 changes: 10 additions & 10 deletions 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
Expand Down
1 change: 0 additions & 1 deletion lib/extensions/symbol.rb
Expand Up @@ -6,4 +6,3 @@ def downcase
end
end
end

61 changes: 31 additions & 30 deletions 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'
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -146,15 +143,15 @@ 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

# 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.
Expand All @@ -175,25 +172,29 @@ 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
rand(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)
Expand All @@ -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'
Expand Down
45 changes: 34 additions & 11 deletions lib/faker/address.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 7df1cd4

Please sign in to comment.