Fixing MySQL and rubygem errors on a new rails 2.3.8 install
Anton Jenkins | March 13, 2011
I’ve been setting up a new MacBook Pro using rvm and gemsets to make it super easy to flick between different versions of rails and ruby (thanks Steve for this very useful post). I was aware that MySQL could be a problem if you get your architectures wrong so it’s important to download the 64 bit version of MySQL and that your ruby is also 64 bit. You can check that by using the following commands:
1 2 |
file `which ruby` file `which mysql` |
I was seeing x86_64 for both so everything was good.
I had already created a rails2.3.8 gemset using rvm and was ready to install the rails and mysql gems:
1 2 |
gem rails install -v 2.3.8 ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config |
However I was getting several errors. First off I couldn’t run the rails command because of this error:
1 |
uninitialized constant ActiveSupport::Dependencies::Mutex (NameError) |
And I couldn’t run my app because of this error in the passenger log:
1 |
uninitialized constant MysqlCompat::MysqlRes |
Fixing rails
Lets start with the rails command error. Turns out theres an incompatibility between rails 2.3.8 and recent versions of rubygems. The suggested fix is to upgrade to rails 2.3.11.
1 2 |
gem uninstall rails gem install rails -v 2.3.11 |
Obviously you’ll now need to go into your application and change your environment.rb to use 2.3.11…
1 2 |
# Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.11' unless defined? RAILS_GEM_VERSION |
And tells rails to update your application…
1 |
rake rails:update |
Once that’s done the first problem is fixed.
Fixing MySQL
I was still getting the MySQL error unfortunately. If you google the error you’ll get all sorts of explanations on how important getting the 64 bit architecture correct is when compiling the mysql gem. Well I’d done that!
I figured out the solution to my problem whilst checking out a ruby forum post on the issue. Some people on there were using symlinks to fix the issue but if you add your MySQL lib directory to your DYLD_LIBRARY_PATH then the problems go away. I’ve already been tinkering with my DYLD_LIBRARY_PATH as this environment variable is used for the Oracle instant client. So I simply opened up my .bash_profile and added the lib directory for MySQL:
1 |
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib |
And now everything works. I’ve got no idea why it was needed and I’m not sure why a small minority of people need this fix whereas most don’t, but there it is.
Fixing your oracle rails stack after upgrading to Snow Leopard
Anton Jenkins | October 06, 2009
The latest upgrade to OS X has proved a little fiddly for users of ruby. Any ruby gem that contains native code needs reinstalling so that this code can be recompiled to 64bit. You might think after doing that you are done and dusted…. but don’t forget your OCI8 library if you are using Oracle with your rails stack!
If you can’t start rails because of the following error then you will most likely need to recompile OCI8:
1 2 |
Missing these required gems: activerecord-oracle_enhanced-adapter |
Now I’m assuming you installed the ruby OCI8 library manually, as I detailed in my post on getting oracle and rails to play together. Try firing up irb and seeing if you can require oci8:
1 2 |
irb(main):002:0> require 'oci8' LoadError: no such file to load -- oci8lib |
There’s your problem – we need to reinstall the OCI8 library. To save you looking back to my previous post I’ve just copied the instructions below (and altered them slightly as a new version of the library is now out).
Step 1: Download ruby-oci8
Download the latest tarball from the ruby-oci8 rubyforge page to your ~/Downloads directory. At the time of writing the latest is version 1.0.6.
Step 2: Make and install ruby-oci8
If you’ve followed the instructions from part 1 then you should have your oracle instant client installed in /opt/oracle/instantclient. If you’ve not installed the instant client yet then scoot off to part 1 and perform those steps before going any further. If you’ve installed it somewhere different then you will need to amend the following commands where appropriate:
1 2 3 4 5 6 7 |
cd ~/Downloads tar xvzf ruby-oci8-1.0.6.tar.gz cd ruby-oci8-1.0.6 ruby setup.rb config -- --with-instant-client=/opt/oracle/instantclient make sudo make install |
Step 3: Test it
1 2 |
irb(main):001:0> require 'oci8' => true |
You should now be able to use rubygems to load the oracle_enhanced adapter:
1 2 |
irb(main):002:0> gem 'activerecord-oracle_enhanced-adapter' => true |
Fingers crossed your rails app should also work now.
String is a number?
Anton Jenkins | June 22, 2009
I’ve been fishing around to see if Ruby has any way of telling whether a String object contains a valid number. The is_a? method looked like it might be a winner for a little while…
1 2 3 4 5 |
>> 34.is_a?(Numeric) => true >> "rah rah".is_a?(Numeric) => false |
So far so good. But my number is going to be stored in a String, and is_a? doesn’t actually look at the value of the String, it just checks its type.
1 2 |
>> "34".is_a?(Numeric) => false |
Ah. Fail. String isn’t a numerical class so even though it contains a numerical string, it’s always going to fail that test.
What about to_i?
I found to_i a little too clever for my needs…
1 2 3 4 5 6 7 8 9 |
>> "34".to_i => 34 # All good so far... >> "34DFDF".to_i => 34 # Ah. Fail. |
I don’t know why I typed 34DFDF. Sounds like a scary bra size….
Rails Forum to the rescue
Next I found a thread on railsforum.com which showed how to make an is_numeric? method and I decided to take that idea and extend the Object class to include this method on all objects. The idea being you could go :
1 2 3 4 5 6 7 8 |
>> 34.is_numeric? => true >> "34".is_numeric? => true >> "34DFDF".is_numeric? => false |
That’s perfect, so let’s write it….
Writing an is_numeric? method
I’m going to extend the Object class with this method so that it’s available everywhere. I’m using this in a rails app so I wrote the following in lib/core_extensions/object.rb
1 2 3 4 5 6 7 8 9 |
# lib/core_extensions/object.rb module CoreExtensions::Object def is_numeric? true if Float(self) rescue false end end Object.send(:include, CoreExtensions::Object) |
What it’s doing is seeing if the Float class can instantiate an instance of itself with the value of object. If object can’t be parsed to a Float then it throws an exception. If an exception is rescued then we know the object can’t be numerical so we return false. Simples.
Now we just need to require our little extension at the end of our environment.rb:
1 2 3 |
# config/environment.rb require 'core_extensions/object' |
... and we’re ready to go!
1 2 3 4 5 6 7 8 |
>> 34.is_numeric? => true >> "I'm not a number".is_numeric? => false >> "34".is_numeric? => true >> "34DFDF".is_numeric? => false |
Perfect.
Why extend Object and not String?
I had a ponder about that and figured it wouldn’t hurt if is_numeric? was called on non strings. By extending Object I can do things such as 34.is_numeric? which isn’t too shoddy. And I’m guessing if something nasty happens the rescue should catch anything bad. But if you can think of a good case for making it a String only method then please feel free to comment.
Also if there’s a better way of checking for numericalness then please post that in the comments. I couldn’t find anything built in to Ruby but I must admit I found that surprising.
Getting rails to play with a legacy Oracle database
Anton Jenkins | June 08, 2009
Just recently I’ve had to do a lot of work getting rails to play with a 15 year old Oracle database. Needless to say this database doesn’t follow the conventions we’ve all grown used to with rails. The table names are all over the place, the primary keys aren’t surrogate keys but actually have business meaning, composite keys which include date columns, crazy methods of generating primary keys instead of sequences….. if there’s a rails convention this thing doesn’t break then I’ve not found it yet!
However rails does provide methods for us to get it working with these legacy systems. Of course, if we were designing an application from scratch, we’d never need these techniques because we’d do it “the rails way” from the start. So I’m going to cover a couple of techniques which I’ve had to use in case you find yourself with the misfortune of having to marry rails to a pig!
Telling rails to use a different table and primary key
If we have a model named Student then rails convention dictates this model will map to a table called students and it will have a primary key called id. Well the real world isn’t always so accommodating. No problem…
1 2 3 4 |
class Student < ActiveRecord::Base set_table_name :student set_primary_key :s_stno end |
Composite keys
In this instance, the composite primary keys gem is your friend. Simply install…
1 |
sudo gem install composite_primary_keys |
... and require in your environment.rb...
1 |
require 'composite_primary_keys'
|
Now you are ready to start supplying multiple keys in your models…
1 2 3 4 |
class CourseFee < ActiveRecord::Base set_table_name "course_avail" set_primary_keys :course_code, :course_date end |
You may notice that one of those composite keys is a date. This can cause you problems when you try and generate a url for an instance of this class because the date won’t be output in the correct format. So we need to override the to_param method to output the date in database format.
1 2 3 |
def to_param "#{course_code},#{course_date.to_s(:db)}" end |
Non standard primary key generation
This one was tricky! Now it wouldn’t be too hard if your legacy system uses a sequence to generate primary keys because you can just tell rails to use this sequence if it’s not named using the rails convention (which is tablename_seq).
1 2 3 |
class Student < ActiveRecord::Base set_sequence_name 'a_non_standard_sequence_name' end |
However you could find yourself in a nasty situation where the database doesn’t use a sequence for primary keys – it uses a value stored in a table instead. No problem you’re thinking to yourself, I’ll just use a before_create hook to populate the primary key? Nope, not going to work. The oracle_enhanced adapter will still go off and try to use a sequence called tablename_seq causing the whole house of cards to come crashing down. So we need to stop oracle_enhanced from looking for this sequence and instead tell it to generate the primary key some other way.
I stole the basis of this hack from the oracle_enhanced website and added my own twist to it to fit my circumstances. I doubt your scenario will exactly match mine (and I hope for your sake it doesn’t!), but you can use this as a starting point.
So…. the primary keys in my evil system are stored in a table called counter. There is only one row in this table and a column for each table you want a primary key for. Nasty. So I started off by generating a model for this table with a method to pull out a primary key…
1 2 3 4 5 6 7 8 9 10 |
class Counter < ActiveRecord::Base set_table_name :counter def self.next_primary_key(col) current_value = Counter.first.read_attribute(col) new_value = current_value + 1 Counter.connection.execute("UPDATE counter SET #{col} = #{new_value}") new_value end end |
Now assuming there is a column in the counter table called student, I can pull a primary key out by calling:
1 |
Counter.next_primary_key('student') |
This will increment the value in the column and return it. It’s a nasty way to generate primary keys but hey, I didn’t design this!
So now we can access these primary keys in a tidy way we need to get our Student model to use it for its primary keys. And this is where the fun starts – we need to monkey patch the oracle_enhanced adapter to use this table, but only when our table doesn’t have a sequence. To do this we create an initialiser in config/initializers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# config/initializers/oracle_enhanced.rb ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.class_eval do alias_method :orig_next_sequence_value, :next_sequence_value def next_sequence_value(sequence_name) if sequence_name =~ /^counter-/ # Strip the counter- part out of the string and pass the remainder to next_primary_key Counter.next_primary_key(sequence_name.match("counter-(.*$)")[1]) else orig_next_sequence_value(sequence_name) end end end |
What this code does is check what the name of the model’s sequence is and if it starts with counter- it looks in the counter table for the primary key. So when we specify the following sequence name…
1 2 3 4 5 |
class Student < ActiveRecord::Base set_table_name :student set_primary_key :s_stno set_sequence_name 'counter-student' end |
... our little monkey patch will spot the counter- prefix, strip it out and make its primary key the result of a call to the following:
1 |
Counter.next_primary_key('student') |
Perfect! It’s a little complicated but we’ve now got a flexible solution to cater for whatever crazy method of primary key generation our predecessors may have dreamt up. And the best part is it gracefully falls back to the default behaviour if the sequence name doesn’t start with counter-.
As I said before, the main guts of this hack (the monkey patching of oracle_enhanced) was written by Raimonds Simanovskis on the oracle_enhanced website. I merely souped it up a little with some regular expressions and adopted it to fit my particular use case.
Further reading
If you are wondering how to setup rails to talk to an Oracle database then you might be interested in my previous two part series on the subject which starts with this post
Passing a hash of conditions to find in rails
Anton Jenkins | April 21, 2009
I just stumbled across a neat trick in ActiveRecord which could help make your code more readable:
1 2 3 |
User.find(:first, :conditions => { :forename => 'Anton', :surname => 'Jenkins', :age => some_value_from_a_form }) |
To me this is so much more readable than:
1 2 |
User.find(:first, :conditions => ["forename = ? AND surname = ? AND age = ?", 'Anton', 'Jenkins', some_value_from_a_form]) |
I know which one I prefer. I can’t believe I’ve never seen anyone using hashes for conditions before! Have I had my head in the sand?
Let me know if there are any gotchas with this technique. Maybe there is a good reason I’ve not seen it used before.











