Class: Viberroo::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/viberroo/response.rb

Overview

Wraps callback response and provides helper methods for easier parameter access.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Response

Returns a new instance of Response.

Examples:

class ViberController < ApplicationController
  skip_before_action :verify_authenticity_token

  def callback
    # For example, params contain the following:
    # { foo: { bar: { baz: :boo }}}
    @response = Viberroo::Response.new(params.permit!)
    # Those can be accessed through params:
    puts @response.params.foo
    # Or directly:
    puts @response.foo
    puts @response.foo.bar
    puts @response.foo.bar.baz
    @bot = Viberroo::Bot.new(response: @response)

    head :ok
  end
end

Parameters:

  • params (Hash)

    Parameters from API callback.


36
37
38
# File 'lib/viberroo/response.rb', line 36

def initialize(params)
  @params = RecursiveOpenStruct.new(params.to_h)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method) ⇒ Object


59
60
61
# File 'lib/viberroo/response.rb', line 59

def method_missing(method)
  params.public_send(method)
end

Instance Attribute Details

#paramsObject (readonly)

Accessor for response parameters.


11
12
13
# File 'lib/viberroo/response.rb', line 11

def params
  @params
end

Instance Method Details

#user_idInteger || nil

Unifies user id access. Different callback events return user id differently. This method unifies user id access interface based on callback event type. Original user id params remain available in ‘params` attribute reader.

Returns:

  • (Integer || nil)

46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/viberroo/response.rb', line 46

def user_id
  case @params.event
  when 'conversation_started', 'subscribed'
    @params.user.id
  when 'unsubscribed', 'delivered', 'seen', 'failed'
    @params.user_id
  when 'message'
    @params.sender.id
  else
    @params.dig(:user, :id)
  end
end