LoginSignup
8

More than 5 years have passed since last update.

HubotのCoffeeScriptで外部クラスを読み込む方法

Last updated at Posted at 2016-06-15

はじめに

Hubotを使ってSlackのbotを作ろうと思って、
既存のクラスを使いまわしたいなーと思った時にハマったのでメモ

いろんなサイトを見ていると、window.Hogeのようにwindowオブジェクトのプロパティにしてしまえとか、@Hogeとしてしまえという話が多かった。

だがしかし、Hubotには画面がないからwindowオブジェクトなんてないし、
@が使えるのも画面を管理するview側からだけ。

解決策

ひとことで言うと、呼ばれる側のクラスclass Hogemodule.exports = (robot)の中で、module.exports = Hogeとしてあげればいい。

そして呼び出す側は、Hoge = require('./hoge')としてあげれば自由に使うことができる。

ソースコード

シンプルに書くと以下の様な感じ。

hoge.coffee
class Hoge
  constructor: (@robot) ->

module.exports = (robot) ->
  hoge = new Hoge robot

  robot.hear /hogehoge/i, (msg) ->
    msg.send "hogehoge"

  module.exports = Hoge

で、呼び出す側では

fuga.coffee
Hoge = require('./hoge')

module.exports = (robot) ->
  hoge = new Hoge robot

のようにする。

ちなみに

hoge.coffeeをjsに変換してみると以下のようになる。

hoge.js
var Hoge;

Hoge = (function() {
  function Hoge(robot1) {
    this.robot = robot1;
  }

  return Hoge;

})();

module.exports = function(robot) {
  var hoge;
  hoge = new Hoge(robot);
  robot.hear(/hogehoge/i, function(msg) {
    return msg.send("hogehoge");
  });
  return module.exports = Hoge;
};

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
8