Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

メタプログラミングRuby | 魔術 | クラスマクロ

概要

クラスマクロ

内容

クラス定義内でクラスメソッドを利用すること。
動的にメソッドを定義する際などによく利用します。
クラスマクロの代表例がRubyが提供しているattr_accesor。

ActiveSupport::Concernを利用したクラス拡張ミックスインと
セットで用いられることも多い。

サンプル

3*3の豆腐(□)の中に黒い豆腐を表示する位置を指定するクラスマクロを作ります。
移動コマンドは自分で定義可能。
サンプルはviキーバインドとゲームの十字キーを模したものにしてみました。

# encoding: utf-8
require 'active_support'

module TofuMover
  extend ActiveSupport::Concern

  module ClassMethods
    def move(key, direction)
      output = ""
      case direction
        when ""
          output =<<-EOS
------
□■□
□□□
□□□
------
          EOS
        when ""
          output =<<-EOS
------
□□□
□□□
□■□
------
          EOS
        when ""
          output =<<-EOS
------
□□□
■□□
□□□
------
          EOS
        when ""
          output =<<-EOS
------
□□□
□□■
□□□
------
          EOS
        else
          output =<<-EOS
------
□□□
□■□
□□□
------
          EOS
      end
      define_method key do
        puts output 
        return self
      end
    end
  end
end

class ViEditor
  include TofuMover
  move :k, ""
  move :j, ""
  move :h, ""
  move :l, ""
  move :stay, "-"
end

ViEditor.new.k.j.h.l.stay

class GameController
  include TofuMover
  move :↑, ""
  move :↓, ""
  move :←, ""
  move :→, ""
  move :N, "-"
end

GameController.new.↑.↓.←.→.N

出力

------
□■□
□□□
□□□
------
------
□□□
□□□
□■□
------
------
□□□
■□□
□□□
------
------
□□□
□□■
□□□
------
------
□□□
□■□
□□□
------
------
□■□
□□□
□□□
------
------
□□□
□□□
□■□
------
------
□□□
■□□
□□□
------
------
□□□
□□■
□□□
------
------
□□□
□■□
□□□
------