Skip to content

Commit

Permalink
Add image_file method to Placeholdit module
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-brousse committed May 23, 2018
1 parent 4ef5dbd commit 76678bb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/faker/placeholdit.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
require "tempfile"
require "net/http"

module Faker
class Placeholdit < Base
class << self
Expand All @@ -9,8 +12,8 @@ def image(size = '300x300', format = 'png', background_color = nil, text_color =

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)/)
raise ArgumentError, "background_color must be a hex value without '#'" unless background_color.nil? || background_color =~ /((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/
raise ArgumentError, "text_color must be a hex value without '#'" unless text_color.nil? || text_color =~ /((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/

image_url = "https://placehold.it/#{size}.#{format}"
image_url += "/#{background_color}" if background_color
Expand All @@ -19,11 +22,24 @@ def image(size = '300x300', format = 'png', background_color = nil, text_color =
image_url
end

def image_file(size = '300x300', format = 'png', background_color = nil, text_color = nil, text = nil)
download_file image(size, format, background_color, text_color, text)
end

private

def generate_color
format('%06x', (rand * 0xffffff))
end

def download_file(url)
file = Tempfile.new("faker_placeholdit")
file.binmode
file << Net::HTTP.get(URI(url))
file.close

::File.new(file.path)
end
end
end
end
4 changes: 4 additions & 0 deletions test/test_placeholdit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,8 @@ def test_text_not_present
def test_text_present
assert @tester.image('300x300', 'jpg', 'fff', '000', 'hello').match(%r{https:\/\/placehold\.it\/(.+)\?text=hello})
end

def test_image_file
assert_instance_of File, @tester.image_file('300x300', 'jpg', 'fff', '000', 'hello')
end
end

0 comments on commit 76678bb

Please sign in to comment.