Simple example for plugin to change files?

I’m trying to write my first very basic plugins on Discourse, after read a lot about Ruby and the benefits the language offers to us :slight_smile:

I want to add text to specific pages like badges, leaderboard (gamification) and similar simple edits like changing the default behavior on search order results, last posts instead relevance.

I understand the best approach is avoid forking the core and write plugins. So where can I look if I want to change specific files on Discourse from a plugin?

We can take an example editing this file:

How to tell Discourse to use the plugin topic_embed.rb and replace default one?

2 Likes

This is a technique known as “monkey patching”. There are several ways to accomplish this but the easiest is to just define the method you want to replace in your plugin.

after_initialize do
  class ::TopicEmbed
    def self.imported_from_html(url)
       # your code
    end
  end
end
2 Likes

Well, we supposed to come from monkeys so after all that could be a good thing to do following your example :slight_smile:

Thanks for your reply! I’m trying it out but what can I do if I want to change the whole embed.rb file?

I see that can only be used to replace an specific class but I want to replace the embed completely removing the buttons and showing a simple onebox.

I can work on the file but I don’t know how to put that file into Discourse without forking (that seems to be gorilla patching).

1 Like

There’s so much existing material here. Just look at all the dozens of existing plugins.

Here’s an example of overriding the onebox system:

Note that patching can be very targeted and clever (this plugin isn’t particularly! But that’s partly due to the structure of this core code that makes overrides necessarily verbose) and the art of it is doing as little as possible to get the desired effect: if you are proposing to override entire files you might want to think again about your overall approach.

And again as per Richard you are almost never (in Ruby on Rails at least) overriding entire files. You need to think about methods.

2 Likes