before_action don't work for BotController actions
luizcarvalho opened this issue · comments
Describe the bug
I tried use before_action to handle messages in BotController.route
, but not work, I tried use in action of another Controller, and works. Why?
To Reproduce
class BotController < Stealth::Controller
helper :all
before_action :print_this, only: :route
def route
if current_session.present?
step_to session: current_session
else
step_to flow: 'hello', state: 'say_hello'
end
end
def print_this
puts "\n\n\n\n\n aaaaaaaaaaaaaaaaaaa \n\n\n\n"
end
end
Expected behavior
Show print_this
message in log
@luizcarvalho if you remove the only: :route
part, does it work? I suspect it's because route
isn't actually an action.
@mgomes still not working without only
option.
route
isn't a action? oh no... =(
The callback chain (before
, after
, around
) get called around a controller action. The route
method is really just a special method.
What if you just called your action inside the route method?
class BotController < Stealth::Controller
helper :all
def route
print_this # before
if current_session.present?
step_to session: current_session
else
step_to flow: 'hello', state: 'say_hello'
end
end
def print_this
puts "\n\n\n\n\n aaaaaaaaaaaaaaaaaaa \n\n\n\n"
end
end
@mgomes I see it now.
print_this is only a example, I have same methods to call in route and I do not want put all in route methods... and I thought about using the before_action for this. But if no possible, I'll do this.
Thanks.
We typically handle Facebook payloads in a similar way. Our BotController
usually looks something like this for Facebook bots:
class BotController < Stealth::Controller
before_action :current_user
def route
if current_message.payload.present?
handle_payloads
current_message.payload = nil
return
end
if current_session.present?
step_to session: current_session
else
step_to flow: 'hello', state: 'say_hello'
end
end
private
def handle_payloads
case current_message.payload
when 'new_user'
step_to flow: 'hello'
when 'developer_restart', 'restart'
step_to flow: 'goodbye', state: 'restart'
end
end
def current_user
@current_user ||= begin
user = User.find_by(recipient_id: current_user_id)
unless user.present?
user = persist_current_user
end
user
end
end
def persist_current_user
fb_profile = Stealth::Services::Facebook::Client.fetch_profile(
recipient_id: current_user_id
)
user = User.create!(
recipient_id: current_user_id,
first_name: fb_profile['first_name'],
last_name: fb_profile['last_name'],
profile_pic: fb_profile['profile_pic']
)
user
end
end