Padrino controller abstraction

I am trying to use the Padrino scheme in one of my projects, and there is one thing that really annoys me. I want to implement, for example, the process of registering users using OmniAuth and I want to split the request handler (controller action) to separate methods, for example:

  get ": provider / callback" do
   @user = find_the_user_by_oauth (request)
   create_user unless @user
   store_user_in_session
 end

 def find_the_user_by_oauth (request)
   # ...
 end

 def store_user_in_session
   session [: user_id] = @ user.id
 end

I know that it would be better to push the logic to the model layer, but my question is how can I split the controller logic into divided methods and exchange information between them (for example, using instance variables). In Rails, I created these methods in a private area of ​​my controller, but here I have to extend the Application class because it throws an Undefined method exception for the previous code. I tried Helpers, but helpers don't know instance variables, so you have to pass variables every time.

What is a good way to make my controller actions clean in Padrino?

+4
source share
2 answers

To define a method inside the Padrino controller, you can use define_method instead of def .

In your example, do the following:

Admin.controllers :dummy do define_method :find_the_user_by_oauth do |request| request.params["username"] # ... end define_method :store_user_in_session do session[:user_id] = @user end get :test do @user = find_the_user_by_oauth(request) create_user unless @user store_user_in_session() session.inspect end end 

Padrino runs the block sent to Admin.controllers using instance_eval. See this answer for the differences fooobar.com/questions/299772 / ... between define_method and def

+11
source

possible offtopic, but consider the Espresso Framework instead.

then you can solve your problem as simple as:

 class App < E def index provider, action = 'callback' @user = find_the_user_by_oauth create_user unless @user store_user_in_session end private def find_the_user_by_oauth # provider, action are accessed via `action_params` # action_params[:provider] # action_params[:action] end def store_user_in_session session[:user_id] = @user.id end end 
-2
source

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


All Articles