lato_settings 3.0.9 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 344cb9bd875b8e2f79d5aa42376c97d66895092109eab6af77e578962a3e908a
4
- data.tar.gz: d47ae3971d99b0d89b037297bc7bea4b3d90e9c87974df2d798e7a6623645721
3
+ metadata.gz: 3c62885a11182f2bfedadf8566baf0e5e6eb27c09ea20d91cadd4f55295e111b
4
+ data.tar.gz: 284bb8b0e3dafce53337d6841bfde7f00a805c23f19b2fcba086c24cdf48efcb
5
5
  SHA512:
6
- metadata.gz: ae5bdecc751184385138b77225ac05a7d1beac18ebc79ec778c4d7ec20ed85571c27352c3803decd0f38927e17a911bef5648eb08cc316598df6950221e34ab5
7
- data.tar.gz: cba5f0c6e033fe893cd07013b7ef159b835010235f4afdcbd95a2482005f67e9adc22fca3c0c8995c5c30b294f88374bb605b778e2a31ed65cbb840a7cfa2241
6
+ metadata.gz: 27714a042223d3d41174349b30f1f9f285de632cd5c10615d83bf26b8463e43e60ca1438423d288c5b438a394272a6a3acfee94f704d6506259e101776a92bed
7
+ data.tar.gz: 565b75debcf86352d461ee460489bd0c670c6ac288d8cf3f4c78756f1eaa66cb149fedc92631103fc6c73693a4422ec5d67e151a3deb13fac0cfce2bb95ac9df
data/README.md CHANGED
@@ -5,7 +5,7 @@ Setting values, keys, and labels are displayed as plain text in the administrati
5
5
 
6
6
  ## Installation
7
7
 
8
- Requires Rails 8.1.3.1 or newer in the 8.1 series and Lato 3.25.0 or newer. Existing applications must install the new Lato session migration before deployment; previous sessions are invalidated.
8
+ Requires Rails 8.1.3.1 or newer in the 8.1 series and Lato 3.25.0 or newer. Existing applications must install the new Lato session migration (`rails lato:install:migrations`) before deployment; previous sessions are invalidated.
9
9
  Add required dependencies to your application's Gemfile:
10
10
 
11
11
  ```ruby
@@ -18,11 +18,13 @@ Install gem and run required tasks:
18
18
 
19
19
  ```bash
20
20
  $ bundle
21
- $ rails lato_settings:install:application
21
+ $ rails lato:install:migrations
22
22
  $ rails lato_settings:install:migrations
23
23
  $ rails db:migrate
24
24
  ```
25
25
 
26
+ `rails lato_settings:install:application` exists for consistency with other Lato engines but does nothing: it is not required.
27
+
26
28
  Mount lato settings routes on the **config/routes.rb** file:
27
29
 
28
30
  ```ruby
@@ -47,6 +49,61 @@ import "lato_settings/application";
47
49
  // ....
48
50
  ```
49
51
 
52
+ ## Permissions
53
+
54
+ Users need the `lato_settings_admin` flag (column added by the engine migrations on `lato_users`):
55
+
56
+ ```ruby
57
+ Lato::User.find_by(email: "admin@example.com").update!(lato_settings_admin: true)
58
+ ```
59
+
60
+ ## Usage
61
+
62
+ Read values with `LatoSettings.get(key, default = nil)`. The key is case-insensitive. The default is returned when the setting does not exist or its stored value can't be converted to its type.
63
+
64
+ | Typology | Returned type |
65
+ |----------|---------------|
66
+ | `string`, `text` | `String` |
67
+ | `integer` | `Integer` |
68
+ | `number` | `Float` |
69
+ | `date` | `Date` |
70
+ | `select` | `String` (one of the allowed values) |
71
+
72
+ Create settings in seeds (idempotent) and let admins edit the values from the panel:
73
+
74
+ ```ruby
75
+ LatoSettings::Setting.find_or_create_by!(key: "items_per_page") do |setting|
76
+ setting.label = "Items per page"
77
+ setting.description = "Rows shown in lists"
78
+ setting.typology = :integer
79
+ setting.value = 25
80
+ setting.required = true
81
+ setting.options = { min: 1, max: 100, step: 1 }
82
+ end
83
+ ```
84
+
85
+ Keys are normalized (`Site Name` becomes `site_name`; accents are transliterated, other characters become `_`) and, like `typology`, **cannot be changed after creation**. A value is required and is validated against its typology on save.
86
+
87
+ ### Options
88
+
89
+ `options` is a JSON hash, set from seeds or console only (the admin UI can't edit it):
90
+
91
+ | Option | Used by | Meaning |
92
+ |--------|---------|---------|
93
+ | `min`, `max` | `integer`, `number`, `date` | Inclusive bounds (dates as `YYYY-MM-DD`) |
94
+ | `step` | `integer`, `number` | Value must be `min + n * step` (`min` defaults to 0) |
95
+ | `values` | `select` | Array of allowed values, compared as strings: `options: { values: %w[draft published] }` |
96
+
97
+ `required: true` settings can be edited but not deleted.
98
+
99
+ ### Caching
100
+
101
+ `LatoSettings.get` reads from a snapshot of all settings kept in `Rails.cache` (key `LatoSettings/v2/cache`, 1 minute TTL) and in a per-process memo that honors the same TTL. Saving or destroying a setting through the model clears it after the transaction commits; call `LatoSettings.reset_cache` after changes that skip callbacks (`update_all`, SQL, other apps). In production with more than one process or host, configure a **shared** cache store (Redis, Memcached, Solid Cache): with a per-process store (`:memory_store`, `:file_store` on separate hosts) changes are visible in other processes only after the TTL.
102
+
103
+ ### Security notes
104
+
105
+ Values are stored as **plain text** in the database and in the cache: do not store secrets (API keys, passwords) here. The engine appends `setting.value` to `config.filter_parameters` so values don't appear in request logs.
106
+
50
107
  ## Development
51
108
 
52
109
  Clone repository, install dependencies, run migrations and start:
@@ -55,11 +112,14 @@ Clone repository, install dependencies, run migrations and start:
55
112
  $ git clone https://github.com/Lato-GAM/lato_settings
56
113
  $ cd lato_settings
57
114
  $ bundle
58
- $ rails db:migrate
59
- $ rails db:seed
60
- $ foreman start -f Procfile.dev
115
+ $ bin/rails db:migrate
116
+ $ bin/rails db:seed
117
+ $ bin/rails server
118
+ $ bin/rails test
61
119
  ```
62
120
 
121
+ The dummy app mounts the engine at `/lato-settings`; seed login is `admin@mail.com` / `Password1!`.
122
+
63
123
  ## Publish
64
124
 
65
125
  ```shell
@@ -1 +1 @@
1
- console.log("Lato Settings JS loaded");
1
+ // Lato Settings has no custom JavaScript: copy buttons use the Lato "lato-copyclip" controller.
@@ -3,24 +3,24 @@ module LatoSettings
3
3
  def index
4
4
  @settings = lato_index_collection(
5
5
  Setting.all,
6
- columns: %i[label value key updated_at actions],
6
+ columns: %i[label typology value key updated_at actions],
7
7
  searchable_columns: %i[key label value],
8
- sortable_columns: %i[updated_at],
8
+ sortable_columns: %i[key label updated_at],
9
9
  pagination: true,
10
10
  default_sort_by: "key|asc"
11
11
  )
12
12
  end
13
13
 
14
14
  def new
15
- @setting = Setting.new(typology: params[:typology])
15
+ @setting = Setting.new(typology: (params[:typology] if Setting.typologies.key?(params[:typology])))
16
16
  end
17
17
 
18
18
  def create
19
- @setting = Setting.new(setting_params)
19
+ @setting = Setting.new(create_params)
20
20
  if @setting.save
21
- redirect_to settings_path
21
+ redirect_to settings_path, notice: I18n.t('lato_settings.setting_created')
22
22
  else
23
- render 'new'
23
+ render 'new', status: :unprocessable_entity
24
24
  end
25
25
  end
26
26
 
@@ -30,23 +30,31 @@ module LatoSettings
30
30
 
31
31
  def update
32
32
  @setting = Setting.find(params[:id])
33
- if @setting.update(setting_params)
34
- redirect_to settings_path
33
+ if @setting.update(update_params)
34
+ redirect_to settings_path, notice: I18n.t('lato_settings.setting_updated')
35
35
  else
36
- render 'edit'
36
+ render 'edit', status: :unprocessable_entity
37
37
  end
38
38
  end
39
39
 
40
40
  def destroy
41
41
  @setting = Setting.find(params[:id])
42
- @setting.destroy
43
- redirect_to settings_path
42
+ if @setting.destroy
43
+ redirect_to settings_path, notice: I18n.t('lato_settings.setting_deleted')
44
+ else
45
+ redirect_to settings_path, alert: I18n.t('lato_settings.setting_required_not_deletable')
46
+ end
44
47
  end
45
48
 
46
49
  private
47
50
 
48
- def setting_params
51
+ def create_params
49
52
  params.require(:setting).permit(:key, :value, :label, :description, :typology)
50
53
  end
54
+
55
+ # key and typology are immutable after creation
56
+ def update_params
57
+ params.require(:setting).permit(:value, :label, :description)
58
+ end
51
59
  end
52
60
  end
@@ -6,43 +6,102 @@ module LatoSettings
6
6
 
7
7
  def lato_settings_setting_value(setting)
8
8
  if setting.typology == 'text'
9
- content_tag(:pre, setting.value_formatted.to_s, class: 'p-2 bg-light border rounded mb-0', style: 'max-height: 200px; overflow: auto;')
9
+ content_tag(:pre, lato_settings_display_value(setting), tabindex: 0, role: 'region', aria: { label: setting.label || setting.key },
10
+ class: 'p-2 bg-light border rounded mb-0', style: 'max-height: 200px; overflow: auto;')
10
11
  else
11
- print_content(setting, setting.value_formatted, :value)
12
+ print_content(setting, lato_settings_display_value(setting), :value)
12
13
  end
13
14
  end
14
15
 
15
16
  def lato_settings_setting_label(setting)
16
17
  content_tag(:div, class: 'd-flex flex-column') do
17
18
  concat content_tag(:strong, setting.label)
18
- if setting.description
19
+ if setting.description.present?
19
20
  concat content_tag(:small, setting.description, class: 'text-muted')
20
21
  end
21
22
  end
22
23
  end
23
-
24
+
25
+ def lato_settings_setting_typology(setting)
26
+ content_tag(:div, class: 'd-flex flex-column align-items-start gap-1') do
27
+ concat content_tag(:span, lato_settings_typology_label(setting.typology))
28
+ concat lato_data_badge(I18n.t('lato_settings.required'), 'secondary') if setting.required
29
+ end
30
+ end
31
+
24
32
  def lato_settings_setting_updated_at(setting)
25
- setting.updated_at.strftime('%d/%m/%Y %H:%M')
33
+ I18n.l(setting.updated_at, format: :long)
26
34
  end
27
35
 
28
36
  def lato_settings_setting_actions(setting)
37
+ name = setting.label || setting.key
38
+
29
39
  content_tag(:div, class: 'btn-group btn-group-sm') do
30
- concat link_to(I18n.t('lato_settings.cta_edit'), lato_settings.edit_setting_path(setting), class: 'btn btn-primary', data: { lato_action_target: 'trigger', turbo_frame: dom_id(setting, 'form'), action_title: I18n.t('lato_settings.edit_setting') })
40
+ concat link_to(I18n.t('lato_settings.cta_edit'), lato_settings.edit_setting_path(setting), class: 'btn btn-primary',
41
+ aria: { label: I18n.t('lato_settings.cta_edit_setting', label: name) },
42
+ data: { lato_action_target: 'trigger', turbo_frame: dom_id(setting, 'form'), action_title: I18n.t('lato_settings.edit_setting') })
31
43
 
32
- unless setting.required
33
- concat link_to(I18n.t('lato_settings.cta_delete'), lato_settings.setting_path(setting), class: 'btn btn-danger', data: { turbo_confirm: I18n.t('lato_settings.cta_delete_confirm'), turbo_method: :delete })
44
+ if setting.required
45
+ reason = I18n.t('lato_settings.setting_required_not_deletable')
46
+ concat content_tag(:button, I18n.t('lato_settings.cta_delete'), type: 'button', class: 'btn btn-danger', disabled: true,
47
+ title: reason, aria: { label: "#{I18n.t('lato_settings.cta_delete_setting', label: name)}: #{reason}" })
48
+ else
49
+ # submit button (not a link) so deletion works without JavaScript. It targets the form rendered by
50
+ # `lato_settings_delete_forms` through the `form` attribute: the index table lives inside a GET form
51
+ # and HTML forbids nested forms, so button_to can't be used here.
52
+ concat content_tag(:button, I18n.t('lato_settings.cta_delete'), type: 'submit', class: 'btn btn-danger',
53
+ form: dom_id(setting, 'delete_form'), aria: { label: I18n.t('lato_settings.cta_delete_setting', label: name) })
34
54
  end
35
55
  end
36
56
  end
37
57
 
58
+ # One DELETE form per deletable setting, to be rendered outside of the index form
59
+ def lato_settings_delete_forms(settings)
60
+ safe_join(settings.reject(&:required).map do |setting|
61
+ form_with(url: lato_settings.setting_path(setting), method: :delete, id: dom_id(setting, 'delete_form'),
62
+ data: { turbo_confirm: I18n.t('lato_settings.cta_delete_confirm') }) { '' }
63
+ end)
64
+ end
65
+
66
+ def lato_settings_typology_label(typology)
67
+ I18n.t("lato_settings.typologies.#{typology}", default: typology.to_s.humanize)
68
+ end
69
+
70
+ def lato_settings_typology_options
71
+ LatoSettings::Setting.typologies.keys.map { |typology| [lato_settings_typology_label(typology), typology] }
72
+ end
73
+
74
+ # Help text for the value input: expected format plus min/max/step from options
75
+ def lato_settings_value_help(setting)
76
+ parts = [I18n.t("lato_settings.help.#{setting.typology}", default: '')]
77
+
78
+ if %w[number integer date].include?(setting.typology)
79
+ parts << I18n.t('lato_settings.help.min', value: setting.option_min) unless setting.option_min.nil?
80
+ parts << I18n.t('lato_settings.help.max', value: setting.option_max) unless setting.option_max.nil?
81
+ end
82
+ if %w[number integer].include?(setting.typology) && setting.option_step_configured
83
+ parts << I18n.t('lato_settings.help.step', value: setting.option_step_configured)
84
+ end
85
+
86
+ parts.reject(&:blank?).join(' ')
87
+ end
88
+
89
+ # Formatted value for display; falls back to the raw stored value when it can't be converted
90
+ def lato_settings_display_value(setting)
91
+ formatted = setting.value_formatted
92
+ return setting.value.to_s if formatted.nil?
93
+
94
+ formatted.is_a?(Date) ? I18n.l(formatted) : formatted.to_s
95
+ end
96
+
38
97
  def print_content(setting, content, type)
39
98
  label = setting.label || setting.key
40
99
  button_id = "#{type}_#{setting.id}"
41
- copy_label = I18n.t("lato_settings.cta_copy")
100
+ copy_label = I18n.t("lato_settings.cta_copy_value", label: label)
42
101
 
43
102
  content_tag(:div, class: "input-group input-group-sm", data: { controller: "lato-copyclip" }) do
44
- concat tag.input(type: "text", class: "form-control", placeholder: label,
45
- aria: { label: label, describedby: button_id }, value: content, readonly: true,
103
+ concat tag.input(type: "text", class: "form-control", placeholder: label, title: content,
104
+ aria: { label: label }, value: content, readonly: true,
46
105
  data: { lato_copyclip_target: "input" })
47
106
  concat content_tag(:button, type: "button", id: button_id, class: "btn btn-primary",
48
107
  title: copy_label, aria: { label: copy_label },
@@ -9,18 +9,23 @@ module LatoSettings
9
9
  select: 3,
10
10
  integer: 4,
11
11
  text: 5
12
- }, prefix: true
12
+ }, prefix: true, validate: true
13
+
14
+ # key and typology identify a setting for the host application: changing them
15
+ # after creation would silently break `LatoSettings.get` callers
16
+ attr_readonly :key, :typology
13
17
 
14
18
  validates :key, presence: true, uniqueness: true, format: { with: /\A[a-zA-Z0-9_]+\z/ }
15
19
  validates :typology, presence: true
16
- validates :value, presence: true, allow_blank: true
20
+ validates :value, presence: true
17
21
  validates :label, presence: true
22
+ validate :value_matches_typology
18
23
 
19
24
  # Hooks
20
25
  ##
21
26
 
22
27
  # normalize key before validation
23
- before_validation do
28
+ before_validation(on: :create) do
24
29
  self.key = key&.to_s&.downcase&.parameterize&.underscore
25
30
  end
26
31
 
@@ -29,55 +34,58 @@ module LatoSettings
29
34
  throw(:abort) if required
30
35
  end
31
36
 
32
- after_save :reload_cache
33
- after_destroy :reload_cache
37
+ # after_commit (not after_save) so other processes can't rebuild the cache from pre-commit data
38
+ after_commit :reload_cache
34
39
  def reload_cache
35
40
  LatoSettings.reset_cache
36
41
  end
37
42
 
38
43
  # Helpers
39
44
  ##
40
-
45
+
46
+ # Never raises: a corrupted row must not break `LatoSettings.get` or the index page.
47
+ # Returns nil when the stored value can't be converted to the typology.
41
48
  def value_formatted
42
49
  return nil if value.nil?
43
50
 
44
51
  case typology
45
- when 'string'
46
- value.to_s
47
52
  when 'number'
48
- value.to_f
53
+ Float(value.to_s, exception: false)
49
54
  when 'date'
50
- Date.parse(value)
55
+ parse_date(value)
51
56
  when 'select'
52
57
  option_values.include?(value) ? value : nil
53
58
  when 'integer'
54
- value.to_i
55
- when 'text'
56
- value.to_s
59
+ Integer(value.to_s, 10, exception: false)
57
60
  else
58
61
  value.to_s
59
62
  end
60
63
  end
61
-
64
+
62
65
  def option_min
63
- options&.dig('min') || nil
66
+ safe_options['min']
64
67
  end
65
68
 
66
69
  def option_max
67
- options&.dig('max') || nil
70
+ safe_options['max']
68
71
  end
69
72
 
70
73
  def option_step
71
- options&.dig('step') || 1
74
+ option_step_configured || 1
75
+ end
76
+
77
+ # nil when no step is set in options (no step constraint)
78
+ def option_step_configured
79
+ safe_options['step']
72
80
  end
73
81
 
74
82
  def option_values
75
- options&.dig('values') || []
83
+ Array(safe_options['values']).map(&:to_s)
76
84
  end
77
85
 
78
86
  # Class
79
87
  ##
80
-
88
+
81
89
  # DEPRECATED METHOD: TO BE REMOVED IN FUTURE VERSIONS
82
90
  def self.get(key, default = nil)
83
91
  Rails.logger.warn "LatoSettings::Setting.get is deprecated. Use LatoSettings.get instead."
@@ -89,5 +97,74 @@ module LatoSettings
89
97
  Rails.logger.warn "LatoSettings::Setting.load_cache is deprecated. Use LatoSettings.reset_cache instead."
90
98
  LatoSettings.reset_cache
91
99
  end
100
+
101
+ private
102
+
103
+ # options may hold symbol keys before reload or a non-hash value if written by hand
104
+ def safe_options
105
+ options.is_a?(Hash) ? options.with_indifferent_access : {}
106
+ end
107
+
108
+ def parse_date(raw)
109
+ Date.parse(raw.to_s)
110
+ rescue Date::Error
111
+ nil
112
+ end
113
+
114
+ def value_matches_typology
115
+ return if value.blank?
116
+
117
+ case typology
118
+ when 'integer'
119
+ number = Integer(value.to_s, 10, exception: false)
120
+ number ? validate_number_options(decimal(number)) : add_value_error(:not_integer)
121
+ when 'number'
122
+ number = Float(value.to_s, exception: false)
123
+ number ? validate_number_options(decimal(number)) : add_value_error(:not_number)
124
+ when 'date'
125
+ validate_date_options
126
+ when 'select'
127
+ add_value_error(:not_in_values) unless option_values.include?(value)
128
+ end
129
+ end
130
+
131
+ def validate_number_options(number)
132
+ min = decimal(option_min)
133
+ max = decimal(option_max)
134
+ step = decimal(option_step_configured)
135
+
136
+ return add_value_error(:too_small, min: option_min) if min && number < min
137
+ return add_value_error(:too_big, max: option_max) if max && number > max
138
+
139
+ add_value_error(:not_on_step, step: option_step) if step&.positive? && ((number - (min || 0)) % step) != 0
140
+ end
141
+
142
+ def validate_date_options
143
+ date = Date.iso8601(value.to_s)
144
+ min = iso_date(option_min)
145
+ max = iso_date(option_max)
146
+
147
+ return add_value_error(:too_small, min: option_min) if min && date < min
148
+
149
+ add_value_error(:too_big, max: option_max) if max && date > max
150
+ rescue Date::Error
151
+ add_value_error(:not_date)
152
+ end
153
+
154
+ def add_value_error(code, **interpolations)
155
+ errors.add(:value, I18n.t("lato_settings.validation.#{code}", **interpolations))
156
+ end
157
+
158
+ def decimal(raw)
159
+ BigDecimal(raw.to_s) unless raw.nil?
160
+ rescue ArgumentError
161
+ nil
162
+ end
163
+
164
+ def iso_date(raw)
165
+ Date.iso8601(raw.to_s) unless raw.nil?
166
+ rescue Date::Error
167
+ nil
168
+ end
92
169
  end
93
170
  end
@@ -1,21 +1,27 @@
1
1
  <%
2
2
 
3
3
  setting ||= LatoSettings::Setting.new
4
+ value_help = lato_settings_value_help(setting)
5
+ value_help_id = 'setting_value_help'
6
+ value_options = { required: true, aria: { describedby: value_help_id } }
4
7
 
5
8
  %>
6
9
 
7
10
  <%= turbo_frame_tag dom_id(setting, 'form') do %>
8
- <%= form_with model: setting, url: setting.persisted? ? lato_settings.setting_path(setting) : lato_settings.settings_path, data: { turbo_frame: '_self', controller: 'lato-form lato-settings-form' } do |form| %>
9
- <%= lato_form_notices class: %w[mb-3] %>
10
- <%= lato_form_errors setting, class: %w[mb-3] %>
11
+ <% if setting.typology %>
12
+ <%= form_with model: setting, url: setting.persisted? ? lato_settings.setting_path(setting) : lato_settings.settings_path, data: { turbo_frame: '_self', controller: 'lato-form' } do |form| %>
13
+ <%= lato_form_notices class: %w[mb-3] %>
14
+ <%= lato_form_errors setting, class: %w[mb-3] %>
11
15
 
12
- <% if setting.typology %>
13
- <%= form.hidden_field :typology %>
16
+ <%= form.hidden_field :typology if setting.new_record? %>
14
17
 
15
18
  <div class="row">
16
19
  <div class="col col-12 col-md-6 mb-3">
17
20
  <%= lato_form_item_label form, :key %>
18
- <%= lato_form_item_input_text form, :key, required: true, disabled: setting.persisted? %>
21
+ <%= lato_form_item_input_text form, :key, required: true, readonly: setting.persisted?, aria: { describedby: ('setting_key_help' if setting.persisted?) } %>
22
+ <% if setting.persisted? %>
23
+ <div id="setting_key_help" class="form-text"><%= I18n.t('lato_settings.help.key_immutable') %></div>
24
+ <% end %>
19
25
  </div>
20
26
 
21
27
  <div class="col col-12 col-md-6 mb-3">
@@ -24,37 +30,28 @@ setting ||= LatoSettings::Setting.new
24
30
  </div>
25
31
  </div>
26
32
 
27
- <% if setting.typology == 'number' %>
28
- <div class="mb-3">
29
- <%= lato_form_item_label form, :value %>
30
- <%= lato_form_item_input_number form, :value, required: true, min: setting.option_min, max: setting.option_max, step: setting.option_step %>
31
- </div>
32
- <% elsif setting.typology == 'integer' %>
33
- <div class="mb-3">
34
- <%= lato_form_item_label form, :value %>
35
- <%= lato_form_item_input_number form, :value, required: true, min: setting.option_min, max: setting.option_max, step: 1 %>
36
- </div>
37
- <% elsif setting.typology == 'date' %>
38
- <div class="mb-3">
39
- <%= lato_form_item_label form, :value %>
40
- <%= lato_form_item_input_date form, :value, required: true, min: setting.option_min, max: setting.option_max %>
41
- </div>
42
- <% elsif setting.typology == 'select' %>
43
- <div class="mb-3">
44
- <%= lato_form_item_label form, :value %>
45
- <%= lato_form_item_input_select form, :value, options_for_select(setting.option_values, setting.value), required: true %>
46
- </div>
47
- <% elsif setting.typology == 'text' %>
48
- <div class="mb-3">
49
- <%= lato_form_item_label form, :value %>
50
- <%= lato_form_item_input_textarea form, :value, required: true, rows: 5 %>
51
- </div>
52
- <% else %>
53
- <div class="mb-3">
54
- <%= lato_form_item_label form, :value %>
55
- <%= lato_form_item_input_text form, :value, required: true %>
33
+ <div class="mb-3">
34
+ <%= lato_form_item_label form, :value %>
35
+ <% if setting.typology == 'number' %>
36
+ <%= lato_form_item_input_number form, :value, **{ min: setting.option_min, max: setting.option_max, step: setting.option_step_configured || 'any' }, **value_options %>
37
+ <% elsif setting.typology == 'integer' %>
38
+ <%= lato_form_item_input_number form, :value, **{ min: setting.option_min, max: setting.option_max, step: setting.option_step_configured || 1 }, **value_options %>
39
+ <% elsif setting.typology == 'date' %>
40
+ <%= lato_form_item_input_date form, :value, **{ min: setting.option_min, max: setting.option_max }, **value_options %>
41
+ <% elsif setting.typology == 'select' %>
42
+ <%= lato_form_item_input_select form, :value, options_for_select(setting.option_values, setting.value), value_options %>
43
+ <% elsif setting.typology == 'text' %>
44
+ <%= lato_form_item_input_textarea form, :value, rows: 5, **value_options %>
45
+ <% else %>
46
+ <%= lato_form_item_input_text form, :value, **value_options %>
47
+ <% end %>
48
+ <div id="<%= value_help_id %>" class="form-text">
49
+ <%= value_help %>
50
+ <% if setting.description.present? && setting.persisted? %>
51
+ <div><%= setting.description %></div>
52
+ <% end %>
56
53
  </div>
57
- <% end %>
54
+ </div>
58
55
 
59
56
  <div class="mb-3">
60
57
  <%= lato_form_item_label form, :description %>
@@ -64,14 +61,18 @@ setting ||= LatoSettings::Setting.new
64
61
  <div class="d-flex justify-content-end">
65
62
  <%= lato_form_submit form, setting.persisted? ? I18n.t('lato_settings.cta_update') : I18n.t('lato_settings.cta_confirm'), class: %w[btn-success] %>
66
63
  </div>
67
- <% elsif !setting.persisted? %>
64
+ <% end %>
65
+ <% else %>
66
+ <%# typology step: explicit submit instead of navigating on change (WCAG 3.2.2) %>
67
+ <%= form_with url: lato_settings.new_setting_path, method: :get, data: { turbo_frame: '_self' } do |form| %>
68
68
  <div class="mb-3">
69
- <%= lato_form_item_label form, :typology %>
70
- <%= lato_form_item_input_select form, :typology, options_for_select(LatoSettings::Setting.typologies.keys.map { |s| [s.humanize, s] }, setting.typology), required: true, data: { lato_settings_form_target: 'inputTypology' } %>
69
+ <%= form.label :typology, LatoSettings::Setting.human_attribute_name(:typology), class: 'form-label' %>
70
+ <%= form.select :typology, options_for_select(lato_settings_typology_options), {}, class: 'form-control', required: true %>
71
71
  </div>
72
72
 
73
- <%= link_to '', lato_settings.new_setting_path(typology: ''), class: 'd-none', data: { lato_settings_form_target: 'linkTypologySelected' } %>
73
+ <div class="d-flex justify-content-end">
74
+ <%= form.submit I18n.t('lato_settings.cta_continue'), class: 'btn btn-primary', name: nil %>
75
+ </div>
74
76
  <% end %>
75
-
76
77
  <% end %>
77
- <% end %>
78
+ <% end %>
@@ -7,11 +7,13 @@
7
7
  create: {
8
8
  path: lato_settings.new_setting_path,
9
9
  icon: 'bi bi-plus',
10
- aria_label: I18n.t('lato_settings.add_setting'),
10
+ aria: { label: I18n.t('lato_settings.add_setting') },
11
11
  title: I18n.t('lato_settings.add_setting'),
12
12
  data: { lato_action_target: 'trigger', turbo_frame: dom_id(LatoSettings::Setting.new, 'form'), action_title: I18n.t('lato_settings.add_setting') },
13
13
  }
14
14
  }
15
15
  %>
16
16
  </div>
17
- </div>
17
+ </div>
18
+
19
+ <%= lato_settings_delete_forms(@settings) %>
data/config/importmap.rb CHANGED
@@ -1,2 +1 @@
1
1
  pin "lato_settings/application", to: "lato_settings/application.js"
2
- pin_all_from LatoSettings::Engine.root.join("app/assets/javascripts/lato_settings/controllers"), under: "controllers", to: "lato_settings/controllers"
@@ -3,9 +3,54 @@ en:
3
3
  settings: Settings
4
4
  add_setting: Add Setting
5
5
  edit_setting: Edit Setting
6
+ required: Required
6
7
  cta_edit: Edit
8
+ cta_edit_setting: "Edit %{label}"
7
9
  cta_update: Update
8
10
  cta_delete: Delete
11
+ cta_delete_setting: "Delete %{label}"
9
12
  cta_confirm: Confirm
13
+ cta_continue: Continue
10
14
  cta_copy: Copy
11
- cta_delete_confirm: Are you sure you want to delete this setting?
15
+ cta_copy_value: "Copy value of %{label}"
16
+ cta_delete_confirm: Are you sure you want to delete this setting?
17
+ setting_created: Setting created successfully.
18
+ setting_updated: Setting updated successfully.
19
+ setting_deleted: Setting deleted successfully.
20
+ setting_required_not_deletable: Required settings cannot be deleted.
21
+ typologies:
22
+ string: String
23
+ number: Number
24
+ date: Date
25
+ select: Select
26
+ integer: Integer
27
+ text: Text
28
+ help:
29
+ key_immutable: The key cannot be changed after creation.
30
+ string: Short text.
31
+ text: Long text.
32
+ integer: Whole number.
33
+ number: Decimal number.
34
+ date: Date in YYYY-MM-DD format.
35
+ select: Choose one of the allowed values.
36
+ min: "Minimum: %{value}."
37
+ max: "Maximum: %{value}."
38
+ step: "Step: %{value}."
39
+ validation:
40
+ not_integer: must be a whole number
41
+ not_number: must be a number
42
+ not_date: must be a valid date (YYYY-MM-DD)
43
+ not_in_values: must be one of the allowed values
44
+ too_small: "must be greater than or equal to %{min}"
45
+ too_big: "must be less than or equal to %{max}"
46
+ not_on_step: "must be a multiple of %{step} (starting from the minimum)"
47
+ activerecord:
48
+ attributes:
49
+ lato_settings/setting:
50
+ typology: Type
51
+ key: Key
52
+ label: Label
53
+ value: Value
54
+ description: Description
55
+ updated_at: Updated at
56
+ actions: Actions
@@ -3,12 +3,47 @@ it:
3
3
  settings: Impostazioni
4
4
  add_setting: Aggiungi Impostazione
5
5
  edit_setting: Modifica Impostazione
6
+ required: Obbligatoria
6
7
  cta_edit: Modifica
8
+ cta_edit_setting: "Modifica %{label}"
7
9
  cta_update: Aggiorna
8
10
  cta_delete: Cancella
11
+ cta_delete_setting: "Cancella %{label}"
9
12
  cta_confirm: Conferma
13
+ cta_continue: Continua
10
14
  cta_copy: Copia
15
+ cta_copy_value: "Copia il valore di %{label}"
11
16
  cta_delete_confirm: Sei sicuro di voler cancellare questa impostazione?
17
+ setting_created: Impostazione creata con successo.
18
+ setting_updated: Impostazione aggiornata con successo.
19
+ setting_deleted: Impostazione cancellata con successo.
20
+ setting_required_not_deletable: Le impostazioni obbligatorie non possono essere cancellate.
21
+ typologies:
22
+ string: Stringa
23
+ number: Numero
24
+ date: Data
25
+ select: Selezione
26
+ integer: Intero
27
+ text: Testo
28
+ help:
29
+ key_immutable: La chiave non può essere modificata dopo la creazione.
30
+ string: Testo breve.
31
+ text: Testo lungo.
32
+ integer: Numero intero.
33
+ number: Numero decimale.
34
+ date: Data nel formato AAAA-MM-GG.
35
+ select: Scegli uno dei valori consentiti.
36
+ min: "Minimo: %{value}."
37
+ max: "Massimo: %{value}."
38
+ step: "Passo: %{value}."
39
+ validation:
40
+ not_integer: deve essere un numero intero
41
+ not_number: deve essere un numero
42
+ not_date: deve essere una data valida (AAAA-MM-GG)
43
+ not_in_values: deve essere uno dei valori consentiti
44
+ too_small: "deve essere maggiore o uguale a %{min}"
45
+ too_big: "deve essere minore o uguale a %{max}"
46
+ not_on_step: "deve essere un multiplo di %{step} (a partire dal minimo)"
12
47
  activerecord:
13
48
  attributes:
14
49
  lato_settings/setting:
@@ -0,0 +1,12 @@
1
+ class ChangeLatoSettingsValueAndDescriptionToText < ActiveRecord::Migration[7.1]
2
+ # string columns are limited to 255 chars on PostgreSQL/MySQL, too short for the `text` typology
3
+ def up
4
+ change_column :lato_settings_settings, :value, :text
5
+ change_column :lato_settings_settings, :description, :text
6
+ end
7
+
8
+ def down
9
+ change_column :lato_settings_settings, :value, :string
10
+ change_column :lato_settings_settings, :description, :string
11
+ end
12
+ end
@@ -6,6 +6,12 @@ module LatoSettings
6
6
  app.config.importmap.paths << root.join('config/importmap.rb')
7
7
  end
8
8
 
9
+ # Setting values may contain secrets typed by admins: keep them out of request logs.
10
+ # after_initialize + append so host filter_parameters assignments are never overridden.
11
+ config.after_initialize do |app|
12
+ app.config.filter_parameters << /\Asetting\.value\z/
13
+ end
14
+
9
15
  initializer "lato_settings.precompile" do |app|
10
16
  app.config.assets.precompile << "lato_settings_manifest.js"
11
17
  end
@@ -1,3 +1,3 @@
1
1
  module LatoSettings
2
- VERSION = "3.0.9"
2
+ VERSION = "3.1.0"
3
3
  end
data/lib/lato_settings.rb CHANGED
@@ -3,6 +3,9 @@ require "lato_settings/engine"
3
3
  require "lato_settings/config"
4
4
 
5
5
  module LatoSettings
6
+ CACHE_KEY = "LatoSettings/v2/cache".freeze
7
+ CACHE_TTL = 1.minute
8
+
6
9
  class << self
7
10
  def config
8
11
  @config ||= Config.new
@@ -12,33 +15,28 @@ module LatoSettings
12
15
  yield config
13
16
  end
14
17
 
18
+ # Returns the typed value of the setting or `default` when missing/unconvertible.
15
19
  def get(key, default = nil)
16
- load_cache
20
+ value = load_cache[:data][key.to_s.downcase]
17
21
 
18
- @cache[:data][key.to_s] || default
22
+ value.nil? ? default : value
19
23
  end
20
24
 
21
25
  def load_cache
22
- return true if defined?(@cache) && @cache && @cache[:expires_at] && @cache[:expires_at] > Time.now
23
-
24
- @cache = Rails.cache.fetch('LatoSettings/cache') do
25
- data = {}
26
- LatoSettings::Setting.all.each do |setting|
27
- data[setting.key] = setting.value_formatted
28
- end
26
+ # the per-process memo must honor expiry, otherwise it would never refresh
27
+ @cache = nil if @cache && @cache[:expires_at] <= Time.now
29
28
 
29
+ @cache ||= Rails.cache.fetch(CACHE_KEY, expires_in: CACHE_TTL) do
30
30
  {
31
- data: data,
32
- expires_at: Time.now + 1.minute
31
+ data: LatoSettings::Setting.all.each_with_object({}) { |setting, data| data[setting.key] = setting.value_formatted },
32
+ expires_at: Time.now + CACHE_TTL
33
33
  }
34
34
  end
35
-
36
- @cache
37
35
  end
38
36
 
39
37
  def reset_cache
40
38
  @cache = nil
41
- Rails.cache.delete('LatoSettings/cache')
39
+ Rails.cache.delete(CACHE_KEY)
42
40
  end
43
41
  end
44
42
  end
@@ -2,10 +2,10 @@ require 'fileutils'
2
2
 
3
3
  namespace :lato_settings do
4
4
  namespace :install do
5
- desc 'Install Lato settings engine and run tasks on main rails application'
5
+ desc 'No-op kept for consistency with other Lato engines (nothing to install on the host application)'
6
6
  # Usage: rails lato_settings:install:application
7
7
  task :application do
8
- # Free for future use...
8
+ puts 'lato_settings: nothing to install on the application. Run `rails lato_settings:install:migrations` to copy migrations.'
9
9
  end
10
10
  end
11
11
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lato_settings
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.0.9
4
+ version: 3.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Gregorio Galante
@@ -55,7 +55,6 @@ files:
55
55
  - Rakefile
56
56
  - app/assets/config/lato_settings_manifest.js
57
57
  - app/assets/javascripts/lato_settings/application.js
58
- - app/assets/javascripts/lato_settings/controllers/lato_settings_form_controller.js
59
58
  - app/assets/stylesheets/lato_settings/application.scss
60
59
  - app/controllers/lato_settings/application_controller.rb
61
60
  - app/controllers/lato_settings/settings_controller.rb
@@ -74,6 +73,7 @@ files:
74
73
  - config/routes.rb
75
74
  - db/migrate/20250328072343_add_lato_settings_admin_to_lato_user.rb
76
75
  - db/migrate/20250328073205_create_lato_settings_settings.rb
76
+ - db/migrate/20261110090000_change_lato_settings_value_and_description_to_text.rb
77
77
  - lib/lato_settings.rb
78
78
  - lib/lato_settings/config.rb
79
79
  - lib/lato_settings/engine.rb
@@ -101,5 +101,5 @@ required_rubygems_version: !ruby/object:Gem::Requirement
101
101
  requirements: []
102
102
  rubygems_version: 4.0.9
103
103
  specification_version: 4
104
- summary: Another engine for Lato projects
104
+ summary: Application settings management for Lato projects
105
105
  test_files: []
@@ -1,25 +0,0 @@
1
- import { Controller } from "@hotwired/stimulus"
2
-
3
- export default class extends Controller {
4
- static targets = [
5
- "inputTypology",
6
- "linkTypologySelected"
7
- ]
8
-
9
- connect() {
10
- this.onInputTypologyChange = this.onInputTypologyChange.bind(this)
11
-
12
- if (this.hasInputTypologyTarget && this.hasLinkTypologySelectedTarget) {
13
- this.inputTypologyTarget.addEventListener("change", this.onInputTypologyChange)
14
- }
15
- }
16
-
17
- onInputTypologyChange(event) {
18
- if (!this.hasInputTypologyTarget) return
19
- if (!this.hasLinkTypologySelectedTarget) return
20
- if (!event.target.value) return
21
-
22
- this.linkTypologySelectedTarget.href = this.linkTypologySelectedTarget.href.replace(/typology=[^&]*/, `typology=${event.target.value}`)
23
- this.linkTypologySelectedTarget.click()
24
- }
25
- }