lib/rails-settings/base.rb in rails-settings-cached-2.4.1 vs lib/rails-settings/base.rb in rails-settings-cached-2.5.0
- old
+ new
@@ -26,11 +26,11 @@
RequestCache.reset
Rails.cache.delete(cache_key)
end
def field(key, **opts)
- _define_field(key, default: opts[:default], type: opts[:type], readonly: opts[:readonly], separator: opts[:separator])
+ _define_field(key, default: opts[:default], type: opts[:type], readonly: opts[:readonly], separator: opts[:separator], validates: opts[:validates])
end
def get_field(key)
@defined_fields.find { |field| field[:key] == key.to_s } || {}
end
@@ -57,11 +57,11 @@
@defined_fields.select { |field| field[:readonly] }.map { |field| field[:key] }
end
private
- def _define_field(key, default: nil, type: :string, readonly: false, separator: nil)
+ def _define_field(key, default: nil, type: :string, readonly: false, separator: nil, validates: nil)
@defined_fields ||= []
@defined_fields << {
key: key.to_s,
default: default,
type: type || :string,
@@ -93,12 +93,21 @@
record = find_by(var: var_name) || new(var: var_name)
value = send(:_convert_string_to_typeof_value, type, value, separator: separator)
record.value = value
- record.save!
+ record.save(validate: false)
value
+ end
+
+ if validates
+ validates[:if] = Proc.new { |item| item.var.to_s == key.to_s }
+ send(:validates, key, **validates)
+
+ define_method(:read_attribute_for_validation) do |_key|
+ self.value
+ end
end
end
if type == :boolean
define_singleton_method("#{key}?") do