Module: Whatsapp::Rails::ModelExtension

Defined in:
lib/whatsapp/rails/model_extension.rb

Overview

ActiveRecord macro for adding WhatsApp functionality to models.

Extended into ActiveRecord::Base automatically by the Railtie.

Destination mode (default)

One global WhatsApp account sends to the model's phone attribute:

class Customer < ApplicationRecord has_whatsapp :phone end customer.whatsapp.send_message("hello")

Account mode

Each record has its own WhatsApp account (multi-session):

class Hotel < ApplicationRecord has_whatsapp :phone, account: true end hotel.whatsapp.connect hotel.whatsapp.send_message(to: "+33...", text: "Bienvenue")

Instance Method Summary collapse

Instance Method Details

#has_whatsapp(phone_attribute, account: false, session: nil) ⇒ void

This method returns an undefined value.

Declare WhatsApp capabilities on a model.

Examples:

Destination mode

has_whatsapp :phone

Account mode with default key

has_whatsapp :phone, account: true
# session_key = "ClassName_id"

Account mode with custom lambda

has_whatsapp :phone, account: true, session: -> { "hotel-#{id}" }

Parameters:

  • phone_attribute (Symbol)

    attribute containing the phone number

  • account (Boolean) (defaults to: false)

    if true, each record gets its own WhatsApp session

  • session (String, Proc, nil) (defaults to: nil)

    custom session key (account mode only). Can be a static string or a lambda evaluated in instance context.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/whatsapp/rails/model_extension.rb', line 42

def has_whatsapp(phone_attribute, account: false, session: nil) # rubocop:disable Naming/PredicateName
  if 
    define_method(:whatsapp) do
      session_key = if session.is_a?(Proc)
        instance_exec(&session)
      elsif session
        session.to_s
      else
        "#{self.class.name}_#{id}"
      end
      Whatsapp::AccountProxy.new(session_key: session_key)
    end
  else
    define_method(:whatsapp) do
      phone = send(phone_attribute)
      Whatsapp::RecordProxy.new(phone)
    end
  end
end