Archive for January, 2008

Why I hate ActiveRecord – part II (validation)

January 25, 2008

Everybody using Rails probably knows that ActiveRecord provides many methods for declaring validation of records – the validate method as well as validates_xxx methods which generate code for most common validation tasks. There is a problem though…

The validation can be easily skipped. Just use the update_attribute method and you can set any values without validation. Kinda scary if you’re used to encapsulating consistency checks in model – some other coder writing controllers for your model can just break your rules…

Just one more reason to ignore DHH’s words on moving validation to application layer and putting it back in database (where it should always be, even if you have the rules in your application layer too; skip consistency checks provided by the RDBMS only if they are too complicated to be effectively expressed with SQL or you’re using RDBMS with limited capabilites in this regard, like MySQL or SQLite)

Threading in RoR 2.0.2

January 12, 2008

We’re working on a project using Ruby on Rails 2.0.2 currently.

As you probably know, RoR is not thread-safe. But even if you are not using ActiveRecord, ActionPack nor any other Rails part you still might run into some problems if you thread.

We use the probably most common setup – small loop launching threads to query some web services in parallel. This seemed safe, as it would not use any of RoR classes/modules.

Now here’s the gotcha – automatic constant resolver (part of ActiveSupport) that loads classes from properly named files. It’s a part of RoR too…. and has threading problems, just like the rest of RoR. If a constant is not known before the threads launched, every thread would try to load that constant on its own; only the first thread would succeeded, all the other would raise “constant X is not unknown” exception.

Currently we worked this around by requiring files defining all dependencies in the file that launches the thread before going parallel. It’s ugly and not easily maintainable, as threads use different functions, each with it’s own dependencies – but it works, for now.

Perhaps it’s time to port that project to python – it has proper thread support (not to mention the fact that I wouldn’t have to deal with RoR worst part, that is ActiveRecord – SqlAlchemy is way better)