Compare commits

...

32 Commits

Author SHA1 Message Date
Aşkın Gedik c8875e3183 Merge branch 'master' of github.com:askn/faker 2022-04-04 21:44:02 +03:00
Aşkın Gedik 99afcf6407 v0.8.0 2022-04-04 21:43:44 +03:00
Aşkın Gedik 979e5b2bc4
Merge pull request #20 from fixtheclouds/code
Added Faker::Code
2022-02-21 13:47:34 +03:00
Egor Romanov 7f32a1197b Added Faker::Code.imei 2022-02-16 22:55:53 +03:00
Egor Romanov e2c95c114d Added Faker::Code.isbn 2022-02-16 22:53:16 +03:00
Aşkın Gedik 9f8608f7cd v0.7.0 2022-01-17 18:26:28 +03:00
Aşkın Gedik c1094112ee
Merge pull request #18 from mmacia/master
Added Faker::Date generators for date factories
2022-01-08 23:27:55 +03:00
Moisès Macià 3570ade457 added Faker::Date generators for date factories 2022-01-07 16:35:11 +01:00
robacarp 0d54d8e729
Merge pull request #17 from askn/ci_actions
add github actions CI
2021-04-11 21:49:18 -06:00
Rob ea898d7352 add github actions CI 2021-04-10 20:42:25 -06:00
Aşkın Gedik bfda3f2fd8 v0.6.0 2021-04-10 21:03:31 +03:00
Aşkın Gedik 86dcfb72ad
Merge pull request #16 from josacar/master
Support Crystal 1.0 version
2021-04-10 21:02:02 +03:00
Jose Luis Salas 352c3905fc
Support Crystal 1.0 version 2021-03-24 20:13:33 +01:00
Aşkın Gedik 12e5de36f1 v0.5.0 2021-03-18 00:29:58 +03:00
Aşkın Gedik 77ec8b25f3
Merge pull request #15 from jinn999/fix-issue-10-internet-user-name
Fix issue 10 internet user name
2021-03-18 00:13:35 +03:00
Davide Paolo Tua ffab21cdc5 Remove commented code 2021-02-24 14:47:37 +01:00
Davide Paolo Tua fa7f556864 Fix username rotating between only 4 fixed values 2021-02-24 14:44:22 +01:00
Aşkın Gedik 112bfd0ba0
Merge pull request #14 from jinn999/fix-failing-business-card-spec
Fix business card failing spec
2020-11-17 22:20:28 +03:00
Davide Paolo Tua 56a48c18bd Fix business card failing spec 2020-11-17 19:15:28 +01:00
Aşkın Gedik 5caaca1080
Merge pull request #13 from josacar/master
Bump version to 0.4.1 to tag it as shards expect
2020-11-07 12:36:24 +03:00
Jose Luis Salas 5b7a1a9e92
Bump version to 0.4.1 to tag it as shards expect 2020-11-01 18:02:03 +01:00
Aşkın Gedik 83c938838b
Merge pull request #7 from rickychilcott/feature/unique
Generate unique address
2019-06-26 21:14:12 +03:00
Ricky Chilcott 06ad8f03e5 Expand Travis script to execute examples 2019-06-19 12:22:22 -04:00
Ricky Chilcott 544bb80025 Clean up comment 2019-06-19 09:32:20 -04:00
Ricky Chilcott bd1a8efc6c Get all methods to have a `unique_` variant 2019-06-19 09:15:51 -04:00
Ricky Chilcott 4d8f2e6f6e Crystal format 2019-06-18 22:20:53 -04:00
Ricky Chilcott 0b8c158403 Merge remote-tracking branch 'askn/master' into feature/unique 2019-06-18 20:53:11 -04:00
Aşkın Gedik 5b53bf19c5
Merge pull request #9 from art-of-dom/travis-fix
Fix nested it in specs
2019-02-28 17:41:10 +03:00
Dom Postorivo df79923101 fix nested it in specs 2019-02-25 20:55:08 -05:00
Aşkın Gedik da14470383
Merge pull request #8 from vnbrs/patch-1
Fix README.md titles
2018-12-09 18:15:01 +03:00
Vinicius Brasil 9243265586
Fix README.md titles 2018-12-08 00:30:13 -02:00
Ricky Chilcott 5e4fc757e5 Uniquify no argument methods 2018-09-24 08:22:18 -04:00
29 changed files with 565 additions and 58 deletions

25
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: Tests
on:
schedule:
- cron: '0 10 1 * *'
pull_request:
branches:
- master
push:
branches:
- master
jobs:
build:
name: Test
runs-on: ubuntu-latest
container:
image: crystallang/crystal:latest
steps:
- uses: actions/checkout@v2
- run: crystal --version
- run: shards install
- run: crystal spec
- run: crystal run examples/test.cr
- run: crystal run examples/test2.cr

View File

@ -1,3 +0,0 @@
language: crystal
crystal:
- latest

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2015 Aşkın Gedik
Copyright (c) 2021 Aşkın Gedik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -27,7 +27,7 @@ Faker::Name.name
If you wish to seed the random data, you can call `Faker.seed number` and then all subsequent calls will be deterministic.
### Faker::Address
### Faker::Address
```crystal
Faker::Address.city #=> "Imogeneborough"
@ -66,7 +66,7 @@ Faker::Address.latitude #=> "-58.17256227443719"
Faker::Address.longitude #=> "-156.65548382095133"
```
### Faker::Business
### Faker::Business
```crystal
@ -79,7 +79,18 @@ Faker::Business.credit_card_type #=> "visa"
```
### Faker::Commerce
### Faker::Code
```crystal
Faker::Code.isbn #=> "640354399-7"
Faker::Code.imei #=> "531691246033652"
```
### Faker::Commerce
```crystal
@ -97,7 +108,7 @@ Faker::Commerce.price #=> "44.6"
Faker::Commerce.material #=> "Plastic"
```
### Faker::Company
### Faker::Company
```crystal
@ -110,7 +121,25 @@ Faker::Company.logo #=> "https://pigment.github.com/fake-logos/logos/medium/colo
```
### Faker::Internet
### Faker::Date
```crystal
Faker::Date.birthday.to_s("%Y-%m-%d") #=> "1993-03-09"
Faker::Date.between("2020-01-01", "2020-08-15").to_s("%Y-%m-%d") #=> "2020-03-29"
Faker::Date.between_except("2020-01-01", "2020-08-15", "2020-05-10").to_s("%Y-%m-%d") #=> "2020-03-29"
Faker::Date.forward(days: 30).to_s("%Y-%m-%d") #=> "2022-02-09"
Faker::Date.backward(days: 30).to_s("%Y-%m-%d") #=> "2021-12-12"
Faker::Date.in_date_period(year: 2005).to_s("%Y-%m-%d") #=> "2005-02-12"
```
### Faker::Internet
```crystal
# Optional argument name=nil
@ -172,7 +201,7 @@ Faker::Internet.slug('foo bar', '-') #=> "foo-bar"
```
### Faker::Lorem
### Faker::Lorem
```crystal
@ -213,7 +242,7 @@ Faker::Lorem.paragraphs(1, true) #=> ""
```
### Faker::Name
### Faker::Name
```crystal
Faker::Name.name #=> "Tyshawn Johns Sr."
@ -230,7 +259,7 @@ Faker::Name.title #=> "Legacy Creative Director"
```
### Faker::Number
### Faker::Number
```crystal
@ -255,7 +284,7 @@ Faker::Number.digit #=> "1"
```
### Faker::PhoneNumber
### Faker::PhoneNumber
```crystal

View File

@ -23,9 +23,15 @@ puts Faker::Address.longitude
puts "\n### Faker::Commerce\n\n"
puts Faker::Commerce.color
puts Faker::Commerce.unique_color
puts Faker::Commerce.department
puts Faker::Commerce.unique_department
puts Faker::Commerce.unique_department(2)
puts Faker::Commerce.unique_department(2, true)
puts Faker::Commerce.product_name
puts Faker::Commerce.price
puts Faker::Commerce.unique_price
puts Faker::Commerce.unique_price(0.0..10_000.00)
puts "\n### Faker::Company\n\n"
@ -38,10 +44,16 @@ puts "\n\t### Faker::Internet\n\n"
puts Faker::Internet.email
puts Faker::Internet.email("Nancy")
puts Faker::Internet.unique_email("Nancy")
puts Faker::Internet.unique_email("Nancy")
puts Faker::Internet.free_email
puts Faker::Internet.unique_free_email
puts Faker::Internet.free_email("Nancy")
puts Faker::Internet.unique_free_email("Nancy")
puts Faker::Internet.safe_email
puts Faker::Internet.unique_safe_email
puts Faker::Internet.safe_email("Nancy")
puts Faker::Internet.unique_safe_email("Nancy")
puts Faker::Internet.user_name
puts Faker::Internet.user_name("Nancy")
@ -88,12 +100,25 @@ puts Faker::Name.prefix
puts Faker::Name.suffix
puts Faker::Name.title
puts "\n\t### Faker::Avatar\n\n"
puts Faker::Avatar.image
puts Faker::Avatar.image("borp")
puts Faker::Avatar.unique_image("borp")
puts Faker::Avatar.unique_image("borp")
puts "\n\t### Faker::Number\n\n"
puts Faker::Number.number(10)
# puts Faker::Number.unique_number(10)
# puts Faker::Number.unique_number(10)
# puts Faker::Number.unique_number(10)
puts Faker::Number.decimal(2)
puts Faker::Number.decimal(2, 3)
puts Faker::Number.unique_decimal(2)
# puts Faker::Number.unique_decimal(2, 3)
puts Faker::Number.digit
puts Faker::Number.unique_digit
puts "\n\t### Faker::PhoneNumber\n\n"
@ -101,6 +126,10 @@ puts Faker::PhoneNumber.phone_number
puts "\n\t### Faker::Business\n\n"
p Faker::Business.credit_card_number
p Faker::Business.credit_card_expiry_date
p Faker::Business.credit_card_type
puts Faker::Business.credit_card_number
puts Faker::Business.credit_card_expiry_date
puts Faker::Business.credit_card_type
puts Faker::Business.unique_credit_card_number
puts Faker::Business.unique_credit_card_expiry_date
puts Faker::Business.unique_credit_card_type

View File

@ -1,7 +1,9 @@
name: faker
version: 0.2.0
version: 0.8.0
authors:
- Aşkın Gedik <askn@bil.omu.edu.tr>
license: MIT
crystal: "~> 1.0, >= 1.0.0"

View File

@ -21,4 +21,15 @@ describe Faker::Address do
Faker::Address.latitude.should eq "-23.850993082533705"
Faker::Address.longitude.should eq "-4.488135572134695"
end
it "should generate unique result" do
Faker.seed 123456
vals = Array(String).new
10_000.times do |t|
vals << Faker::Address.unique_city
end
vals.size.should eq vals.uniq.size
end
end

View File

@ -4,7 +4,7 @@ describe Faker::Business do
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Business.credit_card_number.should eq "1228-1221-1221-1431"
Faker::Business.credit_card_expiry_date.should eq Time.new(2013, 9, 12)
Faker::Business.credit_card_expiry_date.should eq Time.local(2013, 9, 12)
Faker::Business.credit_card_type.should eq "mastercard"
end
end

22
spec/code_spec.cr Normal file
View File

@ -0,0 +1,22 @@
require "./spec_helper"
describe Faker::Code do
it "base 10 isbn" do
Faker::Code.isbn.match(/^\d{9}-[\d|X]$/).should_not eq nil
end
it "base 13 isbn" do
Faker::Code.isbn(13).match(/^\d{12}-\d$/).should_not eq nil
end
it "imei" do
Faker::Code.imei.match(/\A[\d.:\-\s]+\z/i).should_not eq nil
end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Code.isbn.should eq "394314441-0"
Faker::Code.isbn(13).should eq "205982563728-9"
Faker::Code.imei.should eq "860839366575918"
end
end

106
spec/date_spec.cr Normal file
View File

@ -0,0 +1,106 @@
require "./spec_helper"
describe Faker::Date do
describe "#between" do
it "should return between date" do
from = Time.parse("2019-01-01", "%Y-%m-%d", Time::Location::UTC)
to = Time.parse("2022-01-01", "%Y-%m-%d", Time::Location::UTC)
100.times do
random_date = Faker::Date.between(from: from, to: to)
random_date.should be >= from
random_date.should be <= to
end
end
it "should raise and exception on invalid date" do
from = "2019-01-01"
to = "0000-00-00"
expect_raises(ArgumentError, "Invalid time") do
Faker::Date.between(from: from, to: to)
end
end
end
describe "#between_except" do
it "should return between date except gvien one" do
from = "2012-01-01"
to = "2012-01-05"
excepted = "2012-01-03"
100.times do
random_date = Faker::Date.between_except(from: from, to: to, excepted: excepted)
random_date.should_not be_nil
random_date.should_not eq(Time.parse(excepted, "%Y-%m-%d", Time::Location::UTC))
end
end
it "should raise an excpetion when all args are the same" do
from = "2012-01-01"
to = "2012-01-01"
excepted = "2012-01-01"
expect_raises(ArgumentError, "From date, to date and excepted date must not be the same") do
Faker::Date.between_except(from: from, to: to, excepted: excepted)
end
end
end
describe "#birthday" do
it "should return a birthday" do
min = 40
max = 90
t = Time.utc
birthday_min = Time.utc(t.year - max, t.month, t.day)
birthday_max = Time.utc(t.year - min, t.month, t.day)
100.times do
birthday = Faker::Date.birthday(min_age: min, max_age: max)
birthday.should be >= birthday_min
birthday.should be <= birthday_max
end
end
it "should return today when min_age and max_age are the same" do
min = 0
max = 0
t = Time.utc
birthday = Faker::Date.birthday(min_age: min, max_age: max)
birthday.should eq Time.utc(t.year, t.month, t.day)
end
end
it "should return a forward date" do
today = Time.utc
100.times do
random_date = Faker::Date.forward(days: 5)
random_date.should be > today
end
end
it "should return a backward date" do
today = Time.utc
100.times do
random_date = Faker::Date.backward(days: 5)
random_date.should be < today
end
end
describe "#date_in_period" do
it "should work with default params" do
current_year = Time.utc.year
10.times do
date = Faker::Date.in_date_period
date.year.should eq(current_year)
end
end
end
end

View File

@ -63,14 +63,14 @@ describe Faker::Internet do
it "password_with_integer_arg" do
(1..32).to_a.each do |min_length|
it { (Faker::Internet.password(min_length).size >= min_length).should be_true }
(Faker::Internet.password(min_length).size >= min_length).should be_true
end
end
it "password_max_with_integer_arg" do
(1..32).to_a.each do |min_length|
max_length = min_length + 4
it { (Faker::Internet.password(min_length, max_length).size <= max_length).should be_true }
(Faker::Internet.password(min_length, max_length).size <= max_length).should be_true
end
end
@ -169,32 +169,32 @@ describe Faker::Internet do
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Internet.email.should eq "faker_internet@deckowboyer.biz"
Faker::Internet.email("Nancy").should eq "nancy@batz.org"
Faker::Internet.free_email.should eq "internet.faker@hotmail.com"
Faker::Internet.email.should eq "danyka.gleichner@fay.net"
Faker::Internet.email("Nancy").should eq "nancy@barrows.name"
Faker::Internet.free_email.should eq "dayne_brown@hotmail.com"
Faker::Internet.free_email("Nancy").should eq "nancy@yahoo.com"
Faker::Internet.safe_email.should eq "internet_faker@example.org"
Faker::Internet.safe_email("Nancy").should eq "nancy@example.com"
Faker::Internet.user_name.should eq "internet.faker"
Faker::Internet.safe_email.should eq "cassie@example.net"
Faker::Internet.safe_email("Nancy").should eq "nancy@example.org"
Faker::Internet.user_name.should eq "eve_batz"
Faker::Internet.user_name("Nancy").should eq "nancy"
Faker::Internet.user_name("Nancy Johnson", [".", "_", "-"] of ::String).should eq "nancy-johnson"
Faker::Internet.password.should eq "NuSjR9XpA"
Faker::Internet.password(8).should eq "Tb7vMjXzD"
Faker::Internet.password(10, 20).should eq "Xc0qFgOxMo"
Faker::Internet.password(10, 20, true).should eq "J9GvT6LdLd7"
Faker::Internet.password(10, 20, true, true).should eq "#*^!#&@%^iG"
Faker::Internet.domain_name.should eq "hackett.net"
Faker::Internet.domain_word.should eq "murphy"
Faker::Internet.domain_suffix.should eq "co"
Faker::Internet.ip_v4_address.should eq "38.54.91.207"
Faker::Internet.ip_v6_address.should eq "f682:cc5a:cb38:94d3:7911:ff68:94df:f377"
Faker::Internet.mac_address.should eq "00:d0:57:d9:d8:d5"
Faker::Internet.mac_address("55:44:33").should eq "55:44:33:bc:fd:c8"
Faker::Internet.url.should eq "http://vonruedenlind.name/faker_internet"
Faker::Internet.url("example.com").should eq "http://example.com/internet_faker"
Faker::Internet.password.should eq "P2AtB7Vm"
Faker::Internet.password(8).should eq "XzKdXc0qG"
Faker::Internet.password(10, 20).should eq "Vj9gVt6lDlQ"
Faker::Internet.password(10, 20, true).should eq "7c2s0zXmQlT"
Faker::Internet.password(10, 20, true, true).should eq "@6IpGuR8PvG"
Faker::Internet.domain_name.should eq "beatty.io"
Faker::Internet.domain_word.should eq "veum"
Faker::Internet.domain_suffix.should eq "io"
Faker::Internet.ip_v4_address.should eq "230.101.43.38"
Faker::Internet.ip_v6_address.should eq "a970:ba8b:26b8:f682:cc5a:cb38:94d3:7911"
Faker::Internet.mac_address.should eq "00:68:df:77:d0:57"
Faker::Internet.mac_address("55:44:33").should eq "55:44:33:d9:d8:d5"
Faker::Internet.url.should eq "http://raugottlieb.com/mia_hills"
Faker::Internet.url("example.com").should eq "http://example.com/daron_nolan"
Faker::Internet.url("example.com", "/foobar.html").should eq "http://example.com/foobar.html"
Faker::Internet.slug.should eq "mollitia.nostrum"
Faker::Internet.slug("foo bar").should eq "foo.bar"
Faker::Internet.slug.should eq "doloribus_quidem"
Faker::Internet.slug("foo bar").should eq "foo_bar"
Faker::Internet.slug("foo bar", "-").should eq "foo-bar"
end
end

View File

@ -1,4 +1,5 @@
require "./data.cr"
require "./faker/base"
require "./faker/*"
module Faker

View File

@ -1,19 +1,24 @@
module Faker
class Address
class Address < Base
def self.zip_code
Faker.numerify(["#####", "#####-####"].sample(Faker.rng))
end
uniquify_builder(zip_code)
{% for data_type in %w(state state_abbr city_suffix city_prefix country street_suffix country_code) %}
def self.{{data_type.id}}
Faker.fetch(Data["address"]["{{data_type.id}}"])
end
uniquify_builder({{data_type.id}})
{% end %}
def self.city
Faker.fetch(Data["address"]["city"])
end
uniquify_builder(city)
def self.street_name
[
->{ [Name.last_name, street_suffix].join(" ") },
@ -21,6 +26,8 @@ module Faker
].sample(Faker.rng).call
end
uniquify_builder(street_name)
def self.street_address
Faker.numerify([
->{ "##### %s" % street_name },
@ -32,14 +39,20 @@ module Faker
].sample(Faker.rng).call)
end
uniquify_builder(street_address)
def self.secondary_address
Faker.numerify(Faker.fetch(Data["address"]["secondary_address"]))
end
uniquify_builder(street_address)
def self.building_number
Faker.bothify(Faker.fetch(Data["address"]["building_number"]))
end
uniquify_builder(building_number)
def self.postcode
Faker.bothify([
->{ "??# #??" },
@ -47,16 +60,24 @@ module Faker
].sample(Faker.rng).call)
end
uniquify_builder(postcode)
def self.latitude
((Faker.rng.rand * 180) - 90).to_s
end
uniquify_builder(latitude)
def self.longitude
((Faker.rng.rand * 360) - 180).to_s
end
uniquify_builder(longitude)
def self.time_zone
Faker.fetch(Data["address"]["time_zone"])
end
uniquify_builder(time_zone)
end
end

View File

@ -1,8 +1,10 @@
module Faker
class Avatar
class Avatar < Base
def self.image(slug = nil)
slug ||= Faker::Lorem.word
"http://robohash.org/#{slug}"
end
uniquify_builder(image, slug = nil)
end
end

25
src/faker/base.cr Normal file
View File

@ -0,0 +1,25 @@
module Faker
class NonUniqueValue < Exception
end
class Base
alias Any = String | Int32 | Float64 | Time
macro uniquify_builder(attribute_name, *modified_method_attributes)
@@__unique_vals_for_{{attribute_name}} = Array(Any).new
def self.unique_{{attribute_name}}({% if !modified_method_attributes.empty? %}{{*modified_method_attributes}},{% end %} max_retries = 10_0000)
max_retries.times do |t|
val = self.{{attribute_name}}({{*modified_method_attributes}})
if !@@__unique_vals_for_{{attribute_name}}.includes?(val)
@@__unique_vals_for_{{attribute_name}} << val
return val
end
end
raise NonUniqueValue.new("Unable to generate unique value for {{attribute_name}}")
end
end
end
end

View File

@ -1,16 +1,22 @@
module Faker
class Business
class Business < Base
def self.credit_card_number
Faker.fetch(Data["business"]["credit_card_numbers"])
end
uniquify_builder(credit_card_number)
def self.credit_card_expiry_date
credit_card_expiry_date = Faker.fetch(Data["business"]["credit_card_expiry_dates"]).as String
Time.parse_local(credit_card_expiry_date, "%Y-%m-%d")
end
uniquify_builder(credit_card_expiry_date)
def self.credit_card_type
Faker.fetch(Data["business"]["credit_card_types"])
end
uniquify_builder(credit_card_type)
end
end

66
src/faker/code.cr Normal file
View File

@ -0,0 +1,66 @@
module Faker
class Code < Base
RBI = %w[01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99]
def self.isbn(base : Int32 = 10)
case base
when 10 then generate_base10_isbn
when 13 then generate_base13_isbn
else raise ArgumentError.new("base must be 10 or 13")
end
end
def self.imei
str = Array.new(15, 0)
sum = 0
len = 15
# Fill in the first two values of the string based with the specified prefix.
arr = RBI.sample(Faker.rng)
str[0] = arr[0].to_i
str[1] = arr[1].to_i
pos = 2
# Fill all the remaining numbers except for the last one with random values.
while pos < (len - 1)
str[pos] = Faker.rng.rand(0..9)
pos += 1
end
# Calculate the Luhn checksum of the values thus far
len_offset = (len + 1) % 2
(0..(len - 1)).each do |position|
if (position + len_offset).odd?
t = str[position] * 2
t -= 9 if t > 9
sum += t
else
sum += str[position]
end
end
str[len - 1] = (10 - (sum % 10)) % 10
str.join("")
end
private def self.generate_base10_isbn
values = Faker.regexify(/\d{9}/)
remainder = sum(values) { |value, index| (index + 1) * value.to_i } % 11
values += "-#{remainder == 10 ? 'X' : remainder}"
end
private def self.generate_base13_isbn
values = Faker.regexify(/\d{12}/)
remainder = sum(values) { |value, index| index.even? ? value.to_i : value.to_i * 3 } % 10
values += "-#{(10 - remainder) % 10}"
end
private def self.sum(values)
values.split(//).each_with_index.reduce(0) do |sum, (value, index)|
sum + yield(value, index)
end
end
end
end

View File

@ -1,9 +1,11 @@
module Faker
class Commerce
class Commerce < Base
def self.color
Faker.fetch(Data["color"]["name"])
end
uniquify_builder(color)
def self.department(max = 3, fixed_amount = false)
num = max if fixed_amount
num ||= 1 + Faker.rng.rand(max)
@ -17,20 +19,28 @@ module Faker
end
end
uniquify_builder(department, max = 3, fixed_amount = false)
def self.material
product_name = Data["commerce"]["product_name"].as Hash
Faker.fetch(product_name["material"])
end
uniquify_builder(material)
def self.product_name
product_name = Data["commerce"]["product_name"].as Hash
Faker.fetch(product_name["adjective"]) + " " + Faker.fetch(product_name["material"]) + " " + Faker.fetch(product_name["product"])
end
uniquify_builder(product_name)
def self.price(range = 0.0..100.0)
(Faker.rng.rand(range) * 100).floor/100.0
end
uniquify_builder(price, range = 0.0..100.0)
private def self.categories(num)
categories = [] of String
while categories.size < num

View File

@ -1,26 +1,36 @@
module Faker
class Company
class Company < Base
def self.name
Faker.fetch(Data["company"]["name"])
end
uniquify_builder(name)
def self.suffix
Faker.fetch(Data["company"]["suffix"])
end
uniquify_builder(suffix)
def self.catch_phrase
data = Data["company"]["buzzwords"].as Array(Array(String))
Faker.fetch(data.flatten)
end
uniquify_builder(catch_phrase)
def self.bs
data = Data["company"]["bs"].as Array(Array(String))
Faker.fetch(data.flatten)
end
uniquify_builder(bs)
def self.logo
rand_num = Faker.rng.rand(13) + 1
"https://pigment.github.io/fake-logos/logos/medium/color/#{rand_num}.png"
end
uniquify_builder(logo)
end
end

74
src/faker/date.cr Normal file
View File

@ -0,0 +1,74 @@
module Faker
class Date < Base
def self.between(from : Time | String, to : Time | String) : Time
from = parse_date(from)
to = parse_date(to)
Time.unix(Faker.rand_in_range(from.to_unix, to.to_unix)).at_beginning_of_day
end
def self.between_except(from : Time | String, to : Time | String, excepted : Time | String)
raise ArgumentError.new("From date, to date and excepted date must not be the same") if from == to && to == excepted
excepted = parse_date(excepted)
loop do
date = between(from: from, to: to)
return date if date != excepted
end
end
def self.birthday(min_age : Int32 = 18, max_age : Int32 = 65) : Time
today = Time.utc
from = birthday_date(today, max_age)
to = birthday_date(today, min_age)
between(from, to)
end
def self.forward(days : Int32 = 365) : Time
from = Time.utc + 1.day
to = Time.utc + days.days
between(from: from, to: to)
end
def self.backward(days : Int32 = 365) : Time
from = Time.utc - days.days
to = Time.utc - 1.day
between(from: from, to: to)
end
def self.in_date_period(month : Int32? = nil, year : Int32 = Time.utc.year) : Time
from = Time.utc(year, month || 1, 1)
to_month = month || 12
end_day = Time.utc(year, to_month, 1).at_end_of_month.day
to = Time.utc(year, to_month, end_day)
between(from: from, to: to)
end
private def self.parse_date(date : String) : Time
Time.parse(date, "%Y-%m-%d", Time::Location::UTC)
end
private def self.parse_date(date : Time) : Time
date
end
private def self.birthday_date(date : Time, age : Int32) : Time
year = date.year - age
day =
if date.day == 29 && date.month == 2 && Time.leap_year?(year)
28
else
date.day
end
Time.utc(year, date.month, day)
end
end
end

View File

@ -1,5 +1,5 @@
module Faker
class Finance
class Finance < Base
CREDIT_CARD_TYPES = (Data["credit_card"].as(Hash)).keys
def self.credit_card(types : Array = [] of Array(String))
@ -21,5 +21,6 @@ module Faker
template = template.gsub "L", luhn_digit.to_s
template
end
# TODO: uniquify_builder(credit_card, types : Array = [] of Array(String))
end
end

View File

@ -1,14 +1,17 @@
# Port of http://shinytoylabs.com/jargon/
module Faker
class Hacker
class Hacker < Base
def self.say_something_smart
phrases.sample(Faker.rng)
end
uniquify_builder(say_something_smart)
{% for data_type in %w(abbreviation adjective noun verb ingverb) %}
def self.{{data_type.id}}
Faker.fetch(Data["hacker"]["{{data_type.id}}"])
end
uniquify_builder({{data_type.id}})
{% end %}
def self.phrases

View File

@ -1,17 +1,23 @@
module Faker
class Internet
class Internet < Base
def self.email(name = nil)
[user_name(name), domain_name].join("@")
end
uniquify_builder(email, name = nil)
def self.free_email(name = nil)
[user_name(name), Faker.fetch(Data["internet"]["free_email"])].join("@")
end
uniquify_builder(free_email, name = nil)
def self.safe_email(name = nil)
[user_name(name), "example." + %w(org com net).shuffle(Faker.rng).first].join("@")
end
uniquify_builder(safe_email, name = nil)
def self.user_name(specifier = nil, separators = %w(. _))
if specifier.is_a? String
return specifier.scan(/\w+/).map { |s| s[0] }.shuffle(Faker.rng).join(separators.sample(Faker.rng)).downcase
@ -40,7 +46,6 @@ module Faker
return result[0...specifier.max]
end
return name.scan(/\w+/).shuffle(Faker.rng).map(&.[0]).join(separators.sample(Faker.rng)).downcase if name
[
->{ Name.first_name.gsub(/\W/, "").downcase },
->{
@ -51,18 +56,26 @@ module Faker
].sample(Faker.rng).call
end
uniquify_builder(user_name, specifier = nil, separators = %w(. _))
def self.domain_name
[domain_word, domain_suffix].join(".")
end
uniquify_builder(domain_name)
def self.domain_word
Company.name.split(" ").first.gsub(/\W/, "").downcase
end
uniquify_builder(domain_word)
def self.domain_suffix
Faker.fetch(Data["internet"]["domain_suffix"])
end
uniquify_builder(domain_suffix)
def self.ip_v4_address
[
(2..254).to_a.sample(Faker.rng),
@ -72,27 +85,37 @@ module Faker
].join('.')
end
uniquify_builder(ip_v4_address)
def self.ip_v6_address
ip_v6_space = (0..65535).to_a
container = (1..8).map { |_| ip_v6_space.sample(Faker.rng) }
container.map { |n| n.to_s(16) }.join(':')
end
uniquify_builder(ip_v6_address)
def self.mac_address(prefix = "")
prefix_digits = prefix.split(":").map { |d| d.to_i?(16) ? d.to_i?(16) : 0 }
address_digits = (1..(6 - prefix_digits.size)).map { Faker.rng.rand(256) }
(prefix_digits + address_digits).map { |d| "%02x" % d }.join(":")
end
uniquify_builder(mac_address, prefix = "")
def self.url(host = domain_name, path = "/#{user_name}")
"http://#{host}#{path}"
end
uniquify_builder(url, host = domain_name, path = "/#{user_name}")
def self.slug(words = nil, glue = nil)
glue ||= %w(- _ .).sample(Faker.rng)
(words || Lorem.words(2).join(' ')).gsub(' ', glue).downcase
end
uniquify_builder(slug, words = nil, glue = nil)
def self.password(min_length = 8, max_length = 16, mix_case = true, special_chars = false)
temp = Lorem.characters(min_length)
diff_length = max_length - min_length
@ -108,12 +131,15 @@ module Faker
if special_chars
chars = %w(! @ # $ % ^ & *)
Faker.rng.rand(min_length).times do |i|
number_of_substitutions = Faker.rng.rand(min_length - 1) + 1 # substitute at least one character
number_of_substitutions.times do |i|
temp = temp.sub({temp[i] => chars[Faker.rng.rand(chars.size)]})
end
end
return temp
end
uniquify_builder(password, min_length = 8, max_length = 16, mix_case = true, special_chars = false)
end
end

View File

@ -1,20 +1,26 @@
module Faker
# Based on Perl"s Text::Lorem
class Lorem
class Lorem < Base
def self.character
characters(1)
end
uniquify_builder(character)
def self.characters(char_count = 255)
chars = ("a".."z").to_a + (0..9).to_a
Array(String).new(char_count < 0 ? 0 : char_count, "").map { chars.sample(Faker.rng) }.join("")
end
uniquify_builder(characters)
def self.word
words = Data["lorem"]["words"].as Array
Faker.fetch(words)
end
uniquify_builder(word)
def self.words(num = 3, supplemental = false)
words = Data["lorem"]["words"].as Array(String)
words += (Data["lorem"]["supplemental"].as Array(String)) if supplemental
@ -22,10 +28,14 @@ module Faker
words.shuffle(Faker.rng)[0, num]
end
uniquify_builder(words)
def self.sentence(word_count = 4, supplemental = false, random_words_to_add = 6)
words(word_count + Faker.rng.rand(random_words_to_add.to_i).to_i, supplemental).join(" ").capitalize + "."
end
uniquify_builder(sentence)
def self.sentences(sentence_count = 3, supplemental = false)
([] of String).tap do |sentences|
1.upto(sentence_count) do
@ -34,10 +44,14 @@ module Faker
end
end
uniquify_builder(sentences)
def self.paragraph(sentence_count = 3, supplemental = false, random_sentences_to_add = 3)
sentences(sentence_count + Faker.rng.rand(random_sentences_to_add.to_i).to_i, supplemental).join(" ")
end
uniquify_builder(paragraph)
def self.paragraphs(paragraph_count = 3, supplemental = false)
([] of String).tap do |paragraphs|
1.upto(paragraph_count) do
@ -45,5 +59,7 @@ module Faker
end
end
end
uniquify_builder(paragraphs)
end
end

View File

@ -1,14 +1,17 @@
module Faker
class Name
class Name < Base
{% for data_type in %w(first_name last_name name prefix suffix) %}
def self.{{data_type.id}}
Faker.fetch(Data["name"]["{{data_type.id}}"])
end
uniquify_builder({{data_type.id}})
{% end %}
def self.title
title = Data["name"]["title"].as Hash
Faker.fetch(title["descriptor"]) + " " + Faker.fetch(title["level"]) + " " + Faker.fetch(title["job"])
end
uniquify_builder(title)
end
end

View File

@ -1,39 +1,53 @@
module Faker
class Number
class Number < Base
def self.number(digits)
(1..digits).map { digit }.join ""
end
uniquify_builder(number, digits)
def self.digit
Faker.rng.rand(10).to_s
end
uniquify_builder(digit)
def self.decimal(l_digits, r_digits = 2)
l_d = number(l_digits)
r_d = number(r_digits)
"#{l_d}.#{r_d}"
end
uniquify_builder(decimal, l_digits, r_digits = 2)
def self.between(from = 1.00, to = 5000.00)
Faker.rand_in_range(from, to)
end
uniquify_builder(between)
def self.positive(from = 1.00, to = 5000.00)
random_number = between(from, to)
greater_than_zero(random_number)
end
uniquify_builder(positive)
def self.negative(from = -5000.00, to = -1.00)
random_number = between(from, to)
less_than_zero(random_number)
end
uniquify_builder(negative)
def self.hexadecimal(digits)
hex = ""
digits.times { hex += Faker.rng.rand(15).to_s(16) }
hex
end
uniquify_builder(hexadecimal)
private def self.greater_than_zero(number)
if number > 0
number

View File

@ -1,7 +1,9 @@
module Faker
class PhoneNumber
class PhoneNumber < Base
def self.phone_number
Faker.numerify(Faker.fetch(Data["phone_number"]["formats"]))
end
uniquify_builder(phone_number)
end
end

View File

@ -1,15 +1,21 @@
module Faker
class Team
class Team < Base
def self.name
Faker.fetch(Data["team"]["name"])
end
uniquify_builder(name)
def self.creature
Faker.fetch(Data["team"]["creature"])
end
uniquify_builder(creature)
def self.state
Faker.fetch(Data["address"]["state"])
end
uniquify_builder(state)
end
end

View File

@ -1,3 +1,3 @@
module Faker
VERSION = "0.3.0"
VERSION = "0.8.0"
end