Module: SettingAccessors::Integration::ClassMethods

Defined in:
lib/setting_accessors/integration.rb

Instance Method Summary collapse

Instance Method Details

#setting_accessor(setting_name, options = {}) ⇒ Object

Generates a new accessor (=getter and setter) for the given setting

Parameters:

  • setting_name (String, Symbol)

    The setting’s name

  • options (Hash) (defaults to: {})

    Options to customize the behaviour of the generated accessor

Options Hash (options):

  • :fallback (Symbol, Object) — default: nil

    If set to :default, the getter will return the setting’s default value if no own value was specified for this record

    If set to :global, the getter will try to find a global setting if no record specific setting was found

    If set to another value, this value is used by default

    If not set at all or to nil, the getter will only search for a record specific setting and return nil if none was specified previously.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/setting_accessors/integration.rb', line 38

def setting_accessor(setting_name, options = {})
  #If the database table does not yet exist,
  return unless self.table_exists?

  fallback = options.delete(:fallback)

  SettingAccessors::Internal.set_class_setting(self, setting_name, options)

  #Create a virtual column in the models column hash.
  #This is currently not absolutely necessary, but will become important once
  #Time etc. are supported. Otherwise, Rails won't be able to e.g. automatically
  #create multi-param fields in forms.
  self.columns_hash[setting_name.to_s] = OpenStruct.new(type: SettingAccessors::Internal.setting_value_type(setting_name, self.new).to_sym)

  #Add the setting's name to the list of setting_accessors for this class
  SettingAccessors::Internal.add_setting_accessor_name(self, setting_name)

  #Getter
  define_method(setting_name) do
    settings.get_with_fallback(setting_name, fallback)
  end

  # Setter
  define_method("#{setting_name}=") do |new_value|
    settings[setting_name] = new_value
  end

  #NAME_was
  define_method("#{setting_name}_was") do
    settings.value_was(setting_name, fallback)
  end

  #NAME_before_type_cast
  define_method("#{setting_name}_before_type_cast") do
    settings.value_before_type_cast(setting_name)
  end

  #NAME_changed?
  define_method("#{setting_name}_changed?") do
    settings.value_changed?(setting_name)
  end
end