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.



60
61
62
63
64
# File 'lib/sinatra/captcha.rb', line 60

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



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
107
108
109
110
111
112
113
114
115
# File 'lib/sinatra/captcha.rb', line 79

def ajax_html id = 'captcha_ajax'
  div_id  = 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/#{div_id}', 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



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/sinatra/captcha.rb', line 66

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



117
118
119
# File 'lib/sinatra/captcha.rb', line 117

def image key
  @generator.refresh key
end

#validate(response, key) ⇒ Object



121
122
123
# File 'lib/sinatra/captcha.rb', line 121

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