Redmineプラグイン開発入門(1)
こんにちは。今日は日曜日、のんびりデスクに向かっています。
今回は、前回構築した環境で、Redmineの簡単なプラグインの開発を行ってみたいと思います。
前回の開発環境構築の話はこちらになります。 it-managers-life.hatenablog.com
環境
- Winsows10 WSL
- Ubuntu 18.0 LTS
- Ruby 2.5
- Rails 4.2
- MySQL 5.7
- Redmine 3.4.9
今回は入門編ということで、ユーザーの一覧表示をするプラグインを作成していきます。
1. プラグインの雛形作成
以下のコマンドを入力します。
$ cd /mnt/c/rails_projects/redmine-3.4.9 $ bundle exec rails generate redmine_plugin ShowUsers
plugins/show_users/ にプラグインの雛形が作成されます。
2. 基本情報の編集
show_users/init.rb を編集します。一部の情報はRedmineのplugin管理画面で表示されます。
Redmine::Plugin.register :show_users do name 'Show Users plugin' author 'Author name' description 'This is a plugin for Redmine' version '0.0.1' url 'http://example.com/path/to/plugin' author_url 'http://example.com/about' end
3. コントローラの雛形作成
以下のコマンドを入力します。
$ bundle exec rails generate redmine_plugin_controller show_users show index
コントローラの雛形が作成されます。
4. コントローラの編集
show_users/app/controllers/show_controller.rbを編集します。ここで全ユーザーの情報を取得しています。
class ShowController < ApplicationController unloadable # 認証 before_action :global_authorize # # インデックス # def index # 全ユーザーを取得する all_users = User.where(type: "User").where(status: 1) # 名前を配列に入れる @names = [] all_users.each do |user| @names << user.firstname + user.lastname end end # # ログインユーザーを取得する # def set_user @current_user ||= User.current end # # ログインユーザーでなければエラー # def global_authorize set_user render_403 unless @current_user.type == 'User' end end
5. ビューの編集
app/views/shows/index.html.erbを編集します。ここでユーザの一覧を出力します。
<h2>ShowController#index</h2> <table class="list" style="max-width: 400px; align: right;"> <tr> <th>ユーザー名</th> </tr> <% @names.each{|value| %> <tr> <td><%= value %>さん</td> </tr> <% } %> </table>
6. メニューの追加
show_users/init.rb を編集します。今回はアプリケーションメニューに追加します。
Redmine::Plugin.register :show_users do name 'Show Users plugin' author 'Author name' description 'This is a plugin for Redmine' version '0.0.1' url 'http://example.com/path/to/plugin' author_url 'http://example.com/about' #アプリケーションメニューに「ユーザー表示」を表示する menu :application_menu, :show_users, { :controller => 'show', :action => 'index' }, :caption => 'ユーザー表示', :if => Proc.new { User.current.logged? } end
7. ルーティングの設定
show_users/config/routes.rbを編集します。最初は空になっています。
# Plugin's routes # See: http://guides.rubyonrails.org/routing.html Rails.application.routes.draw do resources :show end
8. 実行
アプリケーションメニューから「ユーザーの表示」をクリックします。下図の様に表示されます。
以上で終わりです。
今回は、簡単なプラグインを作成することで、雰囲気が理解できたのではないでしょうか。
これからプラグインを作ってみたいという方の参考になれば幸いです。では、また次回。