[ANN] setting_accessors 1.0 - A global key-value-store and database-persisted attribute accessors


(Stefan Exner) #1

Hey!

A while ago I wrote a small gem which let developers assign attributes to
ActiveRecord models which would
automatically be persisted in the database and generally behave like normal
column-based attributes.
It also included a generic persisted key-value-store which could validate /
type cast its entries based
on a global configuration.

While upgrading a big project that used it to Rails 5, it showed that some
of the mechanisms I used to
mimic ActiveRecord’s behaviour did no longer work due to framework changes.
I took this as an opportunity to almost completely refactor the whole gem
and especially extend
its test suite and Ruby/Rails versions to be tested against.

I found the gem useful for feature testing without having to migrate the
database all the time for
columns which could be removed again within a month. The accessors also
work great for storing
serialized data like Hashes or Arrays without having to define a new “text”
column.
Version 0.x [2] has been in active use for a few years now.

Maybe someone else finds it useful, if you have questions or comments,
everything’s welcome!

Cheers,
Stefan

[1] https://github.com/Stex/setting_accessors
[2] https://github.com/Stex/setting_accessors/tree/major_versions/0.x

Some usage examples:

# Global key-value-store
Setting.the_meaning_of_life = 42
Setting.the_meaning_of_life #=> 42

# Key-value-store within a certain assignable (AR record)
Setting[:the_meaning_of_life, universe1] = 42
Setting[:the_meaning_of_life, universe2] = 43
Setting.the_meaning_of_life(universe1) #=> 42
Setting.the_meaning_of_life(universe2) #=> 43

# Persisted attribute accessors
class MyModel < ActiveRecord::Base
  setting_accessor :my_string, type: :string, default: ‘Oiski’

  validates :my_string, presence: true
end

my_model = MyModel.new
my_model.my_string #=> ‘Oiski’
my_model.my_string = ‘Poiski’
my_model.save
my_model.reload.my_string = ‘Poiski'