File: filter.rb

package info (click to toggle)
ruby-pluggaloid 1.7.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 260 kB
  • sloc: ruby: 1,752; sh: 4; makefile: 2
file content (52 lines) | stat: -rw-r--r-- 1,565 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# -*- coding: utf-8 -*-

class Pluggaloid::Filter < Pluggaloid::Handler
  NotConverted = Class.new
  THROUGH = NotConverted.new.freeze

  # フィルタ内部で使う。フィルタの実行をキャンセルする。Plugin#filtering はfalseを返し、
  # イベントのフィルタの場合は、そのイベントの実行自体をキャンセルする。
  # また、 _result_ が渡された場合、Event#filtering の戻り値は _result_ になる。
  def self.cancel!(result=false)
    throw :filter_exit, result end

  CANCEL_PROC = method(:cancel!)

  # ==== Args
  # [event] 監視するEventのインスタンス
  # [name:] 名前(String | nil)
  # [slug:] フィルタスラッグ(Symbol | nil)
  # [tags:] Pluggaloid::HandlerTag|Array フィルタのタグ
  # [&callback] コールバック
  def initialize(event, **kwrest, &callback)
    kwrest[:name] ||= '%s line %i' % callback.source_location
    super(event, **kwrest)
    @callback = callback
    event.add_filter self end

  # イベントを実行する
  # ==== Args
  # [*args] イベントの引数
  # ==== Return
  # 加工後の引数の配列
  def filtering(*args)
    length = args.size
    result = @callback.call(*args, &CANCEL_PROC)
    case
    when THROUGH == result
      args
    when length != result.size
      raise Pluggaloid::FilterError, "filter changes arguments length (#{length} to #{result.size})"
    else
      result
    end
  end

  # このリスナを削除する
  # ==== Return
  # self
  def detach
    @event.delete_filter(self)
    self end

end