LoginSignup
2
3

More than 5 years have passed since last update.

Rubyでプラグイン機能を実現する

Posted at

Rubyでプラグイン機能を実現するための自分なりの方法。

概要

入力があって、それをいじっていくタイプのプラグイン機構を作りたい。例えば、rubyという入力があって、大文字にするプラグインと、2回繰り返すプラグインがあったら、RUBYRUBYとなる。

ディレクトリ構造

+--main.rb
+--plugins
|  +--pluginA
|  |  +--plugin.rb
|  +--pluginB
|  |  +--plugin.rb

プラグインを追加したい場合

例えば、大文字にするプラグイン(upcase)を追加したい場合

plugins/upcase/plugin.rb
class UpcasePlugin
  def on_message(msg)
    msg.upcase!
  end
end

ソース

main.rb
plugins = []
Dir.entries('plugins').each do |name|
    path = "plugins/#{name}"
    next if File.ftype(path) != 'directory' or %w(. ..).include? name

    require_relative path + '/plugin.rb'
    name[0] = name[0].upcase
    plugins << Module.const_get("#{name}Plugin").new
end

loop do
    msg = gets.chomp!
    plugins.each{|plugin| plugin.on_message(msg) }
    puts msg
end

エラー処理皆無ですw。plugins内にあるディレクトリをプラグインとみなし、その中にあるplugin.rbをrequireすることでファイルをロードし、Module.const_getでクラスを取得してnewしています。プラグインを使うときは、eachでぐるぐる回します。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3