在生产模式下,Rails依赖项会出现问题

时间:2009-07-05 21:28:05

标签: ruby-on-rails config production

我正在处理遗留的oracle数据库,其中有一个稍微奇怪的表命名约定,其中每个列的名称都以表格的前缀字母为前缀 - 例如policy.poli_id。

为了使这个数据库更容易使用我有一个方法set_column_prefix,它为删除了前缀的每一列创建访问器。即:

# Taken from wiki.rubyonrails.org/rails/pages/howtouselegacyschemas
class << ActiveRecord::Base
  def set_column_prefix(prefix)
    column_names.each do |name|
      next if name == primary_key

      if name[/#{prefix}(.*)/e]
        a = $1

        define_method(a.to_sym) do
          read_attribute(name)
        end

        define_method("#{a}=".to_sym) do |value|
          write_attribute(name, value)
        end

        define_method("#{a}?".to_sym) do
          self.send("#{name}?".to_sym)
        end

      end
    end
  end
end

这是在我的lib /目录中的文件(insoft.rb)中,并且是在Rails :: Initializer.run块之后从我的config / environment.rb中获取的。

这在开发中运行良好,但是当我尝试在生产模式下运行应用程序时,我在所有模型中都出现以下错误:

dgs@dgs-laptop:~/code/voyager$ RAILS_ENV=production script/server 
=> Booting Mongrel
=> Rails 2.3.2 application starting on http://0.0.0.0:3000
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/base.rb:1964:in `method_missing': 
undefined method `set_column_prefix' for #<Class:0xb3fb81d8> (NoMethodError)
    from /home/dgs/code/voyager/app/models/agent.rb:16

此错误由config / environments / production.rb中的“config.cache_classes = true”行触发。 如果我将其设置为 false ,则rails将启动,但不会缓存类。我猜这会让rails在运行Initializer块之前缓存所有模型

如果我将'require'insoft.rb'“移到Rails :: Initializer.run块的开头之前,那么我会收到错误,因为ActiveRecord尚未初始化:

usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:443:in `load_missing_constant': uninitialized constant ActiveRecord (NameError)
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:80:in `const_missing'
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:92:in `const_missing'
    from /home/dgs/code/voyager/lib/insoft.rb:1

我应该在哪里包含这个自定义lib和set_column_prefix方法,以便在缓存模型之前拾取它,但是在加载了所有的activerecord文件之后?

干杯

Dave Smylie

1 个答案:

答案 0 :(得分:2)

  

我应该在哪里包含这个自定义lib和set_column_prefix方法,以便在缓存模型之前拾取它,但是在加载了所有的activerecord文件之后?

尝试设置initializer。您可以使用猴子补丁的内容将其命名为config / initializers / insoft.rb:

class << ActiveRecord::Base
  def set_column_prefix(prefix)
    column_names.each do |name|
      next if name == primary_key

      if name[/#{prefix}(.*)/e]
        a = $1

        define_method(a.to_sym) do
          read_attribute(name)
        end

        define_method("#{a}=".to_sym) do |value|
          write_attribute(name, value)
        end

        define_method("#{a}?".to_sym) do
          self.send("#{name}?".to_sym)
        end

      end
    end
  end
end