Rails plugin generator

Newbie note: you must run the generator in the Discourse source directory (that’s /src if you use Docker). Otherwise you’ll just get confusing error/help messages about how the parameters are incorrect for rails new.

5 лайков

There seems to be a mismatch between the plugin generator and this post. Specifically, the Beginner’s Guide suggests to create the javascript initializer with the following directory and naming structure:

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

However, the plugin creates the javascript initializer at

plugins/discourse-racoon/assets/javascripts/initializers/discourse-racoon.es6

Personally, I was having issues with the javascript loading after using this plugin until I changed the directory and naming structure to match the Beginner’s guide. Should the package be updated?

4 лайка

Yes would be better indeed.

3 лайка

Yes I had to rename the JavaScript extensions but the structure worked for me.

this thing breaks for me.

Cant help you, you give me no context. What did you type? where did you type it? clean or exisisting state?

6 лайков

I followed this tutorial https://meta.discourse.org/t/beginners-guide-to-creating-discourse-plugins-part-1/30515. Just installed and worked so guess its clean.
I typed:

bundle exec rails g plugin cidian

EDIT: Capitalization matters in ruby. The name of the plugin created by this generator gets to be a ruby class so that’s why a lower case argument supplied to this generator will lead to a broken plugin.

No it’s not clean as you have followed this tutorial to create a plugin, and the error is likely in what you typed while following the tutorial.

The error is very clear to me: mount ::cidian::Engine, at: "/cidian" is invalid. You should fix this in your code.

2 лайка

First of all: I dont know ruby (yet) as I will start from the front end.
this code was produced by this plugin generator. so its not my fault. Its the generators fault. I typed nothing while following the tutorial. I just followed the development environment setup guide for ubuntu. Before running the generator the local discourse instance worked fine.
https://github.com/discourse/discourse/blob/master/lib/generators/plugin/templates/plugin.rb.erb
to be very clear: I am just at the first page of this tutorial. specifically the part that links to this plugin generator.

Я только что внес масштабное обновление в это.

Впереди ещё многое: специфические генераторы (например, добавление одного контроллера) и административные плагины.

12 лайков

Вау! Выглядит отлично в диффе (для того, кто очень мало знает о написании плагинов). Не терпится попробовать (но я, скорее всего, подожду, пока не приду в офис в понедельник :wink:)

2 лайка

Привет, @j.jaffeux, я только что попробовал (снова сделал git pull и создал ещё несколько плагинов после того, как в первый раз не получилось) и получаю:

/home/pfaffman/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/actionpack-5.2.3/lib/action_dispatch/routing/mapper.rb:314:in `block (2 levels) in check_controller_and_action': 'one_two/one-two' is not a supported controller name. This can lead to potential routing problems. See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use (ArgumentError)

Мне грустно, потому что у меня есть плагин, который начался с этого, и я добавил в него много кода перед запуском. Можешь подсказать, как это исправить? Информация в том руководстве и то, что я нашёл на StackOverflow, мне не помогли.

Спасибо.

Да, я наткнулся на это и пока не исправил.

Думаю, это должно быть controllers/one_two/one_two_controller.rb, но не уверен, так как вы не предоставили все данные.

4 лайка

Кажется, я нашёл его! Проблема была в config/routes.rb. Я изменил

 get "/" => "three-four#index", constraints: ThreeFourConstraint.new

на

get “/” => “three_four#index”, constraints: ThreeFourConstraint.new

и теперь всё в порядке, по крайней мере на мой неискушённый взгляд.

Как мне это сделать?

Пытаюсь использовать это в моей новой среде Deb для Windows Subsystem
Мой Discourse работает и запускается, но при попытке выполнить

rails g plugin --help

я получаю:

/var/lib/gems/2.5.0/gems/railties-6.0.0/lib/rails/app_loader.rb:53: warning: Insecure world writable dir /home/jose/.rbenv/shims in PATH, mode 040777
Could not find actionview_precompiler-0.2.1 in any of the sources
Run `bundle install` to install missing gems.

Выполнение bundle install ничего не делает (новое), а precompiler есть в списке gems.
Есть какие-то идеи?

Запущен ли ваш сервер Discourse в контейнере Docker? Если да, то bundle install нужно запускать внутри контейнера.

Нет, я так не думаю. Это тестовая среда, это был прямой клон из git.

Это сработало идеально из коробки.

Спасибо за это.

Только что запустил этот генератор для Rails, создал базовую структуру нового плагина, загрузил его в Git, добавил в YAML-файл, пересобрал приложение, и он установился безупречно из коробки.

Перешёл на вкладку плагинов, и вот она — полностью оснащённая настройкой включения/выключения по умолчанию. :heart:

Огромное спасибо @j.jaffeux за этот простой в использовании и полезный генератор.

Единственное изменение, которое я внёс, — это удаление папки .git через rm -rf и повторная инициализация Git, чтобы я мог отправить репозиторий в свой аккаунт. Но это, скорее всего, связано с тем, что я не очень хорошо разбираюсь в git, и мне часто приходится «колотить» команды git молотком, чтобы они работали так, как я ожидаю.

Безупречный генератор. Ещё раз спасибо @j.jaffeux

4 лайка

Рад, что у вас получилось. Честно говоря, мне стоит уделить этому время, так как многие вещи работают некорректно.

6 лайков