2009-07-05 31 views
1

我正在使用一个略有奇怪的表命名约定的传统oracle数据库,其中每个列名都以表首字母为前缀,例如policy.poli_id。在生产模式下Rails依赖关系问题

为了使这个数据库更容易工作我有一个方法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),并需要从我到config/environment.rb后的Rails :: Initializer.run块。

这在发展一直工作正常,但是当我尝试运行在生产模式下的应用程序,我得到了我的所有车型以下错误:

[email protected]:~/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 

此错误是由“配置触发.cache_classes = true'config/environments/production.rb中的行。 如果我将此设置为false,那么rails将启动,但不会缓存类。我猜这使得轨道缓存所有的模型,然后它运行初始化程序块

如果我将'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的文件已加载?

干杯

戴夫Smylie

回答

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 
+0

Thanks guys。这似乎解决了这个问题。 – 2009-07-05 22:35:39