class DbBot::Translate

Attributes

collection[RW]
number[RW]
query[RW]
response[RW]
search_query[RW]
table[RW]
target_attribute[RW]
verb[RW]
when[RW]

Public Class Methods

new(message) click to toggle source
# File lib/db_bot/translate.rb, line 21
def initialize(message)
  @message = message
end
perform(*args) click to toggle source
# File lib/db_bot/translate.rb, line 17
def self.perform(*args)
  return new(*args).tap { |use_case| use_case.perform }
end

Public Instance Methods

perform() click to toggle source
# File lib/db_bot/translate.rb, line 25
def perform
  init_wit_client

  construct_entities

  process_verb

rescue TranslateException => e
  @response = e.message
end

Private Instance Methods

construct_entities() click to toggle source
# File lib/db_bot/translate.rb, line 43
def construct_entities
  translation = @client.message(@message)
  puts entities = translation['entities']

  @table  = entities['table'][0]['value'] if entities['table']
  @query  = entities['query'][0]['value'] if entities['query']
  @verb   = entities['verb'][0]['value'] if entities['verb']
  @when   = ::DateTime.parse(entities['datetime'][0]['value']) if entities['datetime']
  @number = entities['number'][0]['value'] if entities['number']
  @target_attribute = entities['target_attribute'][0]['value'] if entities['target_attribute']
  @search_query = entities['search_query'][0]['value'] if entities['search_query']
end
count_verb() click to toggle source

Verbs

# File lib/db_bot/translate.rb, line 71
def count_verb
  find_class

  if @when
    @response = @class.where('created_at >= ?', @when).size.to_s
  else
    @response = @class.all.size.to_s
  end
end
find_class() click to toggle source

Helpers

# File lib/db_bot/translate.rb, line 99
def find_class
  @class = @table.singularize.camelize.constantize

rescue NameError
  raise TranslateException, 'Class cannot be found'
end
init_wit_client() click to toggle source
# File lib/db_bot/translate.rb, line 38
def init_wit_client
  @client = Wit.new(access_token: 'RAS7ZDEPPJCGRTYONX7Q2UP6JOMY4OF2')
  # @client = Wit.new(access_token: ENV['WIT_ACCESS_KEY'])
end
process_verb() click to toggle source
# File lib/db_bot/translate.rb, line 56
def process_verb
  case @verb
  when 'count'
    if @table && @query
      return count_verb
    end
  when 'return'
    return return_verb
  end

  @response = "Please try again"
end
return_verb() click to toggle source
# File lib/db_bot/translate.rb, line 81
def return_verb
  find_class

  if @target_attribute
    @collection = @class.where(@target_attribute.to_sym => @search_query)
  else
    @collection = @class.limit(@number || 100)
  end

  if @collection.any?
    @response = 'There you go'
  else
    @response = "There weren't any #{@table}"
  end
end