Class: Rcaptcha

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Rcaptcha

Returns a new instance of Rcaptcha.



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

def initialize(options = {})
  @length    = options[:length] || 5
  @directory = options[:dir] || "tmp"
  @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



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

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

  canvas = Magick::Image.new(30 * @length, 60, Magick::HatchFill.new('#ffffff','#4169e1'))

  text = Magick::Draw.new
  text.annotate(canvas, 100, 50, 30, 5, @captcha) do
    self.fill = "#000000"
    self.stroke = "transparent"
    self.pointsize = 32
    self.font_weight = Magick::BoldWeight
    self.gravity = Magick::SouthGravity
  end

  canvas = canvas.implode(-0.4)
  data   = canvas.to_blob { self.format = "jpg" }

  f = File.new(@file, 'w')
  f.write(data)
  f.flush
  f.close
end

#generateObject



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

def generate
  clean!

  @captcha = SecureRandom.hex[0...@length]
  create_image
end

#valid?(text) ⇒ Boolean

Returns:

  • (Boolean)


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

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