Sha256: 351c8e0239d76d14711092f4adec55470a374b07aafbd5ecc5382709c61d115e

Contents?: true

Size: 984 Bytes

Versions: 2

Compression:

Stored size: 984 Bytes

Contents

module Workers
  class Processor < Base
    HANDLERS = {
      '\A\/start(\s.*|\z)' => Commands::Start,
      '\A\/stop\z'         => Commands::Stop
    }.freeze

    def perform(message_dump)
      process_message YAML.load(message_dump)
    end

    private

    def process_message(message)
      user = user_by_message(message)
      command_klass(message).invoke(message, user)
    end

    def user_by_message(message)
      from = message.from
      user = Models::User.find_or_initialize_by(telegram_id: from.id)
      if user.new_record?
        user.update(first_name: from.first_name, last_name: from.last_name, username: from.username)
      end
      user
    end

    def command_klass(message)
      command_klass_by_text(message.text) || Commands::Missing
    end

    def command_klass_by_text(text)
      key = HANDLERS.keys.find { |regex| /#{regex}/ =~ prepare_text(text) }
      HANDLERS[key]
    end

    def prepare_text(text)
      text.strip
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
telegrator-0.2.0 lib/telegrator/generators/bot/templates/app/workers/processor.rb.tt
telegrator-0.2.0.rc1 lib/telegrator/generators/bot/templates/app/workers/processor.rb.tt