class Messenger::Bot::Api

Constants

ENDPOINTS
POOL_SIZE

Attributes

token[R]

Public Class Methods

new(token) click to toggle source
# File lib/messenger/bot/api.rb, line 17
def initialize(token)
  @token = token
end

Public Instance Methods

call(endpoint, raw_params = {}) click to toggle source
# File lib/messenger/bot/api.rb, line 45
def call(endpoint, raw_params = {})
  params = build_params(raw_params)
  response = self.class.post("/me/#{endpoint}?access_token=#{token}", query: params)
  if response.code == 200
    response.to_hash
  else
    fail Exceptions::ResponseError.new(response),
         'Messenger API has returned the error.'
  end
end
method_missing(method_name, *args, &block) click to toggle source
Calls superclass method
# File lib/messenger/bot/api.rb, line 21
def method_missing(method_name, *args, &block)
  endpoint = method_name.to_s
  endpoint = camelize(endpoint) if endpoint.include?('_')

  ENDPOINTS.include?(endpoint) ? call(endpoint, *args) : super
end
respond_to_missing?(*args) click to toggle source
Calls superclass method
# File lib/messenger/bot/api.rb, line 28
def respond_to_missing?(*args)
  method_name = args[0].to_s
  method_name = camelize(method_name) if method_name.include?('_')

  ENDPOINTS.include?(method_name) || super
end
user_profile(user_id) click to toggle source
# File lib/messenger/bot/api.rb, line 35
def user_profile(user_id)
  response = self.class.get("#{user_id}?fields=first_name,last_name,profile_pic&access_token=#{token}")
  if response.code == 200
    response.to_hash
  else
    fail Exceptions::ResponseError.new(response),
         'Messenger API has returned the error.'
  end
end

Private Instance Methods

build_params(h) click to toggle source
# File lib/messenger/bot/api.rb, line 58
def build_params(h)
  h.each_with_object({}) do |(key, value), params|
    params[key] = sanitize_value(value)
  end
end
camelize(method_name) click to toggle source
# File lib/messenger/bot/api.rb, line 80
def camelize(method_name)
  words = method_name.split('_')
  words.drop(1).map(&:capitalize!)
  words.join
end
jsonify(value) click to toggle source
# File lib/messenger/bot/api.rb, line 75
def jsonify(value)
  return value unless value.is_a?(Array)
  value.map { |i| i.to_h.select { |_, v| v } }.to_json
end
jsonify_with_file_preservation(value) click to toggle source
# File lib/messenger/bot/api.rb, line 68
def jsonify_with_file_preservation(value)
  if !value.is_a?(File)
    return value.to_h.to_json
  end
  return value
end
sanitize_value(value) click to toggle source
# File lib/messenger/bot/api.rb, line 64
def sanitize_value(value)
  jsonify(jsonify_with_file_preservation(value))
end