Search code examples
ruby-on-railsrubycontrollerdryprivate-methods

How to stay DRY using private methods?


I'm on Rails 5.0. Creating new controllers and adding more and more code there I've discovered that I have quite a lot of identical methods in private sections of each class like

private

def find_post
  @post = Posts.find(params[:id])
end

def find_user
  @user = User.find(params[:id])
end

def find_group
  ...
end

and so on.

Is there any way to include a "standard" set of private methods to all the classes that need it?


Solution

  • You can use concerns in controllers just like you can in models.

    Just define a concern called Finders or something in app/controllers/concerns/finders.rb and then include Finders to use it.

    Also note that since Ruby 2.0 def actually returns a symbol with the method name, so it is possible to do something like the following:

    private def find_post
      @post = Posts.find(params[:id])
    end
    
    private def find_user
      @user = User.find(params[:id])
    end
    

    While it's true that this leads to slightly more typing, it's more explicit and much less error prone than the class level access modifiers.