Rails Database Connection with Block

Posted on December 4th, 2008

I found myself needing to very quickly connect to an alternate database that was defined in my database.yml like so:

alternate_data:
    adapter: mysql
    database: alternate_database
    username: user
    password: pass
    host: localhost

I was accessing it with something similar to the following:

ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["#{state}_data"])
results = connection.execute description_params[:extraction_sql];
#This wasn't actually hard coded, but this is just an example
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["development"])

The problems with this was that I had to repeat this ugly code everywhere, and if there was an exception thrown while accessing the alternate database it would not revert back to the original before exiting.  So the next request to the server thought the default database was the alternate database.  What I decided would be useful would be to have an “establish_connection” method that accepted a block and handle these issues.

(more…)

Rails Caching: Dynamic Fragments

Posted on December 3rd, 2008

I am finally getting around to implementing caching on my Rails application that I’ve been working on adamantly for the past couple of months.  For the time being, I am using a memcached server with simple action and page caching.  I ran into a few problems with my first few attempts at fragment caching and decided it wasn’t really necessary for the time being.  I needed a simple method of including small sections of dynamic code in an otherwise static page.  I then wanted to use action caching on the resulting view.  I’ll outline a simple method I used to achieve this.

(more…)

© Chasing • Powered by Wordpress • Using the Swiss Cool theme.