简体   繁体   中英

Best way to store a global state for a Rails app?

I have a Rails app in which moderators can manage meetings and normal users can attend those meetings.

At some point, the admins should be able to "semi-freeze" the app. This is basically setting a period of time (let's call it a "Frozen Period") during which a few things happen:

  • as the meetings created before the frozen period starts will be included in a calculation soon, they cannot be edit ed during the frozen period.
  • moderators can continue to create new meetings and edit those meetings, as those new meetings won't affect the calculation.
  • warnings appear around the site explaining these issues.

In principle I could create a FrozenPeriod model, but I don't actually need to store several frozen periods at a time, as they are discarded once they are over.

Therefore, I'm looking for a "global state" type approach. This should still be stored in the database, but maybe without an associated model.

Does this make sense? Do best practices include a way of having a "singleton model" stored in the database, for example?

Create Model to save this settings to, and create only 1 record in migration:

class CreateFrozenPeriod < ActiveRecord::Migration
   def change
    create_table :frozen_periods do |t|
      t.boolean :active
    end
   end
  # create 1 record to store settings to.
  FrozenPeriod.create
end

Use this model as a singleton to set and get the value:

class FrozenPeriod 
   def self.active?
      FrozenPeriod.first.active
   end

   def self.active= val 
     FrozenPeriod.first.update_column(:active, val)
   end
end

You can also use Rails Settings Cached which do the same as above for you, and its good for extending models with settings.

I think that it will be good design to have a FreezePeriod model with the following attributes:

  • start_date
  • end_date

You can then write logic to check if there is currently an active freeze period.

Using this approach allows you to keep a history of freeze periods, and you can also schedule freezes in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM