lib/te_bot/court.rb in te_bot-0.2.0 vs lib/te_bot/court.rb in te_bot-0.3.0

- old
+ new

@@ -25,23 +25,35 @@ @commands[text] = block end ::TeBot::Message::GENERAL_MESSAGE_TYPES.each do |m| define_method(m) do |&block| - instance_variable_get("@#{m}") || instance_variable_set("@#{m}", block) - instance_variable_get("@#{m}") + @message_handlers ||= {} + + if block.respond_to?(:call) + @message_handlers[m] = block + else + @message_handlers[m] + end end end + + def message_handlers(handler) + @message_handlers ||= {} + @message_handlers[handler] + end end def call(env) json_only(env) do |body| response = handle_request(body) - if response.is_a?(Array) - status, headers, body = response - [status, headers, body] + case response + in [Integer, Hash, Array] => rack_response + rack_response + in Hash => json_body + [200, {"Content-Type" => "application/json"}, [JSON.generate(json_body)]] else [200, {"Content-Type" => "application/json"}, [JSON.generate({"message" => "success"})]] end end end @@ -76,12 +88,12 @@ elsif self.class.default_command.respond_to?(:call) self.class.default_command.call(conn) end end - ::TeBot::Message::GENERAL_MESSAGE_TYPES.each do |f| - message.public_send(f) do - handler = self.class.public_send(f) + ::TeBot::Message::GENERAL_MESSAGE_TYPES.each do |message_type| + message.public_send(message_type) do + handler = self.class.message_handlers(message_type) next unless handler.respond_to?(:call) handler.call(conn) end end