Rails :: Railtie: problem creating Rails 3 gem

I could use another set of eyes, so I thought I'd post it here. Some time ago, I wrote a basic ActiveRecord extension for my own educational purposes. Recently I read about railways and thought that I would try to get it to work with Rails 3. I thought I would pack it like a gem to understand this process. If I skip Railtie and just do it like a traditional monkeypatch in the initialization folder, it works fine. Using Railtie ... nothing.

In appearance, my Railtie never performed, and so nothing else seems to be happening.

Does anyone see something wrong here?

Any suggestions for best practices or improvements are also welcome.

project gemfile:

gem 'sql_explain', :path => "/home/mike/projects/sql_explain/" 

gemspec:

 ... spec.files = %w(README.rdoc sql_explain.rb lib/sql_explain.rb lib/railtie.rb sql_explain.gemspec) ... 

sql_explain.rb

 require 'lib/railtie.rb' 

railtie.rb

 require 'active_record' require 'sql_explain' module SqlExplain class Railtie < Rails::Railtie railtie_name :sql_explain initializer 'sql_explain.extend.activerecord' do if defined?(ActiveRecord) ActiveRecord::ConnectionAdapters::MysqlAdapter.include SqlExplain::AR end end end end 

sql_explain.rb

 module SqlExplain module AR def self.included(base_klass) base_klass.send :alias_method_chain, :select, :explain end def select_with_explain(sql, name = nil) @connection.query_with_result = true result = execute('explain ' + sql, :skip_logging) rows = [] result.each_hash { |row| rows << row } result.free @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped exp_string = "" rows.each{|row| row.each_pair{|k,v| exp_string += " #{k}: #{v} |"}} log(exp_string, "Explanation") {} select_without_explain(sql, name) end end end 
+4
source share
2 answers

It sounds like you've already figured it out, but remember that with Rails 3 you can do:

 ActiveSupport.on_load :active_record do ActiveRecord::ConnectionAdapters::MysqlAdapter.include SqlExplain::AR end 

This ensures that your power on will only be launched after ActiveRecord is loaded.

+3
source

Are you sure this is true?

 if defined?(ActiveRecord) 

I believe this is not true. Instead of "rails" try to require "rails / all" - the first does not load AR.

+1
source

All Articles