byroot / activerecord-typedstore

ActiveRecord::Store but with type definition
MIT License
439 stars 57 forks source link

Dynamic settings #46

Closed jfilipe closed 7 years ago

jfilipe commented 7 years ago

Hey there, First off let me say this is a great library.

I'm curious if you can recommend a way of defining dynamic settings per instance. My use case is to expose a subset of user settings that are defined from a larger pool of predefined team settings.

i.e.

class UserSetting < ActiveRecord::Base
  belongs_to :user
  belongs_to :team

  after_initialize :build_preferences_from_available_team_settings

  def build_preferences_from_available_team_settings
    # Instead of a hardcoded array, this would be retrieved from the database
    team_settings = [{ setting_name: "enable_awesome_feature", setting_default: false }]

    self.class.typed_store :preferences, coder: JSON do |s|
      team_settings.map do |ts|
        s.boolean ts[:setting_name].to_sym, default: ts[:setting_default], null: false
      end
    end
  end
end

The above works, however because it's changing the global class, all future instances of UserSetting are populated with incorrect preferences. I've tried playing around with singleton_class however I'm curious if there's a better way to go about this.

Thanks!

byroot commented 7 years ago

The store definition is shared for all the instances of a class, so no, you can't define them dynamically on an instance basis.

The closest thing I can think of is STI: http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html