Convert a check box value to a boolean

Most of the time when I create a model with a boolean attribute I don’t actually
use a boolean in the database. A popular example is published on a blog post,
being implemented via setting the publish_date.

This means that in Rails to use form_for you just need to define the accessors
on the model and everything should work, except it doesn’t because the form
returns “0” for false and “1” for true, as strings. A real ActiveRecord model
gets around this by converting the values to boolean before setting. Since it is
tedious to implement time and time again it is easy to just reuse the Rails
internal function.

ActiveRecord::ConnectionAdapters::Column.value_to_boolean("0")

=> false

ActiveRecord::ConnectionAdapters::Column.value_to_boolean(“1”)

=> true

Quick and easy!

Enjoy.

Rails snippet: Making a ActiveRecord model save fail

This is the start of bunch of (hopefully) regular small posts with snippets for ruby and
rails. It’s supposed to be about those little things I keep looking up again and
again.

so back to topic: Making a rails model save fail!

  1. Add something to the errors in the validation

https://gist.github.com/4574361.js

  1. Make a before_filter fail (eg. before_create, …)
    Return false in a before_filter, will cause the model save to fail

https://gist.github.com/4574343.js

My pet project: Todobadour

Todobadour

Todobadour has been my pet project for quite
some time now. I keep using it to try stuff, or whenever I need a rails app to
experiment with, like checking out rails4 or play with websockets and so on.
I actually started it quite a while back, but yesterday I decided maybe it is
actually useful to somebody else so I decided to push it up to heroku, clean it
up and make it ready to be used. So here it is! It a basic todolist, which can
be shared and is synced real-time, which is actually quite useful I guess, and in the end its all about learning something isn’t it?

Enjoy, drop a comment if you like.

Foreman and SOA services

For the longest time I was fighting the problem of having the problem that ease
of development setup and composing my apps of different services seemed to fight
each other, but recently I discovered not only one but actually 2 solutions,
Foreman with
Subcontractor as well as
Vagrant.

First a little background: Imagine a very basic app, which relies on another
service to provide some functionality, my always happy to jump in example would
be a rails app which relies on websockets via faye. Of course to develop
locally, which I always prefer, I need to run both on my machine or else the app
will not be fully functional. So far I’ve been always starting the faye server
and the rails app separately, and of course forgetting to start the push server
from time to time and wonder about failing integration tests. So much for the
setting now the solution(s).

First vagrant: It provides a virtualized environment to run the apps, and relies
on Virtualbox to do so. It’s pretty simple to setup a machine which has both
services running at boot which solves the problem. The issue I have with that
is that I am not sure if I am ready to take the performance hit to run
everything virtualized. Also developing in either the VM, and migrating my
vimrc between every project is not really feasible, and mounting is slow.

Foreman to the rescue, foreman allows you to package the whole setup of what
needs to be running to make your app work in one nice file, the Procfile. The
problem has been for me that running a second rack app inside foreman is not
really possible, but this is what subcontractor is for, it lets you
specify which separate ruby apps need to be running with which environment

Procfile.development

push: subcontract --chdir $PUSH_PATH --signal INT 
      -- env BUNDLE_GEMFILE=$PUSH_PATH/Gemfile bundle exec 
      rackup config.ru -s thin -E $PUSH_RACK_ENV -p $PUSH_PORT

This means that all you need to do is specifying all service dependencies in a
Procfile and that run

foreman start -f Procfile.development

This allows even complex service setups to be run as needed.

Enjoy!

ActiveRecordTranslatable, rails plugin to manage translations for ActiveRecord Models

Let’s face it translations are always a pain, be it managing po files for PHP
projects, or YAML files in Rails… Especially if the models in your
database contain some attributes being translated in different languages it
becomes hard to keep track of the translations, as well as managing the database
holding them.

Luckily Rails helps with that by providing I18n translations
across the board, and even supporting flexible backends for the translation
engine. Still if there are multiple attributes on models which
have to be provided in multiple languages, being different by model, I18n in its
basic form fails in my opinion. But the basics are already in place:

There also is the globalize gem, but
it didn’t quite fit what I needed, mainly since it stores the translations per
model, which makes it hard to provide a single interface to manage them. So I decided to roll my own and here it is,
ActiveRecordTranslatable.
The main goal was to integrate in the I18n backend itself so all available
translations can easily be found and contrasted to create an interface a group
managing translations can work in. For a basic usage just checkout the
Readme, or install
via rubygems

$ gem install activerecord_translatable

As always any remarks are highly welcome.

Enjoy

Using Rails ActiveResource via OAuth2

Exposing Resources via a REST interface can be a nice way to split-off certain
parts of a larger Rails application. To consume those,
ActiveResource has been a nice way to go
for quite some time now, and still is in my opinion even thought with Rails 4 it
will move to its own gem and be no longer tied to Rails Core (good or bad?).

One hurdle left is that in some cases resources are, or
should be protected. In this case working with OAuth2 for example is quite easy
the only thing needed is setting a header.

https://gist.github.com/3820532.js

The token obtained for example via Omniauth and then set in the Controller. So
thats it now using the Resource works just as using an ActiveRecord Model.

Fixing the restart for faye upstart foreman and thin

In a little test project of min I manage rails deployment by using a combination
of capistrano, upstart and foreman. This
means as soon as I run


$ cap deploy

foreman is exporting the current Procfile to upstart scripts and copies those
to the correct locations for deployment on my ubuntu server, to restart the app
after the deployment capistrano now runs


$ service APPNAME restart

This works perfectly fine as long as all services restart nicely, but I ran into
a problem while setting up faye to allow push in the
app. Now since there is a connection between thin (my appserver) and faye, thin
will not shutdown gracefully as soon as upstart tells it to, which in turn means
faye will not shut down as well… ok so my app server will take a lot of time
to restart which is not that nice. To get rid of this problem I created a small
rake task to shut down the thin servers before the restart phase, this fixes the
“deadlock” (not really a deadlock I know but oh well). So here it is

https://gist.github.com/3434628.js

Fill Database with ActiveRecord

Rails ActiveRecord is a quite powerfull tool even without Rails itself. Since it gets all the needed information from the Database it can actually be used for all kinds of operations on the Database itself via scripting. In a current project there was the need to generate a lot of data on a table to use for testing, since the table was modified during the testing it made sense to write a script which auto generates the data based on the current table configuration.

This can be achieved by leveraging ActiveRecord, like this

https://gist.github.com/3017432.js?file=argen.rb

This can be expanded to all kinds of SQL types by extending the mapping hash, as well as the needed data generate methods. By doing so it can incoperate also database specific types like hashes by identifying the via their characteristic SQL type, i.e. md5 hash is char(40).

Ruby render :action => “new” does not call new method…

… Even though I should know that It drove me crazy the last hour. It’s important to remember when using render in error handling with nested resources. The following actually does not work, since when calling render :action => “new” in the error handling, @b will not be set, an therefore render will fail (probably unless @b is not used at all)

https://gist.github.com/661956.js

It’s important to actually set @b in this case even though it is not actually needed for the create

https://gist.github.com/661962.js

Just nice to know, because it actually feels like calling a controller but it doesn’t.

Getting your test records made for you

For the longest time I’ve been working with fixtures in ruby for testing, until
I recently discovered the factory_girl_rails gem. Fixtures are nice, they
provide a constant set of data to rely on without having to write them all the
time. While for a lot of purposes fixtures are nice, if you need to create new
objects all the time it can be a chore to to so. Especially maintaining them can
become quite a lot of work, especially when having objects which are
interrelated. This is where factories come in. They provide a new object
whenever you need one. I myself am still pretty new to it but it is just so easy
to even model interrelated objects and using them for your tests without having
to worry about updating them, unless your data model changes, which should not
happen that often. So just as a quick introduction those a 2 models following a
:belongs_to, :has_many relationship.

http://gist.github.com/646058.js