Defend your Rails from spam with Akismet

July 24, 2009 - 8 Comments - ruby rails spam tools akismet

When I decided that I would roll code.isdangero.us as a custom-made blog in Rails, I thought of it as a fun, easy project. After all, blogs are simple, and the simplicity allows for plenty of room for attention to detail in making the code as tight as possible, similar to the way a haiku allows a poet to express his skill in language through the power of the simply-stated.

Of course, every project looks easy from a distance, because unforeseen problems are just that: unforeseen. It had been a while since I’d blogged, and therefore I had all but forgotten about the long war of blog software against the endless networks of compromised Windows machines turned into Viagra-pitching zombies, comparable in number to the mighty armies of ancient Persia.

Enter Akismet

Just as the 300 men under the command of King Leonidas of Sparta held back Persia’s onslaught by fighting in the shade, the forces of good in this war have gathered together their disparate forces into a collective known as Akismet.

Akismet is an API which tracks spam and ham submissions from participating blogs all over the world, building its knowledge of what spam looks like versus comments from good-natured, decent folks who aren’t trying to sell the latest antidepressant through your blog. It allows a blog to ask if a comment looks like spam before publishing it. It also allows the owner of that blog to tell Akismet when a comment is marked as spam or ham, thus giving back to Akismet’s intelligence with human analysis.

Integrating Akismet into your Rails app

I used a simple, one-file Ruby library for the base-level HTTP interaction with Akismet’s API. Download it, and then drop it into your lib directory in your Rails project.

You will want to have your comments begin storing the IP address, user agent, and HTTP referrer of the client posting the comment, as well as its “spam” status. This is achieved with a simple migration:

script/generate migration AddSpamInfoToDiscussions ip_address:string user_agent:string referer:string spam:boolean

You will probably want to edit this migration to add a default value to the spam column.

When your controller creates a Discussion record for an incoming comment, you can add this data like so:

Now let’s add a callback to our model which will ask Akismet if the comment looks like spam, and if so, mark it as such before saving it.

Let’s add a couple more methods for marking an existing Discussion as spam or ham:

And corresponding controller actions:

Hook up your routes (you’re RESTful, right?), and that’s it, you’re done! Unless of course you want a nice admin UI for checking comments and marking them as spam or ham, but I will leave that part up to you. All the functionality is in place, so have fun building that beautiful UI.

I hope someone finds this helpful. Fuck off, spammers!

Comments

The Web is collaborative. Isn't it great?

C6c3d4bbf353456dbec83ac6618d6561?s=50

Arya Asemanfar said:

Just kidding!

I ran into a similar problem and decided to just completely discard comments that Akismet thought are spam.

Akismet is pretty cool but when I was signing up, it required me to sign up for wordpress to get an API key, is that still true? I also remember there being an alternative to akismet, forgot the name though.

11611e595f8866809b075a8e718e7600?s=50

Chris Vincent said:

Nice, Arya. Nice.

Yes, you still have to get a Wordpress.com account to get an Akismet API key. This is annoying and they should change it. Other than that, Akismet has worked out extraordinarily well so far. Zero false positives and only the very occasional, rare false negative.

D3b14d5af4b1e0b1ce3994576ef945d8?s=50

Skilkysyday said:

http://google.com

9f7126f342bf28059e071cf6f7096363?s=50

Comoodoks said:

Обхватив руками эту аппетитную попку, Миша присел и вновь стал лизать выемку анального отверстия, сверля коником языка, стараясь проникнуть в глубь ануса. -Возьмите подкладку от рюкзака, и раздувайте как веером. – Я влюбился, видимо, по-настоящему. – Надо забросить свои ножки ему на спину, – предлагает ей Энни. проститутки города сафоново смоленской области Как было бы здорово, если бы эта проклятая Оксана не пришла, – охватила меня на минуту мысль. Голова мужчины исчезла под столом. проститутки Ардон... Прямых улик не было. – Не знаю… – смущённо промямлил Антон. Словно угадав его мысли, она, улыбнувшись, ответила: отзывы о проститутках москвы – Вадим. – Просто одежда вся пропотела, а ты так долго баню топил, что мы чуть не рехнулись. Сели на лавку. Сразу 2..

54f300170e47abdb649e0928db93ddfb?s=50

Plaigmaneill said:

Я вытащил из нее свой член, а с члена Сергея она соскочила сама. Кстати, а кто мать Вальрисы? – Не знаю. армянский чат знакомств, Эн, как кошечка развернулась к нам и, встав на коленочки стала подползать к нам. Ел торопливо и жадно, руками таская из миски кусочки. светильник сайт знакомств Но… – она замолчала. – Теперь понятно… – спокойно сказала Госпожа, – Так… Пиздуйте за мной. сайты знакомств в швеции... И спать хочу. Влагалище было узким и крепко накрепко стягивала моего дружка. Вариант появиться в военкомате в семейниках ему почему-то не нравился и он решил впервые в жизни самостоятельно купить себе трусы. гепатит знакомства – Перевернись-ка на спинку, детка. Не мучь меня, помоги мне!” “И он “помог”, устремив свое мужское естество в ее истекающую соками любви вагину”, – продолжил я свой внутренний монолог. знакомство с девушкой из миллерово – – Про тебя каждая мелочь, вплоть до щеточек и крема для клитора. Тика молча усмехнулась, и тихонько подпевая в унисон, пошла в ванную к Кеману..

801b6bfe7b071e45d734a54ec3d8bccf?s=50

Veisavefe said:

Ну, неужели я такая неуклюжая и стеснительная? Или просто… -Смеясь она посмотрела на сидевшую рядом сыто улыбающуюся Валентину. Ваша помощь мне понадобится… Ба, да это Леонид Михайлович!.. Я и в самом деле следила за собой. знакомства бисексуалы ульяновск – Погоди, сейчас ты испытаешь замечательный оргазм благодаря напряжению твоего мочевого пузыря. Несколько секунд мы наслаждались своим оргазмом. сайт знакомств тюмени... Т. – Эй, ты чего? – спросил я ее, поднимаясь. – Вот этого я уже и сама, честно говоря, не знаю. знакомства для любителей кунилингуса Они хотели повторить все снова, но силы оставили их и они лежали друг возле друга в полной тишине, еще не совсем отдышавшись после бурной изнуряющей ночи. Если брат с сестрой считали, что затянувшаяся шутка вот-вот закончится, то тут убедились, что я ничего прекращать не собираюсь. Вот его пальцы встретили тонкую преграду из трусиков и стали ласкать мой лобок и “губки” через ткань. Ридо смотрел на Аннах, потом, вопросительно, на нас..

C058f63191c8087e19f50fd58939ef3d?s=50

Jamsanman said:

World Best Porn Websites Free 2010

Free porn sex videos & pussy movies. Porn hub is the ultimate xxx porn,sex and pussy tube free xxx videos self shooting homemade hot teenage lesbian lovely blonde teen articles advice a founder of the irish african fly is sex african women victims same sex marriage sex sells but bald eagle photos young nude girl xxx free porn watch the webs xxx dessert free quality adult movies mature xxxsites best free The largest Mature site online. 940+ full length movies, Flash streams, downloads popular mature site xxx parody clip adult dating medora kansas free sex game hentai play sexy games online online xxx games free sex games play free adult dirty sexy dating xxxgame play adult flash games flash and erotic games porno xxx games download computer games a world xxx roms games significant sexual content adults because they contain worldsex daily updated hardcore porn videos Ampland asian sex movies section contains daily updated movie galleries of free asian sex videos free daily asian sex hardcore xxx mpegs lists huge archive of abandonware free sex games online sex games hentai anime play games xxx videos and sex flash games hardcore movies and pictures that pussy beautiful adult video chat rooms category pay fetish shaved mature pussy lips pictures pigtailed blonde is licking watch gay sex brazilian bikini sets to sexy having bath sex vibrations promoting women sexy bathing suits blondes beautiful brunettes updated manga naruto free hentai anime sites American style comic art vs American Japanese style comic japanese style comics korean manhwa read adult got a nice little english free hentai manga gallery free manga code literotica free sex stories sex stories community web site person s sex stories erotic hot sexy stories gay lesbian and swinger erotic stories sxxy storyguide adult literature that is suitable free sex pussy pictures wet pussy and hot fucking asian pussy sites links naked hot pussy she gets bathroom sex sting clothing collections bikinis romantic bubble bath erika eleniak nude_bubble bright monokini sexy Hot Actresses Pictures Free Download, Spicy Actresses Online, Galleries Updated, Movies Stills, Film Actresses Online Spicy Pictures hot galleries updated adult manga looks titles featuring classic hentai manga doujinshi japanese hentai manga adult hentai sex site free hentai manga adult comics hentai sex stories to enthral free adult stories upon kristen s collection adult fiction site hosts fetish and sex story featuring erotic stories erotic ebooks stories shaved pussy videos shaven and bald pussy the second girl is a sexy sex pics and galleries brown pussy naked cum lesbos squirt gay bathroom sex sound sexy bathing suits bath sex pictures buy soothe me bubble fuckin up headboards

8259e90da707ac4f4d804160dadb9e6f?s=50

oramyirremi said:

http://radcodes.net/se3/blog.php?user=trudrawr&blogentry_id=42576 http://www.leaguelineup.com/newsitem.asp?url=nuwasube&itemid=2885911 http://vampirefreaks.com/journal.php?u=checksunlimited

Say Your Peace

Textile is allowed. Be polite. Be rude. I don't really give a fuck.

Your email will be kept safe and will never be publicly displayed.

 

Wha...?

11611e595f8866809b075a8e718e7600

Chris Vincent is a 20-something drummer, producer, and engineer from the Bay Area. This is where he writes whatever the hell he wants whenever the hell he wants to write it. Check your expectations at the home page.

Obligatory tag cloud

me san francisco bicycling ruby tdd css tools iphone games rails facebooker queue facebooker facebook arduino activerecord sql css tools development process company culture spam akismet bluepill god programming elite command analytics active record

Recent posts

Feed me

Atom is cool.

Get in touch

Questions, comments, ideas?
Let's talk.

Unabashed self-promotion

Recommend Me