Class: Rcaptcha

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length, directory) ⇒ Rcaptcha

Returns a new instance of Rcaptcha.



7
8
9
10
11
# File 'lib/rcaptcha.rb', line 7

def initialize(length, directory)
  @length    = length
  @directory = directory
  @file      = ""
end

Instance Attribute Details

#imageObject (readonly)

Returns the value of attribute image.



5
6
7
# File 'lib/rcaptcha.rb', line 5

def image
  @image
end

Instance Method Details

#clean!Object



17
18
19
# File 'lib/rcaptcha.rb', line 17

def clean!
  File.delete(@file) if File.exists?(@file)
end

#create_imageObject

TODO: make images ‘more twisted’ to make it difficult to break



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rcaptcha.rb', line 29

def create_image
  filename = "#{SecureRandom.urlsafe_base64}.png"
  @image   = "#{filename}"
  @file    = "#{File.expand_path(@directory)}/#{filename}"

  granite = Magick::ImageList.new('granite:')
  canvas = Magick::ImageList.new
  canvas.new_image(180, 60, Magick::TextureFill.new(granite))
  text = Magick::Draw.new
  text.font_family = 'Monaco'
  text.pointsize = 42
  text.gravity = Magick::CenterGravity

  text.annotate(canvas, 0,0,2,2, @captcha) { self.fill = 'gray83' }
  text.annotate(canvas, 0,0,-1.5,-1.5, @captcha) { self.fill = 'gray40' }
  text.annotate(canvas, 0,0,0,0, @captcha) { self.fill = 'darkred' }

  canvas.write(@file)
end

#generateObject



21
22
23
24
25
26
# File 'lib/rcaptcha.rb', line 21

def generate
  clean!

  @captcha = SecureRandom.urlsafe_base64(@length)
  create_image
end

#valid?(my_captcha) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/rcaptcha.rb', line 13

def valid?(my_captcha)
  @captcha == my_captcha
end