Skip to content
This repository has been archived by the owner on Sep 25, 2020. It is now read-only.

Add preferential_settings, getter/setters, and optional encryption #5

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open

Conversation

erkattak
Copy link

@erkattak erkattak commented Apr 9, 2014

This adds a class method to all ActiveRecord::Base models that allows you to set "preferential settings".

Backstory:
We find it useful to be able to encrypt settings on our side when necessary. We also use this to set default values for settings after_create. In addition, we give each setting its own getter and setter method right on our model.

For example:

# config/initializers/redis_settings.rb
Redis::Settings.configure do |config|
  config.encryptor = MyEncryptor.new
  # You can make the encryptor anything you want, but it must be 
  # an object that responds to #encrypt!(value) and #decrypt!(value)
end
# some_model.rb
class SomeModel < ActiveRecord::Base
  self.preferential_settings = {
    external_api_key: {
      encrypted: true
    },
    report_template: {
      default: 'fancy_report'
    }
  }

  after_create :ensure_preferential_settings!
end

Now whenever I create a new SomeModel object, I get the following

obj = SomeModel.create!
obj.settings.all
#=> { report_template: 'fancy_report' }
obj.report_template = 'different_template'
obj.report_template
#=> 'different_template'
obj.external_api_key = 'super secret' #=> will be encrypted at rest
obj.settings.all
#=> { external_api_key: 'super secret', report_template: 'different_template' }

I've also added a settings= method, so you can do the following:

obj.settings = {
  report_template: 'another_style',
  external_api_key: '123xyz',
  something_else: 'anything I want' }
obj.settings.all
#=> { external_api_key: '123xyz', report_template: 'another_style', something_else: 'anything I want' }

You can still use settings where the key is not in preferential_settings, they just don't get accessor methods, so they're used as you normally would before these changes.

While you can also write validations for the new accessor methods provided by preferential settings, there is not yet any code around enforcing them. This means that if I did the following:

class SomeModel < ActiveRecord::Base
  self.preferential_settings = {
    fine_fee: {
      default: 12500
    }
  }

  validates_numericality_of :fine_fee, only_integer: true
end

The validations would run, but not be enforced. An example:

obj = SomeModel.create!
obj.fine_fee
#=> 12500
obj.fine_fee = 'invalid value'
obj.valid?
#=> false
obj.fine_fee # already persisted to Redis at this point, even though it's invalid
#=> 'invalid value'

I hope to add code around this in an upcoming PR

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants