Discourse 플러그인 개발 - 1부 - 기본 플러그인 만들기

일단 몇 가지 비정상적인 동작(quirk)을 익히고 나면 Discourse 플러그인을 만드는 것은 정말 간단할 수 있습니다. 이 게시물의 목표는 기본 구조(skeleton) 플러그인을 생성하고 기본 사항을 소개하는 것입니다.

개발 환경

컴퓨터에서 실행 중인 Discourse 개발 환경이 있는지 확인하세요. 적절한 설치 가이드를 사용하여 설정을 마치고 다시 돌아오시기를 권장합니다.

plugin.rb

:tada: https://github.com/discourse/discourse-plugin-skeleton을(를) 사용하여 plugins 디렉터리에 완전한 discourse 플러그인 스켈레톤을 생성하세요 :tada:

스켈레톤은 이제 discourse 코어에 포함됩니다. rake plugin:create[plugin-name]을(를) 실행하면 스켈레톤을 사용하여 플러그인이 생성됩니다.

Discourse가 시작될 때, plugins 디렉터리에 plugin.rb 파일이 포함된 하위 디렉터리를 찾습니다. plugin.rb 파일에는 두 가지 목적이 있습니다. 첫째, 플러그인의 이름, 연락처 정보 및 설명 등 플러그인에 대한 필수 정보가 포함된 매니페스트입니다. 둘째, 플러그인을 실행하는 데 필요한 루비(ruby) 코드를 초기화하는 것입니다.

이 경우 루비 코드를 추가하지 않지만 plugin.rb는 여전히 필요합니다. basic-plugin이라는 디렉터리를 만들고 그 안에 다음 내용을 포함하는 plugin.rb 파일을 생성해 보겠습니다:

basic-plugin/plugin.rb

# name: basic-plugin
# about: A super simple plugin to demonstrate how plugins work
# version: 0.0.1
# authors: Awesome Plugin Developer
# url: https://github.com/yourusername/basic-plugin

이 파일을 생성한 후 로컬 서버를 재시작하면 플러그인이 로드됩니다.

중요한 함정(Gotcha)!

일반적인 Rails 개발에 익숙하다면 플러그인은 변경 사항을 재로딩(reload)하는 것이 그렇게 매끄럽지 않다는 것을 알아차릴 수 있습니다. 일반적으로 플러그인 변경 사항을 적용할 때는 서버를 중지하기 위해 Ctrl+c를 누른 다음 bin/dev로 서버를 다시 실행해야 합니다.

변경 사항이 적용되지 않았습니다! :warning:

새 파일을 생성하거나 오래된 파일을 삭제할 때 특히 캐시가 완전히 지워지지 않는 경우가 있습니다. 이 문제를 해결하려면 tmp 폴더를 제거하고 Rails를 다시 시작하세요. Mac에서는 하나의 명령어로 수행할 수 있습니다: rm -rf tmp; bin/dev.

플러그인이 로드되었는지 확인하기

로컬 서버를 재시작한 후 URL /admin/plugins에 방문하세요. (플러그인 등록 정보는 관리자만 볼 수 있으므로, 먼저 관리자 계정으로 로그인해야 합니다).

모든 것이 정상이라면, 목록에서 플러그인을 볼 수 있어야 합니다:

축하합니다. 첫 번째 플러그인을 생성했습니다!

자바스크립트 추가해 보기

현재 플러그인은 아무것도 하지 않습니다. Discourse가 로드될 때 경고 상자를 띄우는 자바스크립트 파일을 추가해 봅시다. 이것은 사용자들에게 매우 성가신 동작이 될 것이며 실제 플러그인으로 권장되지 않지만, 실행 중인 애플리케이션에 자바스크립트를 삽입하는 방법을 보여줍니다.

다음 파일을 생성하세요:

plugins/basic-plugin/assets/javascripts/discourse/initializers/alert.js

export default {
  name: "alert",
  initialize() {
    alert("alert boxes are annoying!");
  },
};

이제 로컬 서버를 재시작하면 화면에 "alert boxes are annoying!"이(가) 나타나는 것을 볼 수 있습니다. (나타나지 않았다면, 위의 “변경 사항이 적용되지 않았습니다” 섹션을 참고하세요).

이 동작 방식을 단계별로 살펴보겠습니다:

  1. assets/javascripts/discourse/initializers에 배치된 자바스크립트 파일은 Discourse 애플리케이션이 로드될 때 자동으로 실행됩니다.

  2. 이 특정 파일은 name과 initialize 함수가 포함된 객체 하나를 export합니다.

  3. name은 고유해야 하므로, 간단히 alert라고 이름 붙였습니다.

  4. initialize() 함수는 애플리케이션이 로드될 때 호출됩니다. 이 경우 단순히 alert() 코드를 실행할 뿐입니다.

프론트엔드를 위한 데이터 사전 로드(Preloading)

plugin.rb에서 register_preloaded_data를 사용하면 추가 요청 없이 초기 HTML 응답에 데이터를 포함할 수 있습니다:

after_initialize do
  register_preloaded_data("visibility") do |guardian|
    { can_access: guardian.authenticated? }
  end
end

Core는 키에 플러그인의 # name: 메타데이터를 접두어로 붙입니다. 위의 basic-plugin의 경우, 프론트엔드 초기화 스크립트에서 파싱된 값을 읽으려면 다음을 사용하세요:

import PreloadStore from "discourse/lib/preload-store";

const visibility = PreloadStore.get("basic-plugin:visibility");

이 블록은 애플리케이션 레이아웃을 렌더링하는 각 페이지 로드시 실행되며, 요청의 Guardian을 인자로 받아 JSON으로 직렬화 가능한 값을 반환합니다. 이러한 값들은 캐시된 익명 사이트 페이로드와 별도로 처리됩니다. 항목을 생략하려면 nil을 반환하면 되며, false는 포함됩니다. 비활성화된 플러그인의 블록은 건너뜁니다. Guardian을 통해 민감한 데이터의 범위를 요청 사용자로 제한하세요.

이제 여러분은 공식적인 Discourse 플러그인 개발자입니다!


시리즈의 다른 부분

1부: 이 주제
2부: 플러그인 Outlet
3부: 사이트 설정
4부: git 설정
5부: 관리자 인터페이스
6부: 수락 테스트(Acceptance tests)
7부: 플러그인 배포


이 문서는 버전 관리를 하고 있습니다 - github에서 변경 사항을 제안하세요.

110개의 좋아요
Plugin API documentations?
How to create a new plugins?
Connecting to database with a plugin
Separating View from Data, Plugins, Modularity
Categories Topic Replies
Added custom initializer
Create fully custom header
Overwriting controllers in plugin
How can I add "dislike" button?
Developing Discourse Plugins - Part 2 - Connect to a plugin outlet
Which files can you override from a plugin?
Developing Discourse Plugins - Part 5 - Add an admin interface
How to transfer data from plugin to app/views templates?
Which is Better? Discourse or Flarum?
Hide features for non-admin users through plugin
Customizing handlebars templates
How to properly display jalali dates for Persian language
Topic Ratings Plugin
Enable Like-Button for not logged-in visitors
Why do I need a block storage?
Custom Field not working
Rails plugin generator
Why GNU License?
Code reading help. ES6, plugin-outlet `_connectorCache`, custom-html `_customizations`, appEvents
Customizing handlebars templates
Application Files after Digital Ocean Setup
Application Files after Digital Ocean Setup
Application Files after Digital Ocean Setup
Make an external http request from discourse
Specify user by external id
How can I make my own Discourse plugins?
Reputation and level on member profile
How to Change User Profile Picture
Something like shortcodes for Discourse?
Calendar plugin features to make it really useful for us
Plugin Documentation Style Guide
Any options for over-riding the username restrictions?
How would updating effect custom overrides?
I would like to change the template completely
Adding a second tag description
Rails plugin generator
Creating a plugin
Fatal: Not a git repository (or any parent up to mount point /discourse)
Fatal: Not a git repository (or any parent up to mount point /discourse)
Adding command line tools support for user api keys
Discourse Code Modification for personal use
Plugin routing problems
[PAID] Mentorship needed
Can You Restrict Signups Using `swot` Email Verification?
Plugin API documentations?
Insert tag based upon word match
Triggering account creation/login on external service when a user logs in on discourse
Place for total coding beginners to learn how to customise?
Add additional button post menu
Fetch third party data for topic list
The Ignore User feature (now in 2.3.0.beta7)
Help with a plugin
Create Custom APIs
Proper Development and Deployment
How to make only a group of users can send messages to staff
How might we better structure #howto?
Theme-Component v Plugin: What's the difference
Creating Parsing Extensions
How can I customized my own site
All latest images in posts from a category
(Ruby) Selecting only posts that are made by non-original posters
Hosting discourse on our infrastructure AWS
Display FullName instead of UserName in the Profile
Calling Python scripts w/ arguments on the backend via plugin?
Extend Existing Controller?
How to add custom fields to models
Extend Existing Controller?
Bot writer's tip: Processing every post
Add user to group after purchase
Support for proposed plug-in
Autocompletion for a user field at signup
Custom discourse with limited features
Overriding user_guardian.rb in a plugin (no fork necessary!)
Problems with git clone
Friendly user profile url
Website Integration
Discourse developement environment setup
How to show Full Name in Embeds
How to display full name in comments embeds
Rake task "assets:precompile" is failing due to JS Compilation issue
Change code does not work in VS Studio code editor
Edit Code
Discourse Chain Topics Plugin
Contributing to Discourse
How to edit topics/show.html.erb
Install Discourse on macOS for development
Developing Discourse Plugins - Part 3 - Add custom site settings
Developing Discourse Plugins - Part 4 - Setup git
Developing Discourse Plugins - Part 7 - Publish your plugin
Developing Discourse Plugins - Part 6 - Add acceptance tests
Learn how to start building stuff for Discourse if you're newbie (like myself)
How to disable updating username for admins & moderators?
Backend code
Backend code
Install Discourse on Ubuntu or Debian for Development
How to make changes on backend side of discourse application using rails
Introduction to Discourse Development
Discourse blog (article and comments)
How to learn more about Discourse back-end?
I want to learn how to program for Discourse
Discourse Audio Message
Create custom Automations
How can one add a toggle button to the post menu and implement an action for that toggle button in a Discourse plugin?
Content box
Create an advertising page
Discourse 有自定义插件模板吗,如何写自定义插件呢
Deploy custom Discourse repository via docker
Multiple custom fields for topics similar to custom userfields
How do I go about making a very customized theme?
How can I create a Discourse that's just like Stemaway.com?
Adding new columns to user lists in groups
How to pin a post within a topic?
Ruby script to send automatic welcome message to new users
:cn: Installing the Discourse development environment on Ubuntu 在 Ubuntu 上安装 Discourse 开发环境
Admin not accessible because of auto-minify for Cloudflare
Admin not accessible because of auto-minify for Cloudflare
Update Password Encryption Method
Store pdf and doc files as raw text in the database - Where to start?
How to turn off "Body seems unclear, is it a complete sentence?'
Hosting dynamic pages with discourse
Invisible way to force display order of tags?
Controllers and Routes
Learn about Discourse client-side flow?
How do you learn to build Discourse plugins?
How do you learn to build Discourse plugins?
Discourse 部署成功后如何接入小程序、APP?
I'm trying to run discourse app locally in production env without docker
Customizing CSS via plugin
About the Plugin category
Visual diagraming to add visual dimension to Conversations?
Custom Onebox engine
How can I install my own plugin written in Ruby?
Allow reply-to individual instead of topic/forum (mailing list feature)
Adapt github changes to my own site
Push to digital ocean from command line and rebuild
How to convince my university to use/install Discourse?
Hack to enable invitations for Trust level 1 users
Dropcaps in Discourse - cannot override span tag
Getting certain posts to Zapier
Plugin: add a menu icon (next to search)
Error When creating custom plugin
Error When creating custom plugin
IOTA as a currency for Discourse
New columns in directory (/users)
Bootstrap fails when plugin file specifies gem version range
Running my own discourse image
How to add a job to cron/anacron when creating Docker container

I am able to create plugin in development, it works fine. Thanks.
But I don’t see a way to install other’s plugin in development
So first question is how can I fork someone’s plugin in development and then build on top of that(hope copy paste that repo is not the recommended way)?
Second question is, it seems my created plugin is part of my repo, is there a way to create a separate github repo for the plugin automatically which others can directly use to install?

1개의 좋아요

I have a preferred method to do this. First, I have a ~/code directory where I have all my git projects. So I check out discourse and the plugin in that directory so it’s something like this:

~/code

discourse
discourse-some-plugin

Then, within the ~/code/discourse/plugins folder I create a symlink to the plugin:

$ cd ~/code/discourse/plugins
$ ln -s ~/code/discourse-some-plugin .

Then for good measure:

$ cd ~/code/discourse
$ rm -rf tmp
$ bundle exec rails server

Now you can fork the plugin in ~/code/discourse-some-plugin, make pull requests or whatever you want. It’ll be used by discourse.

13개의 좋아요

What is the best way to render ajax response inside a widget?
I was able to console.log the ajax response, but it is not rendering inside the widget.

Tried to call this.scheduleRerender() after getting ajax response but both results in an infinite loop.

1개의 좋아요

I am getting following error when trying to load a helper module inside my widget

Could you please help me to resolve this error?
Thanks

You should make sure your widget can contain state. After the ajax request, set it on the state object and trigger a this.scheduleRerender and it should appear. For an example look at how the post menu shows who liked something.

Looks like you have the wrong path to your helper. One way to see all the paths that Discourse has resolved is by typing require._eak_seen in your console. Look for the correct path name.

Thanks Robin Ward for your help. I was able to load my module after investigating with require._eak_seen.

Below is the code for my widget. The problem is that this.scheduleRerender() is causing an infinite loop. The div always shows loading animation (even without this.scheduleRerender) which seems this.state.loading is not being set.

import { createWidget } from 'discourse/widgets/widget';
import { getTopic } from 'discourse/plugins/my-plugin/discourse/helpers/topics';
import { ajax } from 'discourse/lib/ajax';
import { h } from 'virtual-dom';

export default createWidget('topic-widget', {
  tagName: 'div.my-topics',
  defaultState() {
    return { loading: false};
  },

  refreshTopic() {
    if (this.state.loading) { return; }
    this.state.loading = true;
    this.state.topic = 'empty';
    getTopic(this).then((result) => {
      console.log(result);
      this.state.topic = result;
      this.state.loading = false;
      this.scheduleRerender();
    });
  },

  html(attrs, state) {
    if (!state.topic) {
      this.refreshTopic();
    }
    const result = [];
    if (state.loading) {
      result.push(h('div.spinner-container', h('div.spinner')));
    } else if (state.topic !== 'empty') {
      result.push(state.topic);
    } else {
      result.push(h('div.no-messages', 'No topic.'))
    }

    return result;
  },
});

Could you help to resolve this error?

Your code looks mostly fine, however, all widgets that deal with state require a key attribute. You should have seen a warning about this, although maybe the warning only appears when running tests?

Try adding a buildKey function like buildKey: () => 'topic-widget'.

That should probably fix it. Also, a much less serious issue is you might want to add topic: null to your state object. Javascript is much faster when it knows the shape of the object in advance.

5개의 좋아요

Thanks Robin Ward.
Adding buildKey function worked fine for me.

1개의 좋아요

@eviltrout I got bitten by this in development and didn’t get a warning about setting a key attribute.

3개의 좋아요

Ah, it only warns in Ember.testing:

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/widgets/widget.js.es6#L153

We might want to just raise an error if that happens now? It is pretty dangerous for Widgets to do that.

4개의 좋아요

:thumbsup: for raising an error instead. Maybe we can extend that to development too? :thought_balloon:

2개의 좋아요

Hopefully this will prevent others from making this mistake:

https://github.com/discourse/discourse/commit/d4bbdcd7d63ddbf20239c95d1ba1cee9030d7e95

6개의 좋아요

Hi,

Is this url correct? Shouldn’t this be ,

I’m new here. please correct me if im wrong :slight_smile:

In Discourse, mainly there are two big JavaScript sections “discourse” and “admin”. Also you can see few more in https://github.com/discourse/discourse/tree/master/app/assets/javascripts.

In plugins, to differentiate admin & normal user section JavaScript files we use “discourse” and “admin” keywords in between like below

plugins/basic-plugin/assets/javascripts/discourse/initializers/alert.js.es6
plugins/basic-plugin/assets/javascripts/admin/initializers/alert.js.es6


Also it will just work even without identification keywords like you mentioned :slight_smile:

11개의 좋아요

@vinothkannans Thank you a lot for the explanation. :slight_smile:

I’m experiencing the same issue with getting symlinks to work (I’m on Linux) - the ln -s appears to work, but from inside the docker container the path is inaccessible. The plugin works when it is directly copied into the plugins folder, but I like the symlink workflow as it enables a more sensible Git arrangment.

This SO question appears to suggest that symlinks won’t work this way unless we also add the linked-to plugin volume to the docker run command https://stackoverflow.com/questions/38485607/mount-host-directory-with-a-symbolic-link-inside-in-docker-container

Anyone any thoughts on this? What are the pro plugin developers doing for a sensible Git workflow?

2개의 좋아요

I’m using symlinks but my dev setup is Docker-frei.

Symlinks are a really nice way of being able to include or exclude plugins on a ‘build’ very quickly without disturbing the codebase.

2개의 좋아요

Here’s what I’ve had to do in order to preserve a similar workflow to using symlinks (softlinks):

I edited /bin/docker/boot_dev in Discourse (outside the container) so that the plugin I want to work on is added as a volume and mounted in the /src/plugins/ directory (inside the container).

In my case it looks like this:

docker run -d -p 9405:9405 -p 1080:1080 -p 3000:3000 -p 9292:9292 \
-v "$DATA_DIR:/shared/postgres_data:delegated" \
-v "$SOURCE_DIR:/src:delegated" \ 
-v "/home/marcus/code/discourse/discourse-reflective-learning-plugin:/src/plugins/discourse-reflective-learning-plugin" \
$ENV_ARGS --hostname=discourse --name=discourse_dev --restart=always \
discourse/discourse_dev:release /sbin/boot

I’ve used absolute paths because I couldn’t be bothered to get into relative paths inside Docker and $SOURCE_DIR environment variables, but I’m sure there’s a cleverer way to do this, so that perhaps all your plugins could be in directories at the same level as discourse and it would automagically include them all. Hope this helps someone.

2개의 좋아요

I am totally open to a PR that automatically follows symlinks in plugins/ dir and then smart mounts volumes.

4개의 좋아요