Module: EasyCaptcha::ControllerHelpers
- Defined in:
- lib/easy_captcha/controller_helpers.rb
Overview
helper class for ActionController
Class Method Summary collapse
-
.included(base) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#captcha_valid?(code) ⇒ Boolean
(also: #valid_captcha?)
validate given captcha code and re.
-
#generate_captcha ⇒ Object
generate captcha image and return it as blob.
-
#generate_captcha_code ⇒ Object
generate captcha code, save in session and return.
-
#reset_last_captcha_code! ⇒ Object
reset the captcha code in session for security after each request.
Class Method Details
.included(base) ⇒ Object
:nodoc:
5 6 7 8 9 |
# File 'lib/easy_captcha/controller_helpers.rb', line 5 def self.included(base) #:nodoc: base.class_eval do helper_method :valid_captcha?, :captcha_valid? end end |
Instance Method Details
#captcha_valid?(code) ⇒ Boolean Also known as: valid_captcha?
validate given captcha code and re
49 50 51 52 |
# File 'lib/easy_captcha/controller_helpers.rb', line 49 def captcha_valid?(code) return false if session[:captcha].blank? or code.blank? session[:captcha].to_s.upcase == code.to_s.upcase end |
#generate_captcha ⇒ Object
generate captcha image and return it as blob
12 13 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 |
# File 'lib/easy_captcha/controller_helpers.rb', line 12 def generate_captcha if EasyCaptcha.cache # create cache dir FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir) # select all generated captchas from cache files = Dir.glob(EasyCaptcha.cache_temp_dir + "*") unless files.size < EasyCaptcha.cache_size file = File.open(files.at(Kernel.rand(files.size))) session[:captcha] = File.basename(file.path) if file.mtime < EasyCaptcha.cache_expire.ago File.unlink(file.path) else return file.readlines.join end end generated_code = generate_captcha_code image = Captcha.new(generated_code).image # write captcha for caching File.open(EasyCaptcha.cache_temp_dir + "#{generated_code}", 'w') { |f| f.write image } # return image image else Captcha.new(generate_captcha_code).image end end |
#generate_captcha_code ⇒ Object
generate captcha code, save in session and return
44 45 46 |
# File 'lib/easy_captcha/controller_helpers.rb', line 44 def generate_captcha_code session[:captcha] = EasyCaptcha.length.times.collect { EasyCaptcha.chars[rand(EasyCaptcha.chars.size)] }.join end |
#reset_last_captcha_code! ⇒ Object
reset the captcha code in session for security after each request
56 57 58 |
# File 'lib/easy_captcha/controller_helpers.rb', line 56 def reset_last_captcha_code! session.delete(:captcha) end |