Class: SimpleCaptchaGuard::Captcha

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_captcha_guard/captcha.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length = 5) ⇒ Captcha

Returns a new instance of Captcha.



10
11
12
# File 'lib/simple_captcha_guard/captcha.rb', line 10

def initialize(length = 5)
  @code = SecureRandom.alphanumeric(length).upcase
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



8
9
10
# File 'lib/simple_captcha_guard/captcha.rb', line 8

def code
  @code
end

Instance Method Details

#generate_imageObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/simple_captcha_guard/captcha.rb', line 14

def generate_image
  image = MiniMagick::Tool::Convert.new do |convert|
    convert.size "121x41"
    convert.gravity "center"
    convert.xc "white"
    convert.fill "black"
    convert.font "Helvetica"
    convert.pointsize "29"
    convert.draw "text 0,0 '#{@code}'"
    color_map = { 1 => "green", 2 => "red", 3 => "blue", 4 => "orange"}
    stroke_count = rand(6..7)
    stroke_count.times do
      convert.stroke "#{color_map[rand(1..4)]}"
      convert.strokewidth "#{rand(2)}"
      x1, y1 = rand(40), rand(38)
      x2, y2 = rand(65..120), rand(38)
      convert.draw "line #{x1},#{y1} #{x2},#{y2}"
    end
    convert.wave "3x55"
    convert << "png:-"
  end

  if image.is_a?(String)
    if image.include?("\0")
      # Definitely binary image data
      return image
    else
      # No null bytes, probably a file path, so check file existence safely
      return File.binread(image) if File.exist?(image)
    end
  end

  image
end