lib/rails-settings/base.rb in rails-settings-cached-2.1.1 vs lib/rails-settings/base.rb in rails-settings-cached-2.2.0

- old
+ new

@@ -4,11 +4,11 @@ module RailsSettings class Base < ActiveRecord::Base class SettingNotFound < RuntimeError; end - SEPARATOR_REGEXP = /[\n,]+/ + SEPARATOR_REGEXP = /[\n,;]+/ self.table_name = table_name_prefix + "settings" # get the value field, YAML decoded def value YAML.load(self[:value]) if self[:value].present? @@ -28,10 +28,12 @@ RequestStore.store[:rails_settings_all_settings] = nil Rails.cache.delete(self.cache_key) end def field(key, **opts) + @keys ||= [] + @keys << key.to_s _define_field(key, default: opts[:default], type: opts[:type], readonly: opts[:readonly], separator: opts[:separator]) end def cache_prefix(&block) @cache_prefix = block @@ -41,15 +43,20 @@ scope = ["rails-settings-cached"] scope << @cache_prefix.call if @cache_prefix scope.join("/") end + def keys + @keys + end + private + def _define_field(key, default: nil, type: :string, readonly: false, separator: nil) if readonly define_singleton_method(key) do - self.send(:_covert_string_to_typeof_value, type, default, separator: separator) + self.send(:_convert_string_to_typeof_value, type, default, separator: separator) end else define_singleton_method(key) do val = self.send(:_value_of, key) result = nil @@ -58,20 +65,20 @@ else result = default result = default.call if default.is_a?(Proc) end - result = self.send(:_covert_string_to_typeof_value, type, result, separator: separator) + result = self.send(:_convert_string_to_typeof_value, type, result, separator: separator) result end define_singleton_method("#{key}=") do |value| var_name = key.to_s record = find_by(var: var_name) || new(var: var_name) - value = self.send(:_covert_string_to_typeof_value, type, value, separator: separator) + value = self.send(:_convert_string_to_typeof_value, type, value, separator: separator) record.value = value record.save! value @@ -83,23 +90,27 @@ self.send(key) end end end - def _covert_string_to_typeof_value(type, value, separator: nil) - return value unless value.is_a?(String) || value.is_a?(Integer) + def _convert_string_to_typeof_value(type, value, separator: nil) + return value unless [String, Integer, Float, BigDecimal].include?(value.class) case type when :boolean - return value == "true" || value == "1" || value == 1 || value == true + value == "true" || value == "1" || value == 1 || value == true when :array - return value.split(separator || SEPARATOR_REGEXP).reject { |str| str.empty? } + value.split(separator || SEPARATOR_REGEXP).reject { |str| str.empty? }.map(&:strip) when :hash - value = YAML.load(value).to_hash rescue {} + value = YAML.load(value).to_h rescue eval(value).to_h rescue {} value.deep_stringify_keys! - return value + value when :integer - return value.to_i + value.to_i + when :float + value.to_f + when :big_decimal + value.to_d else value end end