[RUBY] The story of the first Rails app refactored with a self-made helper

Introduction

I've been writing applications with Ruby on Rails I was curious about it.

This guy that comes with every time you create a controller 〇〇_helper.rb What is this file used for ... Since it says helper, is it related to helper methods ... ??

At this time, I "It must be a convenient file because it is created at the same time." I searched Qiita for commentary articles as I was interested.

Conclusion

It looks like a file that describes your own helper method. (Self-made helper == custom helper) Since the helper method has only used the things provided by Gem until today, I intuitively thought that this would be useful.

I tried using it immediately

I will refer to other people's Qiita articles This time I used it for code refactoring of my personally developed app. The refactoring content in the controller is the content of this article.

environment

Rails 5.2.3 Ruby 2.5.1

How to use

First, let's look at the controller that refactors.

users_controller.rb


class UsersController < ApplicationController

~abridgement~

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

  def check_user
    redirect_to new_user_registration_path, alert: 'Please log in or register' unless current_user.id == @user.id
  end
end

Because the less than unless in the method called check_user is not cool Create a helper method and refactor it.

helpers/users_helper.rb


module UsersHelper

  def current_user?(user)
    current_user.id == user.id
  end

end

I created a helper method called current_user ?. This method name and content seems to be quite standard.
Directly under the directory called helpers There is also a file called application_helper.rb It's like a file that manages helper methods that you apply to multiple controllers and views.

users_controller.rb


class UsersController < ApplicationController
  include UsersHelper

~abridgement~

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

  def check_user
    redirect_to new_user_registration_path, alert: 'Please log in or register' if !current_user?(@user)
  end
end

Description

When using the helper file's own helper in the controller It seems that it is necessary to read with include as in the second line.

Also, the description of unless has been changed to the description of if! ~. This made the code a little cleaner.

Refactor posts_controller with similar content.

posts_controller.rb


class PostsController < ApplicationController
  

  def edit
    redirect_to new_user_registration_path, alert: 'Please log in' unless current_user.id == @a_post.user_id
  end

  def destroy
    redirect_to new_user_registration_path, alert: 'Please log in' unless current_user.id == @a_post.user_id
    if @a_post.destroy
      redirect_to root_path, notice: 'Deleted post'
    else
      render :show, notice: 'The post could not be deleted'
    end
  end


  private

  def set_post
    @a_post = Post.find(params[:id])
  end
end

Here too, we will modify the description below unless.

First, create a helper method.

helpers/posts_helper.rb


module PostsHelper

  def current_user_post?(a_post)
    current_user.id == a_post.user_id
  end

end

We will apply this to the controller.

posts_controller.rb


class PostsController < ApplicationController
  include PostsHelper

  def edit
    redirect_to new_user_registration_path, alert: 'Please log in' if !current_user_post?(@a_post)
  end

  def destroy
    redirect_to new_user_registration_path, alert: 'Please log in' if !current_user_post?(@a_post)
    if @a_post.destroy
      redirect_to root_path, notice: 'Deleted post'
    else
      render :show, notice: 'The post could not be deleted'
    end
  end

  private

  def set_post
    @a_post = Post.find(params[:id])
  end
end

This is also done after loading the helper and refactoring.

Finally

This time I wrote an article focusing on the controller, but it can be used not only for self-made helpers but also for views. Also, when using it for a view, unlike the controller, it seems that there is no need to describe reading. I'll also refactor the view file code after this.

If you find any deficiencies, please let us know in the comments.

Reference article

--Helper loading and priority in Rails 5.0 -Summary of Rails helper methods (frequently used)

Recommended Posts

The story of the first Rails app refactored with a self-made helper
The story of making a reverse proxy with ProxyServlet
The story of making an electronic New Year's card app with Vue.js + Rails
A story packed with the basics of Spring Boot (solved)
The basics of the process of making a call with an Android app
A story about hitting the League Of Legends API with JAVA
A story that struggled with the introduction of Web Apple Pay
[Rails6] Create a new app with Rails [Beginner]
[Rails 5] Create a new app with Rails [Beginner]
How to decorate the radio button of rails6 form_with (helper) with CSS
The story of making a game launcher with automatic loading function [Java]
The story of releasing the Android app to the Play Store for the first time.
The story of learning Java in the first programming
Publish the app made with ruby on rails
The story of tuning android apps with libGDX
A review of the code used by rails beginners
[Heroku] Associate AWS S3 with the deployed Rails app
[Jackson] A story about converting the return value of BigDecimal type with a custom serializer.
Write a test by implementing the story of Mr. Nabeats in the world with ruby
First self-made app by a high school graduate engineer-Introduction-
Roughly the flow of web application development with Rails.
How to get started with creating a Rails app
The story of making dto, dao-like with java, sqlite
The story of pushing a Docker container to GitHub Package Registry and Docker Hub with GitHub Actions
The story of building a Java version of Minecraft server with GCP (and also set a whitelist)
[First post] A story about a second new graduate of PE becoming a programmer with no experience
Story of making a task management application with swing, java
[Rails] I tried to create a mini app with FullCalendar
The first WEB application with Spring Boot-Making a Pomodoro timer-
Summary of initial work when creating an app with Rails
Check the operation of two roles with a chat application
A note about the seed function of Ruby on Rails
A story addicted to toString () of Interface proxied with JdkDynamicAopProxy
A series of steps to create portfolio deliverables with Rails
Explain the benefits of the State pattern with a movie rating
Find the number of days in a month with Kotlin
Modeling a Digimon with DDD for the first time Part 1
A story stuck with NotSerializableException
Create a large number of records with one command using the Ruby on Rails seeds.rb file
When a beginner makes a personal app with rails, the procedure to bring it to the starting point anyway.
I tried incorporating the principle of a single file component into a rails 6 app. I'm not sure.
Try to imitate the idea of a two-dimensional array with a one-dimensional array
[Rails] I made a simple calendar mini app with customized specifications.
[PostgreSQL] If you want to delete the Rails app, delete the database first!
A story of connecting to a CentOS 8 server with an old Ansible
I got a warning message with the rails _6.0.3_ new hello_myapp command
The story of toString () starting with passing an array to System.out.println
The story of making a communication type Othello game using Scala.
The story of stopping because the rails test could not be done
[Illustration] Finding the sum of coins with a recursive function [Ruby]
A story that confirmed the profile of Yasuko Sawaguchi 36 years ago
[Self-study] Creating a portfolio (original app) after completing the Rails tutorial
The story of making it possible to build a project that was built by Maven with Ant
A story that I was addicted to twice with the automatic startup setting of Tomcat 8 on CentOS 8
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
Perform a large amount of csv export (output) of log information etc. on the WEB application with Rails application
[Rails] Check the contents of the object
[Java version] The story of serialization
Explanation of the order of rails routes
[Rails] Creating a new project with rails new
Creating a timer app with a muddy