Using hybriddb with a rails app - first thoughts
I just converted a few apps to use hybriddb instead of ActiveRecord and I thought I’d share the experience.
Overall it was easy with a few Gotchas. For info I was using Rails 2.1
To stop using ActiveRecord in your Rails app, do the following:
Add hybriddb.rb and the hybrid_db folder from the lib directory in the hybriddb download, into the lib folder in your Rails app.
Then modify environment.rb to: load hybriddb, tell rails not to load the ActiveRecord framework, and initialize the hybriddb connection. This required adding three lines:
#environment.rb
require File.join(File.dirname(__FILE__), 'boot')
require File.join(File.dirname(__FILE__), '../lib/hybriddb.rb') #Added
Rails::Initializer.run do |config|
config.frameworks -= [:active_record ] #Added
config.action_controller.session = { :session_key => "_xxxx", :secret => "xxxxxxxx" }
end
#Added the line below
HybridDB::Connection.set_adapter(MySQLAdapter.new({:host=> 'localhost', :user => 'sqllogin', :password => 'sqlpassword', :database => 'testapp' }))
DO NOT delete database.yaml as Rails bugs out if it is not present, even if you don’t use activerecord.
Change your models to inherit from HybridObject instead of ActiveRecord::Base.
Explicitly add attr_accessors (or your own getters, setters and instance variable initializers) for your object properties, I simply used the schema definitions as a basis for this.
Remove belongs_to statements, they are no longer needed, simply add a property to your object and set it to another object. HybridDb will take care of stubbing it and saving the related object if necessary.
Remove join table models and has_many :through, just use has_many to initialize HybridCollections.
Change any code that uses your_model_object.id to your_model_object.hybrid_id.
Change YourModelObject.find_by_xxx(‘foo’) to explicit YourModelObject.find(:first, :conditions => {:xxx = ‘foo’})
Thoughts:
It all worked well, I was actually surprised that it went so smoothly
It was weird not viewing data in the db but actually adding records for test etc. via script.console only
The foo.hybrid_id instead of foo.id property annoyed me so much that I might make id an alias for hybrid_id (possibly via a switch as I initially wanted users to be able to add an id property for models)
It’s nice to see all your properties listed as accessors in your models
You have to remember to add an indexes statement to your models if you want to do a find on a property.
I like doing all searching etc, in pure Ruby. Manipulating collections as Arrays is great.
I think I need to add object initialization from a hash like in ActiveRecord, I was avoiding this as I didn’t want to override initialize, but doing Foo.new(:name => ‘bar’, ;age => 99) is great shorthand.