Class: Sinatra::Captcha::Image

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

Overview

TODO simpliify

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Image

Returns a new instance of Image.



51
52
53
54
55
# File 'lib/sinatra/captcha.rb', line 51

def initialize app
  @generator = FastCaptcha.new(nil, app.captcha_level, app.captcha_width, app.captcha_height)
  @ttl = app.captcha_ttl
  @width, @height = app.captcha_width, app.captcha_height
end

Instance Method Details

#ajax_html(id = 'captcha_ajax') ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/sinatra/captcha.rb', line 70

def ajax_html id='captcha_ajax'
  divid = id + '_div'
  snippet = <<-HTML
    <script type="text/javascript">
      $(document).ready(function() {
        $('##{id}_v').click(function() {
          load_captcha_#{id}();
          $(this).closest('form').find('input[type="submit"]').removeAttr('disabled');
          $('##{id}_r').click(function() {
            load_captcha_#{id}();
            $(this).closest('form').find('input[type="submit"]').removeAttr('disabled');
            return false;
          });
          $(this).remove();
          return false;
        });
      });
      function load_captcha_#{id}() {
          $('##{id}_r').hide();
          $('##{id}').slideDown(250);
          $('##{id}').load('/captcha/snippet/#{divid}', function() {
            $('##{id}').find('input[name="captcha[response]"]').focus();
          });
          $('##{id}').delay(#{@ttl*500}).slideUp(250, function() {
            $(this).closest('form').find('input[type="submit"]').attr('disabled', 'disabled');
            $('##{id}_r').show();
          });
          return false;
      }
    </script>
    <div class="captcha" style="display:none" id="#{id}"></div>
    <div id="#{id}_c">
      <button id="#{id}_v" class="submit">Show Captcha</button>
      <button id="#{id}_r" class="submit" style="display:none">Refresh Captcha</button>
    </div>
  HTML
end

#html(id = 'captcha', key = nil) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/sinatra/captcha.rb', line 57

def html id='captcha', key=nil
  challenge = @generator.generate @ttl, false
  snippet = <<-HTML
    <div id="#{id}">
      <div style="width:#{@width}px;height:#{@height}px;padding:0">
        <img style="margin: 0 auto" src="/captcha/#{challenge.key}" alt="loading ...">
      </div>
      <input type="hidden" name="captcha[challenge]" value="#{challenge.key}">
      <input autocomplete="off" id="cr#{id}" name="captcha[response]" value="">
    </div>
  HTML
end

#image(key) ⇒ Object



108
109
110
# File 'lib/sinatra/captcha.rb', line 108

def image key
  @generator.refresh key
end

#validate(response, key) ⇒ Object



112
113
114
# File 'lib/sinatra/captcha.rb', line 112

def validate response, key
  @generator.validate key, response
end