mahatmanich
mahatmanich

Reputation: 11023

Changing YAML file without restarting Rails 4

I want to be able to edit a YAML file and reload it in a Rails 4 app. Right now I am loading the YAML file via an initializer, and I know that this will load the file only once and a restart will be required after changing it.

How could I accomplish a YAML reloading/refreshing as it is accomplished via i18n YAML files in Rails?

Upvotes: 2

Views: 2777

Answers (3)

bbozo
bbozo

Reputation: 7301

You can try something in the lines of checking for file's change time, for example:

module MyFileReader
  def self.my_yaml_contents
    if @my_yaml_file_ctime != File.ctime(file_name)
      @my_yaml_contents = YAML.load(File.open(file_name))
      @my_yaml_file_ctime = File.ctime(file_name)
    end
    @my_yaml_contents
  end
end

MyFileReader.my_yaml_contents method will load and parse the file only on startup and change and serve the already parsed data in the meantime,

see http://www.ruby-doc.org/core-2.0.0/File.html#method-c-ctime

Upvotes: 2

Simone Carletti
Simone Carletti

Reputation: 176412

When you load the file, I assume you assign it to some variable or constant. If instead you don't assign it, then the load will be performed every time.

Instead of:

CONTENT = Yaml.load_file('your_file.yml')

create a simple class or function:

module YourFileReader
  def self.load
    Yaml.load_file('your_file.yml')
  end
end

and use the defined method to read the file in your app

YourFileReader.load

or even simpler, use

Yaml.load_file('your_file.yml')

directly in your app where you need to read the file.

Upvotes: 1

Thaha kp
Thaha kp

Reputation: 3709

Instead of require use load to load the file.

require will load files only once. But load will load when it is called.

See more about this here http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/

Upvotes: 0

Related Questions