Question

In a Ruby on Rails 3.2.12 project I want to store data for a model in static files.

I don't need to be able to write to the data through the app, and want to handle updating and adding new objects by changing the static file(s).

Is there a way to set up a model, and then say "look at this file (or folder) to find the records", rather than the database (the app also has a database)?

I can imagine the data being stored in two main ways:

  1. all the records are kept in a .json or .yml file
  2. each record is kept in an individual .yml or .markdown file, inside a specific folder (as in jekyll).

Examples: a glossary

My application has a glossary. Each entry in the glossary should be an individual record.

There will be a glossary index page (/glossary) that is just like your standard glossary, listing all the terms and definitions. Each individual record(term + definition) also needs to be individually retrievable for use in footnotes on other pages.

I want people to be able to edit the glossary by editing files through github. They could be pointed to a single file with all the records, or (preferably) an individual file with just the record they want to edit (less syntax to handle, less risk).

Key questions

  1. How do you point the model to the static data file, rather than the database?
  2. Where should the source directory be?
  3. What would be the best storage format?

Thanks very much for your help!

Was it helpful?

Solution

ActiveHash would be a good solution for this. You could use the ActiveYaml configuration if you would like to store the data in a separate yaml file instead of directly in the model.

OTHER TIPS

Unless someone comes up with a better solution or with a gem which can do this out of the box I would recommend building your own model with own find and save methods. Something like (untested):

class Term
  attr_accessor :name, :definition

  def self.find(name)
    YAML.load(File.read("#{name}.yaml"))
  end

  def save
    File.open("#{name}.yaml", 'w'){ |f| f.write(YAML.dump(self)) }
  end
end

The format for saving is up to you, see here or here for more info. Since you want the users to change the files I would go with whichever you find the most user friendly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top