Overriding user_guardian.rb in a plugin (no fork necessary!)

If anyone comes across this and was as lost as I was, I’m providing my code below, as I got it working as intended. I did not modify any files. I simply created a new file plugin.rb and placed within it the below:

# about: Allows users in Anonymous Mode to change their usernames
# version: 0.1


require_dependency 'guardian'
require_dependency 'guardian/user_guardian'

class ::Guardian
end

module ::UserGuardian
  def can_edit_username?(user)
    return false if SiteSetting.sso_overrides_username?
    return true if is_staff?
    return false if SiteSetting.username_change_period <= 0
    return true if is_anonymous?
    is_me?(user) && ((user.post_count + user.topic_count) == 0 || user.created_at > SiteSetting.username_change_period.days.ago)
  end


  def can_edit_name?(user)
    return false unless SiteSetting.enable_names?
    return false if SiteSetting.sso_overrides_name?
    return true if is_staff?
    return true if is_anonymous?
    can_edit?(user)
  end
end

This overrides the user_guardian.rb class in the Discourse core to allow users to change their username and name of their anonymous user accounts.

If you compare what I have here with what’s in user_guardian.rb in Discourse core, you can see there’s a bunch of other stuff I didn’t need to do anything with, so left it alone. All I needed was to edit those two methods can_edit_username and can_edit_name by changing some return values from false to true and I was able to get what I needed done.

Certainly there are enhancements that could be made, and there is likely best practice that I was able to glean by reading the linked posts here and elsewhere, but if you’re brand new to Ruby like I am and just want to get something very simple tweaked in core, this is a working minimalist example on what you need to do.

Many thanks to the people in this thread for their patience with me and their encouragement and assistance! In particular @merefield who has actually helped me with another post in the past.

10 Likes