Monkey patching a model from a plugin


(zh99998) #1

Continuing the discussion from Monkey patching a controller from a plugin:

I’m making a plugin that will modify some model methods. just methods, no custom fields needed.

I have tried:

after_initialize do
  class UsernameValidator
    def username_char_valid?
      return unless errors.empty?
      if username =~ /[^A-Za-z0-9_\.\-\u4e00-\u9fa5]/
        self.errors << I18n.t(:'user.username.characters')
      end
    end
    # modify other methods
  end
end
after_initialize do
  UsernameValidator.class_eval do
    # the same
  end
end
module UsernameValidatorExtensions
  # the same
end
after_initialize do
  class UsernameValidator
    prepend UsernameValidatorExtensions
  end
end

they all not work… my script runs without errors, but no effect. how to do that?


#2

In the same situation. Does anyone recognize this?


(Régis Hanol) #3

This is a private method, so you need to do

after_initialize do
  class UsernameValidator
    private
    def username_char_valid?
      # your code
    end
  end
end

(Robert) #4

At the moment, I do monkey patching like this:

hooks:
  after_code:
    - replace:
        global: true
        filename: /var/www/discourse/app/controllers/users_controller.rb
        from: /^.*StaffActionLogger\.new\(current_user\)\.log_check_email.*$/
        to: ""

This patch is needed to solve this issue: Intense API use floods staff log?

I understood that if I want to put this into a plugin in order to profit again from the online updater, I would need to copy first the entire method in discourse/app/controllers/users_controller.rb.

Is this right that I would have to check manually before every update that this method has not been changed upstream? Currently, the patching with pubs would fail if my patch regex does not work anymore.

Edit: the ATOM Feed Recent Commits to discourse:master May come in any.

I am also interested in changing one line in a translation file: discourse/config/locales/client.en.yml. is his possible with a plugin?