FEATURE: simpler definition of enum types

This commit is contained in:
Sam 2015-08-07 11:41:48 +10:00
parent a4a14e6d5a
commit fd63d89753
3 changed files with 25 additions and 23 deletions

View file

@ -1,19 +0,0 @@
# TODO all enums should probably move out of models
# TODO we should be able to do this kind of stuff without a backing class
require_dependency 'enum_site_setting'
class CategoryStyleSetting < EnumSiteSetting
VALUES = ["bar", "box", "bullet"]
def self.valid_value?(val)
VALUES.include?(val)
end
def self.values
VALUES.map do |l|
{name: l, value: l}
end
end
end

View file

@ -12,6 +12,7 @@
# type: email - Must be a valid email address.
# type: username - Must match the username of an existing user.
# type: list - A list of values, chosen from a set of valid values defined in the choices option.
# type: enum - A single value, chosen from a set of valid values in the choices option.
#
# A type:list setting with the word 'colors' in its name will make color values have a bold line of the corresponding color
#
@ -147,7 +148,11 @@ basic:
category_style:
client: true
default: 'bullet'
enum: 'CategoryStyleSetting'
type: enum
choices:
- bar
- box
- bullet
preview: '<span class="badge-wrapper {{value}}"><span class="badge-category-parent-bg" style="background-color: #aaa;"></span><span class="badge-category-bg" style="background-color: #777;"></span><span style="color: #fff;" data-drop-close="true" class="badge-category clear-badge">Category</span></span>'
enable_mobile_theme:
client: true

View file

@ -3,6 +3,11 @@ require_dependency 'site_settings/db_provider'
module SiteSettingExtension
# For plugins, so they can tell if a feature is supported
def supported_types
[:email, :username, :list, :enum]
end
# part 1 of refactor, centralizing the dependency here
def provider=(val)
@provider = val
@ -171,7 +176,13 @@ module SiteSettingExtension
category: categories[s],
preview: previews[s]
}
opts.merge!({valid_values: enum_class(s).values, translate_names: enum_class(s).translate_names?}) if type == :enum
if type == :enum && enum_class(s)
opts.merge!({valid_values: enum_class(s).values, translate_names: enum_class(s).translate_names?})
elsif type == :enum
opts.merge!({valid_values: choices[s].map{|c| {name: c, value: c}}, translate_names: false})
end
opts[:choices] = choices[s] if choices.has_key? s
opts
end
@ -278,7 +289,11 @@ module SiteSettingExtension
end
if type == types[:enum]
if enum_class(name)
raise Discourse::InvalidParameters.new(:value) unless enum_class(name).valid_value?(val)
else
raise Discourse::InvalidParameters.new(:value) unless choices[name].include?(val)
end
end
if v = validators[name]
@ -408,7 +423,8 @@ module SiteSettingExtension
'username' => UsernameSettingValidator,
types[:fixnum] => IntegerSettingValidator,
types[:string] => StringSettingValidator,
'list' => StringSettingValidator
'list' => StringSettingValidator,
'enum' => StringSettingValidator
}
@validator_mapping[type_name]
end