Captchas and Ruby on Rails

I was spending God-knows how many hours working on setting up a Captcha when I found out that Ruby has a gem that does the same thing; the “captcha” gem. Just go into the directory for the program you are running, and install it from there.

Of course, I get a useless error message. “no such file to load — GD”. I installed GD2, and there is no GD gem to install. Damn it. Looking it up, it seems like a lot of people are having the same problem…

-edit-

OK, this is a big problem and one that is not easily resolved.

GD was the previous, faulty way to use the GD library in Ruby. Unfortunately, you can’t just install a rubygem and get it operational; you need to compile and install the library. Fortunately, GD is used generally in PHP and is usually installed on any properly setup system. However, this makes testing in Instantrails / etc.. very difficult. Adding to this is out-dated nature of Ruby-GD which is the old interface between Ruby and GD.

Enter GD2, which is the new interface and handles everything (and more). However, the Captcha module is not compatible with GD2 – which I thought meant I had to build something completely new. THANK GOD that is not the case. There is a gem called “Turing” which is compatible with GD2, and resolves the problem.

Simply do this from SSH:

gem install turning

Then go into the code and add the following:

require_gem 'turing'

This code, within the subroutine you desire, will output the captcha image into the /public/ directory

ti = Turing::Image.new(:width => 280, :height => 115)
ti.generate(File.join(Dir.getwd, 'a.jpg'), "captchaword")

You can simply output the a.jpg in the associated “RHTML” file. You can, of course, replace the output file name / captcha word with a randomly generated word (be it from a dictionary or what have you).

How to log someone’s IP Address when submitting a form?

So I need to create the ability for a user to submit a form – and I would like to enable some sort of primitive security system. To that end, I need to work out a way to check IP addresses.  All this while in PERL (it’s pretty damn simple in PHP and Ruby on Rails). Let’s see what I can find (hopefully..)

-edit-

Well that wasn’t so bad.

render_text request.env['REMOTE_HOST'].to_s

-edit-

So it turns out that this doesn’t always work. There is a better way to do so; try this.


render_text request.remote_ip().to_s

How to output the results of a function in a template file in Ruby?

Once again given the chance to play with Ruby, I’ve found another problem :/

Let’s say we have this function:

Def abc

render_text “abc”

end

How can I output this in a template file the first time it is loaded (for example, list.rhtml)? (I see the Render Partials function, but that doesn’t seem to be useful for what I am doing since there is no rhtml for the function in question)

Edit

Well the first place I looked was to action rendering. Unfortunately this is not doing the job, I gotta keep looking :(