Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padrino controller abstraction

Tags:

ruby

padrino

I've been trying Padrino framework in one of my project, and there is one thing that really annoys me. I want to implement just for instance a user registration process using OmniAuth and want to break my request handler (controller's action) to separate methods, like this:

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 it would be nicer to push the logic to the model layer, but my question is, how could I break a controller logic to separated methods and share information among them (like using instance variables). In Rails I created these methods in the private scope of my controller, but here I should extend the Application class because it throws Undefined method exception for the previous code. I tried Helpers, but helpers don't know the instance variables, so you should pass the variables every time.

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

like image 332
Nucc Avatar asked Dec 26 '22 14:12

Nucc


1 Answers

To define a method inside an Padrino Controller you can use define_method instead of def.

For your example, do something like this:

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 https://stackoverflow.com/a/3171649 between define_method and def

like image 154
lz. Avatar answered Jan 11 '23 14:01

lz.