Skip to content

Commit

Permalink
Adding Faker::Commerce.rating
Browse files Browse the repository at this point in the history
  • Loading branch information
bradly committed Sep 14, 2023
1 parent f7146f0 commit d785886
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
5 changes: 5 additions & 0 deletions doc/default/commerce.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ Faker::Commerce.product_name #=> "Practical Granite Shirt"
Faker::Commerce.price #=> 44.6
Faker::Commerce.price(range: 0..10.0, as_string: true) #=> "2.18"

# Produces a number between between 0 and 5
# Keyword arguments: range, as_string, decimals
Faker::Commerce.rating #=> 4
Faker::Commerce.rating(range: 0..10, decimals: 2, as_string: true) #=> "8.92"

# Generate a random promotion code.
# Keyword arguments: digits
Faker::Commerce.promotion_code #=> "AmazingDeal829102"
Expand Down
24 changes: 24 additions & 0 deletions lib/faker/default/commerce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,30 @@ def vendor
fetch('commerce.vendor')
end

##
# Produces a random product rating.
#
# @param range [Range] A range to generate the rating number within. Defaults to 0..5.
# @param decimals [Integer] Max number of decimals to generate. Defaults to 0
#
# @return [Integer]
#
# @example
# Faker::Commerce.rating #=> 3
# Faker::Commerce.rating(range: 0..10.0, decimals: 2, as_string: true) #=> "8.92"
#
# @faker.version next
def rating(range: 0..5, decimals: 0, as_string: false)
random_value = rand(range)

if decimals.positive?
format_string = "%.#{decimals}f"
random_value = format(format_string, random_value)
end

as_string ? random_value.to_s : random_value
end

private

def categories(num)
Expand Down
18 changes: 17 additions & 1 deletion test/faker/default/test_faker_commerce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def test_price_is_float
assert @tester.price.is_a? Float
end

def test_when_as_string_is_true
def test_price_when_as_string_is_true
assert @tester.price(range: 0..100.0, as_string: true).is_a?(String)
assert_includes @tester.price(range: 100..500.0, as_string: true), '.'
end
Expand All @@ -106,4 +106,20 @@ def test_brand
def test_vendor
assert_match(/[A-Z][a-z]+\.?/, @tester.vendor)
end

def test_rating
assert_includes 0..5, @tester.rating
end

def test_rating_with_range
assert_includes 1..2, @tester.rating(range: 1..2)
end

def test_rating_with_as_string
assert_instance_of String, @tester.rating(as_string: true)
end

def test_rating_with_decimals
assert_match(/\A\d\.\d{2}\z/, @tester.rating(decimals: 2, as_string: true))
end
end

0 comments on commit d785886

Please sign in to comment.