class Rubotnik::MessageDispatch

Routing for messages

Attributes

message[R]
user[R]

Public Class Methods

new(message) click to toggle source
# File lib/rubotnik/message_dispatch.rb, line 12
def initialize(message)
  @message = message
  p @message.class
  p @message
  @user = Rubotnik::UserStore.instance.find_or_create_user(@message.sender['id'])
end

Public Instance Methods

route(&block) click to toggle source
# File lib/rubotnik/message_dispatch.rb, line 19
def route(&block)
  if @user.current_command
    command = @user.current_command
    execute(command)
    Rubotnik.logger.info "Command #{command} is executed for user #{@user.id}"
  else
    bind_commands(&block)
  end
rescue StandardError => error
  raise unless ENV["DEBUG"] == "true"
  stop_thread
  say "There was an error: #{error}"
end

Private Instance Methods

bind(*regex_strings, all: false, to: nil, reply_with: {}) { || ... } click to toggle source
# File lib/rubotnik/message_dispatch.rb, line 40
def bind(*regex_strings, all: false, to: nil, reply_with: {})
  return if @matched

  regexps = regex_strings.map { |rs| /\b#{rs}/i }
  proceed = regexps.any? { |regex| @message.text =~ regex }
  proceed = regexps.all? { |regex| @message.text =~ regex } if all
  return unless proceed
  @matched = true
  if block_given?
    yield
    return
  end
  handle_command(to, reply_with)
end
bind_commands(&block) click to toggle source
# File lib/rubotnik/message_dispatch.rb, line 35
def bind_commands(&block)
  @matched = false
  instance_eval(&block)
end
default() { || ... } click to toggle source
# File lib/rubotnik/message_dispatch.rb, line 68
def default
  return if @matched
  Rubotnik.logger.info 'None of the commands were recognized'
  yield
  @user.reset_command
end
execute(command) click to toggle source
# File lib/rubotnik/message_dispatch.rb, line 75
def execute(command)
  method(command).call
end
handle_command(to, reply_with) click to toggle source
# File lib/rubotnik/message_dispatch.rb, line 55
def handle_command(to, reply_with)
  if reply_with.empty?
    Rubotnik.logger.info "Command #{to} is executed for user #{@user.id}"
    execute(to)
    @user.reset_command
    Rubotnik.logger.info "Command is reset for user #{@user.id}"
  else
    say(reply_with[:text], quick_replies: reply_with[:quick_replies])
    @user.assign_command(to)
    Rubotnik.logger.info "Command #{to} is set for user #{@user.id}"
  end
end