我真的需要另一双眼睛来看这个,所以我想我应该把它贴在这里。不久前,我为自己的教育目的写了一个基本的ActiveRecord扩展。我最近一直在读关于Railties的文章,我想我应该试着让它和Rails3一起工作,我想我应该把它包装成一个宝石,以了解这个过程。如果我跳过Railtie,只是在initializers文件夹中作为一个传统的monkeypatch,它工作得很好。使用火车..。没什么。
从它的外观来看,我的Railtie从未被执行过,因此似乎没有发生任何其他事情。
有没有人看到有什么不对劲?
任何关于最佳实践或改进的建议也是受欢迎的。
项目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
endsql_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发布于 2010-09-27 10:16:03
看起来你已经解决了这个问题,但请记住,使用Rails3你可以做到:
ActiveSupport.on_load :active_record do
ActiveRecord::ConnectionAdapters::MysqlAdapter.include SqlExplain::AR
end这将确保您的include只会在ActiveRecord加载后触发。
发布于 2010-09-14 04:58:43
你确定这是真的吗?
if defined?(ActiveRecord)我想这是假的。而不是"rails“,试着要求"rails/all”-第一个不是加载AR。
https://stackoverflow.com/questions/3702488
复制相似问题