snax

make camping connect to mysql

By default, Camping connects to a sqlite database in an undisclosed location, similar to Dick Cheney. This confuses practically everybody. Here’s how to make your application use MySQL (or anything you have a Ruby binding for) when you are ready to move it to production.

update

Make sure to read the comments section.

preliminaries

You can’t change the database connection as long as you are using the camping command line tool. You have to bootstrap your app yourself.

This means that you have to be able to start it with ruby myapp.rb, because camping myapp.rb will never pay attention to your special configuration and continue to use a sqlite database. This database will either be the file .camping.db in your home folder on Unix-like systems, or the file camping.db in /Documents and Settings/{current_user}/Application Data/ on Windows, if I remember correctly.

with mongrel

With mongrel, you can make the harness be a postamble in your application’s main file.

put this at the end of your_app.rb
if __FILE__ == $0
  require 'mongrel/camping'

  YourApp::Models::Base.establish_connection :adapter => 'mysql',
    :database => 'camping_yourapp',
    :username => 'camper',
    :password => 'secret'
  YourApp::Models::Base.logger = Logger.new('your_app.log')
  YourApp::Models::Base.threaded_connections = false
  YourApp.create # only if you have a .create method
                 # for loading the schema

  server = Mongrel::Camping::start("0.0.0.0",80,"/", YourApp)
  puts "YourApp is running at http://localhost:80/"
  server.run.join
end

Now you can instantiate mongrels by executing your_app.rb directly, and proxy them through your webserver if necessary. Add a command-line switch to change the port if you need to instantiate a bunch of mongrels all at once.

Please also read this if you need multiple instances of your application to use a single sqlite database concurrently.

with fastcgi

If you are using fastcgi, be sure to put the harness in a separate file. If you don’t, you may get very strange superclass mismatch errors.

your_app_dispatch.rb
#!/usr/local/bin/ruby
require 'rubygems'
require 'camping/fastcgi'

Camping::Models::Base.establish_connection :adapter => 'mysql',
  :database => 'camping_yourapp',
  :username => 'camper',
  :password => 'secret'
Camping::FastCGI.serve("/path/to/your_app.rb")

Then your server can use your_app_dispatch.rb as the fastcgi executable.

Notice how the above uses Camping as the module name, and not YourApp. Also, we didn’t establish a log file here for Base, but we could, similar to the mongrel example.

done

That’s all. If your Camping app connects to Postgres instead of MySQL (:adapter => 'postgresql') you are officially hardcore.