Module: HasHelpers::HashAccessors

Defined in:
lib/has_helpers/hash_accessors.rb

Instance Method Summary collapse

Instance Method Details

#hash_attr_accessor(*attrs, source: :settings, **_options) ⇒ Object Also known as: setting_attr_accessor

Create accessors to root-level settings, where the settings is a Hash attribute, e.g. serialized Hash, JSON-column, etc.

When assigning a blank value (e.g. nil or "") the key corresponding to the accessor will be removed from the backing data store. There is currently no way to disable this.

source: The underlying Hash store for the accessor.

Examples

class ApplicationSetting extend HasHelpers::HashAccessors hash_attr_accessor :search_provider end

application_setting = ApplicationSetting.new
application_setting.settings                        #=> nil
application_setting.search_provider                 #=> nil

application_setting.search_provider = "::SQLSearch"
application_setting.settings                        #=> { "search_provider" => "::SQLSearch" }
application_setting.search_provider                 #=> "::SQLSearch"

Using the source option to override the default.

class Template
extend HasHelpers::HashAccessors
attr_accessor :colors
hash_attr_accessor :header_bg, :header_font, :source => :colors
end

template = Template.new
template.header_bg = "#011134"
template.header_font = "#CCC"
template.colors                  # => { :header_bg => "#011134", :header_font => "#CCC" }


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/has_helpers/hash_accessors.rb', line 41

def hash_attr_accessor(*attrs, source: :settings, **_options)
  attrs.each do |a|
    attr = a.to_s # Keys are only store as strings to ease compatibility with serializers.

    define_method(attr) do
      send(source)[attr] if send(source)
    end

    define_method("#{ attr }=") do |value|
      send("#{ source }=", {}) unless send(source)
      if value.blank?
        send(source).delete(attr) # Remove the key (attr) from the data store if the given value is blank.
      else
        send(source)[attr] = value
      end
    end
  end
end