ActiveRecord can be used as a stand-alone gem without going through a Rails app. When establishing a connection we must provide a name for the database. Here is an example where I use sqlite3 as a db engine. I want to provide a full path to the database also.
[code]
my_db_dir = '~/projects/myapp/db'
filename = File.join(my_db_dir,'development.sqlite3')
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => filename)
[/code]
On Ubuntu systems it is very likely that we will get an error
No such file or directory
I know the file is there. I know the path is correct. So what is wrong? The problem is the “~” character. ActiveRecord uses Ruby’s File.binread() method to read the file. The binread() method is a wrapper for a function in the c code (io.c) of the Ruby interpreter. When you dig deep into the source code of the Ruby project you will find the file.c file which contains a function for checking file paths for security related issues. This function is called rb_get_path_check().
Basically we should not pass a tilde character to File.binread(). It is something that will confuse you for many hours if you it!!
Here is a demonstration of the problem using interactive Ruby (irb).
[code]
$ irb
ruby-1.9.2-rc2 > File.binread("~/myfile.txt")
errno::ENOENT: No such file or directory - ~/myfile.txt
from (irb):1:in `binread'
from (irb):1
from /home/philip/.rvm/rubies/ruby-1.9.2-rc2/bin/irb:17:in `<main>'
ruby-1.9.2-rc2 > File.binread("/home/myuser/myfile.txt")
=> "This is the content of myfile... "
[/code]
You can see that the “~” character did not work.