on_message和on_private_message

时间:2017-03-22 01:01:03

标签: ruby-on-rails ruby c9.io xmpp4r

我目前正在Cloud9上使用XMPP4R。

conference.on_message {|time, nick, text|
     case text
        when /regex/i
            #Same Command as on_private_message
        end
     end
}

conference.on_private_message {|time,nick, text|
     case text
        when /regex/i
            #Same Command as on_message
        end
     end
}

conference.on_message是来自聊天的会议消息,conference.on_private_message是会议的私人消息聊天。

我想将on_message和on_private_message都设为1而不是上面显示的2。

我尝试了类似这样的事情(如下),但它只有conference.on_private_message。我怎样才能成功呢?

(conference.on_message || conference.on_private_message) { |time, nick, text|
    case text
        when /regex/i
            #Same Command on both on_message and on_private_message
        end
     end  
}

1 个答案:

答案 0 :(得分:0)

As I understand the purpose is to DRY your code. It might be worth creating a Proc object and sending it to both functions.

proc = Proc.new { |time, nick, text|
case text
    when /regex/i
        #Same Command on both on_message and on_private_message
    end
 end  
}
conference.on_message(&proc)
conference.on_private_message(&proc)

You could also try using #send method.

[:on_message, :on_private_message].each { |m| conference.send(m, &proc) }