Just wanted to give an update and say thank you to everyone who helped.
With the latest changes, the plugin is now working exactly as I intended! It correctly assigns different titles based on the user’s primary group and trust level.
I’m posting the final working code below. It seems to be correct, but since I’m not a developer, I was wondering if there are any areas for improvement or optimization that I might have missed.
app/jobs/scheduled/update-all-titles.rb
# frozen_string_literal: true
module ::Jobs
class AssignGroupBasedTitles < ::Jobs::Scheduled
every SiteSetting.update_title_frequency.hours
def execute(args)
return unless SiteSetting.add_title_by_group_trust_enabled
rules_json_string = SiteSetting.group_based_title_rules
return if rules_json_string.blank?
begin
# Manually parse the JSON string into a Ruby array.
rules = JSON.parse(rules_json_string)
rescue JSON::ParserError
# If the JSON is malformed, log an error and exit to prevent the job from failing.
Rails.logger.error("Group-Based Titles Plugin: Failed to parse group_based_title_rules JSON.")
return
end
# Safety check to ensure the parsed rules are a non-empty array.
return unless rules.is_a?(Array) && rules.present?
User.transaction do
rules.each do |rule|
group_id = rule["group_id"]
trust_level = rule["trust_level"]
title = rule["title"]
next if group_id.blank? || trust_level.blank? || title.blank?
User.where(primary_group_id: group_id, trust_level: trust_level)
.where.not(title: title)
.update_all(title: title)
end
end
end
end
end
config/settings.yml
plugins:
add_title_by_group_trust_enabled:
default: true
client: true
group_based_title_rules:
type: objects
default: []
schema:
properties:
group_id:
type: integer
name: "User Group"
component: "group-chooser"
trust_level:
type: integer
name: "Trust Level"
min: 1
max: 4
title:
type: string
name: "Title"
update_title_frequency:
default: 24
type: integer
plugin.rb
# frozen_string_literal: true
# name: add-title-by-group-trust-level
# about: Assign titles based on primary group and trust level.
# version: 2.1.0
# authors: Your Name
enabled_site_setting :add_title_by_group_trust_enabled
after_initialize do
require_relative "./app/jobs/scheduled/update-all-titles.rb"
end