ruby-on-railsmongodbconstantsmongoid3database

Constants in MongoDB using Moingoid


Are there any good common practices for storing project-wide constants in Mongodb via Mongoid? Is it even worth keeping them in the database?


Solution

  • Constants are, well, constants. Pi is a constant. You don't need a database for it, you know its value. But probably you meant something more like "A value that's pretty static and is unlikely to change often". If this is the case, then it indeed makes some sense to store those values in a DB. There are probably gems for this kind of stuff, but in vanilla Mongoid I'd do something like this:

    class Setting
      field :_id, type: String
      field :value
    
      def self.read_value name
        # return value or nil
        Setting.where(_id: name).first.try(:value)
      end
    
      def self.write_value name, value
        where(_id: name).upsert(value: value)
      end
    end
    
    # usage
    num_workers = Setting.read_value 'number_of_workers'
    Setting.write_value "upload_dir", '/var/www/uploads'