X
X
Xip
Search…
handle_message
The handle_message method is one of the most fundamental controller methods in Xip. It enables you to succinctly handle messages without needing long if/else or case statements.

Example

Here's an example of what it looks like:
1
def get_call_response
2
handle_message(
3
:yes => proc { step_to state: :say_yes },
4
'Not available' => proc { step_to state: :say_no_problem },
5
:no => proc { step_to state: :say_no_problem },
6
:call => proc { step_to state: :say_call_later }
7
)
8
end
Copied!
In this example, the handle_message method has four different "match arms". Each arm is just key => value pair since it's all just a hash. The keys are the match expressions. The values are procs that serve as the action to take if the match expression is matched.
Xip accepts match expressions in five different ways:
    1.
    A string (like Line 4)
    3.
    A symbol (like Lines 3, 5, and 6)
    4.
    A regex
    5.
    nil
The procs can be multi-line and thus perform more than one action. In the docs for the match expressions we'll include some of those examples.

Proc Scope

If you are new to Ruby, you might be wondering about procs. You can think of them as anonymous functions from Javascript or closures.
The code inside of the proc is executed if the match expression is matched. That code has access to the same variables as the containing method's scope. So for example:
1
def get_response
2
x = 15
3
handle_message(
4
'Buy' => proc {
5
x += 1
6
},
7
'Refinance' => proc {
8
x += 2
9
}
10
)
11
end
Copied!
In this example if a user sends the message "Buy", the value of x will be 16. Similarly, if the user sends the message "Refinance", the value of x will be 17.
Last modified 9mo ago
Copy link