RoR: Polymorphic Controllers

I have an existing site that has a bunch of different models and controllers. I am currently integrating Twilio services on this site. Twilio allows you to specify the URL that will be called when the user interacts with your phone number using your phone. Unfortunately, there is only one URL that you can provide Twilio, and then all parsing is done at your end.

So now I have a twilio controller that analyzes user data and decides what they are trying to do.

Everything that a user can try to do through his phone can already be done on the website, but now they have the opportunity to use their phone on the go. If they change my number "create group foo", then the site will try to create the group accordingly. My problem is that I already have a group controller that knows how to create groups and has the appropriate before_filters to make sure the user has permission to do this, by the way.

Is there a way for the twilio controller to parse the request and then β€œforward” it to the correct controller? I would prefer that the twilio controller does not duplicate all the code and filters that are in every other controller, and some of these things do not feel good to be inserted into models.

I am a little new to rails in general, so I am open to any offer. I hope that there will be a design template that suits my use case, and I am ready to reorganize the entire project for the right solution.

+4
source share
1 answer

I think there are a few things you can do. If you do not need to respond in a specific format, you can simply redirect the request with an appropriately formatted parameter. For instance:

class TwilioController def create if params[:twilio_action] == 'create group' redirect_to create_group_path(:id => params[:group_id], :number => params[:number]) end end end 

There is a good chance that you will have authentication problems, because twilio api will not send and receive cookies for you, so you will not have an authenticated user. If so, it is best to put all of your common code in the model and handle cookie authentication using your GroupController check and phone number using TwilioController. For instance:

 class TwilioController def create if params[:twilio_action] == 'create group' if can_create_group?(params[:phone_number]) Group.create(:id => params[:group_id]) end end end end 

It is always better to put your business logic in your model, but if you really have a function that you want to share in two controllers, you can always create a module for this:

 module GroupControllerActions def create_group user Group.create(params[:group].merge({:user => user})) end end class TwilioController include GroupControllerActions def create if params[:twilio_action] == 'create group' create_group(User.find_by_number(params[:phone_number])) end end end class GroupsController def create create_group(current_user) end end 
+4
source

Source: https://habr.com/ru/post/1339890/


All Articles