本文介绍了Rails :: Railtie:无法创建Rails 3宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的可以使用另一套眼睛,所以我想我会在这里发布。
前一段时间,我为自己的教育目的编写了一个基本的ActiveRecord扩展。我最近一直在阅读关于Railties的文章,并认为我会试着让它与Rails 3一起工作。我想我会把它打包成一个宝石,以便了解这个过程。
如果我跳过Railtie,并且只是将它作为初始化文件夹中的传统monkeypatch,那么它工作正常。使用Railtie ...什么都没有。

I could really use another set of eyes on this so I thought I would post it here.A while ago I wrote a basic ActiveRecord Extension for my own educational purposes. I've been reading about Railties lately and thought I would try to get it working with Rails 3. I thought I would package it up as a gem to get a sense of that process as well.If I skip the Railtie and just do this as a traditional monkeypatch in the initializers folder it works fine. Using a Railtie... nothing.

从外观上看,我的Railtie从不执行,因此没有其他任何事情发生。

From the looks of it my Railtie is never executed and therefore nothing else seems to be happening.

有没有人在这里看到任何错误?

Does anyone see anything wrong here?

对于最佳实践或改进的任何建议也是受欢迎的。

Any suggestions for best practices or improvements are also welcome.

项目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

sql_explain.rb

require 'lib/railtie.rb'

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

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


推荐答案

已经得到了解决,但请记住,使用Rails 3你可以做到:

Looks like you've already got this sorted out, but remember that with Rails 3 you can do:

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

确保您的包含只会在ActiveRecord加载后触发。

That'll ensure that your include will only be fired once ActiveRecord has been loaded.

这篇关于Rails :: Railtie:无法创建Rails 3宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 02:19