有没有办法为rails app自动重新加载初始化程序?

时间:2013-08-28 20:34:04

标签: ruby-on-rails ruby-on-rails-4

我现在正在使用RailsAdmin。

RailsAdmin DSL配置存储在初始化程序中。有一种方法可以将它们保留在模型中,但我认为这是一个坏主意(在模型中存储与视图相关的信息)。

所以,每当我必须更改它时,我必须重新启动rails服务器,这非常烦人。

有没有办法为初始化程序启用自动加载?

2 个答案:

答案 0 :(得分:1)

详见文档here

在您的/config/initializers/rails_admin.rb中,您应该添加config.parent_controller = ApplicationController.to_s

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :reload_rails_admin if :rails_admin_path?

  private

  def reload_rails_admin
    models = %W(User UserProfile)

    models.each do |m|
      RailsAdmin::Config.reset_model(m)
    end

    RailsAdmin::Config::Actions.reset

    load("#{Rails.root}/config/initializers/rails_admin.rb")
  end

  def rails_admin_path?
    controller_path =~ /rails_admin/ && Rails.env == "development"
  end

end

它确实感觉非常hacky,我喜欢听到更好的选择。

答案 1 :(得分:0)

添加此文件 config/initializers/rails_admin_reload.rb

# See also: https://github.com/sferik/rails_admin/wiki/How-to:-Reloading-RailsAdmin-Config-Automatically#alternative-method-for-the-railsadmin-versions-that-does-not-extend-applicationcontroller
Rails.application.config.to_prepare do
  RailsAdmin::ApplicationController.class_eval do
    before_action :reload_rails_admin, if: :reload_rails_admin? # Reloading RailsAdmin Config Automatically

    RAILS_ADMIN_FILE_PATH = "#{Rails.root}/config/initializers/rails_admin.rb"

    class << self
      def fetch_rails_admin_file_updated_time
        File::Stat.new(RAILS_ADMIN_FILE_PATH).mtime
      end
      attr_accessor :__file_timestamp
    end
    @__file_timestamp = fetch_rails_admin_file_updated_time

    def reload_rails_admin
      RailsAdmin::Config.reset

      load(RAILS_ADMIN_FILE_PATH)
    end

    def reload_rails_admin?
      return false unless Rails.env.development?
      begin
        file_updated_at = RailsAdmin::ApplicationController.fetch_rails_admin_file_updated_time
        has_changed = file_updated_at != self.class.__file_timestamp
        return has_changed
      ensure
        self.class.__file_timestamp = file_updated_at
      end
    end
  end
end