Skip to content

Commit

Permalink
Fix #236 fallback to string type when used unsupported field type. …
Browse files Browse the repository at this point in the history
…Ref: #235
  • Loading branch information
huacnlee committed Jun 1, 2023
1 parent 8dc786f commit 3f66d44
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
14 changes: 10 additions & 4 deletions lib/rails-settings/fields/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ def saved_value
return parent.send(:_all_settings)[key] if table_exists?

# Fallback to default value if table was not ready (before migrate)
puts "WARNING: table: \"#{parent.table_name}\" does not exist or not database connection, `#{parent.name}.#{key}` fallback to returns the default value."
nil
puts(
"WARNING: table: \"#{parent.table_name}\" does not exist or not database connection, `#{parent.name}.#{key}` fallback to returns the default value."
)
nil
end

def default_value
Expand Down Expand Up @@ -62,8 +64,12 @@ def generate(**args)
private

def fetch_field_class(type)
field_class_name = type.to_s.split('_').map(&:capitalize).join('')
const_get("::RailsSettings::Fields::#{field_class_name}")
field_class_name = type.to_s.split("_").map(&:capitalize).join("")
begin
const_get("::RailsSettings::Fields::#{field_class_name}")
rescue StandardError
::RailsSettings::Fields::String
end
end
end
end
Expand Down
11 changes: 9 additions & 2 deletions test/base_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ class NewSetting < RailsSettings::Base
end

test "setting_keys" do
assert_equal 16, Setting.keys.size
assert_equal 17, Setting.keys.size
assert_includes(Setting.keys, "host")
assert_includes(Setting.keys, "readonly_item")
assert_includes(Setting.keys, "default_tags")
assert_includes(Setting.keys, "omniauth_google_options")

assert_equal 13, Setting.editable_keys.size
assert_equal 14, Setting.editable_keys.size
assert_includes(Setting.editable_keys, "host")
assert_includes(Setting.editable_keys, "default_tags")

Expand Down Expand Up @@ -365,6 +365,13 @@ class NewSetting < RailsSettings::Base
assert_equal %w[Ruby Rails GitHub], Setting.default_tags
end

test "unsupported type to string" do
assert_equal "hello", Setting.fallback_field

Setting.fallback_field = "bar"
assert_equal "bar", Setting.fallback_field
end

test "key with complex options" do
assert_equal %w[foo bar], Setting.key_with_more_options
field = Setting.get_field(:key_with_more_options)
Expand Down
1 change: 1 addition & 0 deletions test/dummy/app/models/setting.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,5 @@ def foo
end

field :key_with_more_options, type: :array, validates: {presence: true}, default: %w[foo bar], foo: 1, section: :theme
field :fallback_field, type: :foo_bar, default: "hello"
end

0 comments on commit 3f66d44

Please sign in to comment.