Ruby (Rails) constant lookup precedence

Recently I’ve been running into an interesting problem (at least, to me). Within a web application I am working on I found what I thought was a sporadic error occurring, which resulted in the need to restart Apache in order to temporarily fix it. That was, until I made a change to the controller and thus the issue appeared again, until I restarted Apache. The error:

uninitialized constant Frontend::User::ForgottenPasswordController::User

This puzzled me for quite a while, but I continued to develop while every now and again I would come up against this and look for answers. I found nothing, but knew the following:

  • User constant (model class) exists and works fine
  • This only happened in specific controllers

Jumping onto and having a chat with `workmad3` we solved the problem, and it’s a pretty simple one, once you understand how Ruby and thus Rails references constants. Continue reading

Regex: Split on uppercase

If you need to split a string based on uppercase values, for example “ComputeAsAService” in order to provide a readable string “Compute As A Service” you can do so simply by using regular expressions, in particular you can use the lookahead operator “?=”.

str = "ComputeAsAService"
parts = str.split(/(?=[A-Z])/)
>> ["Compute", "As", "A", "Service"]

Continue reading

5 Useful PHP to Ruby methods

When I first started writing in ruby I found myself needing to know the ruby method equivalents to specific PHP functions. These methods are widely used by myself for debugging and day to day checking of data types.

PHP’s die(‘message’) becomes

abort 'message'

PHP’s get_class_methods() becomes


PHP’s in_array() becomes

array.include? 'item'

Continue reading

When to use single quotes and double quotes

If you are familiar with PHP you will know that strings can be contained within single quotes or double quotes. More often than not developers tend to always use double quotes, despite the context of the string.

While this is OK in principle, double quotes take more processing time than that of single quotes (despite being minimal). This is because PHP expects to find variables within double quoted strings and parse them. Continue reading

7 tips to prevent PHP running out of memory

Is the following error familiar to you?

Fatal error: Allowed memory size of XXX bytes exhausted

It is to me, and recently I’ve written an import script that reads the contents of 10 XML files. These files accumulate a total of 14.9MB in size. The XML files contain page content (A good 10,000), each page has references to images and PDFs which needed to be downloaded, stored on the filesystem in the same directory structure as well as imported into an asset manager, again in the same structure. Once the assets have been downloaded the script stores the contents of the XML files. Continue reading