Module: Wikidotrb::Common::Decorators

Included in:
Module::PrivateMessage, Module::PrivateMessageCollection, Module::Site
Defined in:
lib/wikidotrb/common/decorators.rb

Instance Method Summary collapse

Instance Method Details

#login_required(*methods)



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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/wikidotrb/common/decorators.rb', line 6

def (*methods)
  methods.each do |method|
    if singleton_methods.include?(method)
      # クラスメソッドにデコレータを適用
      singleton_class.class_eval do
        alias_method "#{method}_without_login_check", method

        define_method(method) do |*args, **kwargs|
          client = nil

          # インスタンス変数として存在するかを最初にチェック
          client ||= self.client if respond_to?(:client)

          # キーワード引数からclientを探す
          client = kwargs[:client] if kwargs.key?(:client)

          # 引数からClientインスタンスを探す
          unless client
            args.each do |arg|
              if arg.is_a?(Wikidotrb::Module::Client)
                client = arg
                break
              end
            end
          end

          # clientが見つからない場合はエラーを発生させる
          raise ArgumentError, "Client is not found" if client.nil?

          # clientのログインチェック
          client.

          # 元のメソッドの呼び出し
          send("#{method}_without_login_check", *args, **kwargs)
        end
      end
    elsif instance_methods.include?(method)
      # インスタンスメソッドにデコレータを適用
      alias_method "#{method}_without_login_check", method

      define_method(method) do |*args, **kwargs|
        client = nil

        # インスタンス変数として存在するかを最初にチェック
        client ||= self.client if respond_to?(:client)

        # キーワード引数からclientを探す
        client = kwargs[:client] if kwargs.key?(:client)

        # 引数からClientインスタンスを探す
        unless client
          args.each do |arg|
            if arg.is_a?(Wikidotrb::Module::Client)
              client = arg
              break
            end
          end
        end

        # clientが見つからない場合はエラーを発生させる
        raise ArgumentError, "Client is not found" if client.nil?

        # clientのログインチェック
        client.

        # 元のメソッドの呼び出し
        send("#{method}_without_login_check", *args, **kwargs)
      end
    else
      raise NameError, "Undefined method `#{method}` for class `#{self}`"
    end
  end
end