Search code examples
ruby-on-railsactiverecordstore

ActiveRecord::Store with default values


Using the new ActiveRecord::Store for serialization, the docs give the following example implementation:

class User < ActiveRecord::Base
  store :settings, accessors: [ :color, :homepage ]
end

Is it possible to declare attributes with default values, something akin to:

store :settings, accessors: { color: 'blue', homepage: 'rubyonrails.org' }

?


Solution

  • No, there's no way to supply defaults inside the store call. The store macro is quite simple:

    def store(store_attribute, options = {})
      serialize store_attribute, Hash
      store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
    end
    

    And all store_accessor does is iterate through the :accessors and create accessor and mutator methods for each one. If you try to use a Hash with :accessors you'll end up adding some things to your store that you didn't mean to.

    If you want to supply defaults then you could use an after_initialize hook:

    class User < ActiveRecord::Base
      store :settings, accessors: [ :color, :homepage ]
      after_initialize :initialize_defaults, :if => :new_record?
    private
      def initialize_defaults
        self.color    = 'blue'            unless(color_changed?)
        self.homepage = 'rubyonrails.org' unless(homepage_changed?)
      end
    end