如何使用cattr_accessor在Rails初始化程序中定义配置

时间:2018-03-18 03:33:27

标签: ruby-on-rails

给定以下类(这是实际的类,没有其他代码)

class PageRepo
  cattr_accessor :root_path
end 

和初始化文件

PageRepo.root_path = Rails.root.join("content")

我跑的时候 rails console

PageRepo.root_path 
=> PageRepo.root_path
=> #<Pathname:/Users/blah/my_rails_app/content/pages>

但是当我尝试在rails控制器中访问它时,root_path值为 nil 。 (我用web_console检查了这个。)

没有其他类的子类或者是PageRepo类的父类,并且我没有在初始化阶段之后的类级别或实例级别将root_path设置为nil。我多次重启spring和我的服务器无济于事。

当涉及Rails初始化程序或cattr_accessor时,是否有一些我不知道的事情?

更新

我想设置这样的路径,因为在我的代码中,我将初始化一个PageRepo实例,路径不会改变。但是,它可能会在不同环境中发生变化。即在开发过程中,路径将与测试和生产环境的路径不同。虽然我可以做到

def initialize @root_path = ENV['ROOT_PATH'] end

我宁愿不强迫程序员使用ENV VARS来做这个,因此我的尝试就在上面。

1 个答案:

答案 0 :(得分:0)

我的解决方案是使用class方法

class PageRepo
  self.root_path
     Rails.root.join("content")
  end 
end 

PageRepo.root_path会返回#<Pathname:/Users/blah/my_rails_app/content/pages>

您想要#<Pathname:/Users/blah/my_rails_app/content/pages>吗?或者这取决于行动?

我相信您的初始化程序无效

一个有趣的post,你想要实现的是在class initializerconstructor

中写下这样的内容
class PageRepo
  self.initialize
     self.root_path = Rails.root.join("content")
  end 
end 

但我从来没有看到self.initialize与rails一起使用。所以我相信第一种方法更好。

相关问题