Module: CaptchaGenerator

Defined in:
lib/idi_captcha_generator.rb

Class Method Summary collapse

Class Method Details

.generate_captchaObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/idi_captcha_generator.rb', line 7

def self.generate_captcha
  # Randomly generate a simple math question
  num1 = rand(1..10)
  num2 = rand(1..10)
  answer = num1 + num2
  question = "#{num1} + #{num2} = ?"

  # Create a white canvas using MiniMagick
  image = MiniMagick::Image.create('png') do |f|
    f.write MiniMagick::Image.new('canvas:white', size: '200x100').to_blob
  end

  # Annotate the captcha text on the image
  image.combine_options do |c|
    c.font 'Helvetica'
    c.fill 'black'
    c.pointsize '32'
    c.gravity 'center'
    c.draw "text 0,0 '#{question}'"
  end

  # Save image to a temporary location
  image_path = File.join(Dir.tmpdir, "captcha_#{Time.now.to_i}.png")
  image.write(image_path)

  { question: question, answer: answer, image_path: image_path }
end