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



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
# File 'lib/simple_captcha_guard/captcha.rb', line 14

def generate_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"}
    # Add random lines (5 lines)
    stroke_count = rand(6..7)
    stroke_count.times do
      convert.stroke "#{color_map[rand(1..4)]}"           # line color
      convert.strokewidth "#{rand(2)}"       # line thickness
      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:-"  # Output to stdout (returns binary blob)
    
  end.to_blob
end