티스토리 뷰

해당 글은 https://blog.naver.com/kbs4674/221236404213 로 부터 게시글이 이전되었습니다.

 

보통은 코드를 하나의 파일속에 모두 뭉쳐놓으면 다른 사람과 협업할 때 불편하다는 단점이 존재합니다.

(C언어로 표현하자면 메인함수 안에 모든 코드를 표현하는거라고 볼 수 있음.)

 

코드의 분산 개념인 render 대해 내용을 다뤄보겠습니다.

 

 

  • 코드의 분산 : render 예시 보기

레일즈에서도 코드를 분산하는 명령어인 render 이라는 개념이 존재합니다.

일단 2가지 케이스 예시를 보여드리겠습니다,

 

 Case1  게시글 내용 열람 ( app/views/posts/show.html.erb )

 

show.html.erb

1.아래 코드는 게시판(Scaffold)의  app/views/posts/show.html.erb  내용입니다.

## app/views/posts/show.html.erb
 
<p id="notice"><%= notice %></p>
 
<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>
 
<p>
  <strong>Content:</strong>
  <%= @post.content %>
</p>
 
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

 

2. 예시로 저는 아래 코드를  show.html.erb  로부터 따로 분리시켜보겠습니다.

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>
 
<p>
  <strong>Content:</strong>
  <%= @post.content %>
</p>

 

3. 분산을 시키면 아래와 같은 결과가 나옵니다.

1) app/views/posts/show.html.erb

## app/views/posts/show.html.erb
 
<p id="notice"><%= notice %></p>
 
<%= render "/posts/post_content" %>
 
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

 

2) app/views/posts/_post_content.html.erb (posts View 내에서 별도로 새로 파일을 생성해야 함.)

## app/views/posts/_post_content.html.erb
 
<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>
 
<p>
  <strong>Content:</strong>
  <%= @post.content %>
</p>

 

 

4. 결과적으로 show.html.erb 파일 속 일부 코드는 _post_content.html.erb 파일속에 담아내고,

render로 분산처리해서 간결하게 코드를 줄였습니다.

 

 

 Case 2  게시글 목록 (app/views/posts/show.html.erb)

index.html.erb

1. 다음 코드는 게시판(Scaffold)의  app/views/posts/index.html.erb  내용입니다.

## app/views/posts/index.html.erb
 
<p id="notice"><%= notice %></p>
 
<h1>Posts</h1>
 
<table>
  <thead>
    <tr>
      <th colspan="3"></th>
    </tr>
  </thead>
 
  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>
 
<br>
 
<%= link_to 'New Post', new_post_path %>

 

2. 이번 예시는 <% @posts.each do |post| %><% end %> 사이의 코드를 따로 분산시켜 보겠습니다.

1) app/views/posts/index.html.erb

## app/views/posts/index.html.erb

<p id="notice"><%= notice %></p>
 
<h1>Posts</h1>
 
<table>
  <thead>
    <tr>
      <th colspan="3"></th>
    </tr>
  </thead>
 
  <tbody>
    <% @posts.each do |post| %>
        <%= render "/posts/list" %>
    <% end %>
  </tbody>
</table>
 
<br>
 
<%= link_to 'New Post', new_post_path %>

2) app/views/posts/_list.html.erb (posts View 내에서 별도로 새로 파일을 생성해야 함.)

## app/views/posts/_post_content.html.erb

<tr>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>

 

3. 위와같이 코드를 분산하고, 결과를 보면

에러가 납니다.

분명 Case 1과 똑같이 했음에도 왜 이런 오류가 발생하는걸까요?

 

4. 그 이유는 each do에 있습니다.

아래 코드에 있어 render 함수로 지목되는 파일에는 each do로부터 상속된 변수(post)에 대한 정보를 알려줘야 합니다.

## app/views/posts/index.html.erb

<% @posts.each do |post| %>
    <%= render "/posts/list" %>
<% end %>

 

 

5. 따로 render을 위해 만들어진  _post_content.html.erb  속에 정의된 post 명칭은  index.html.erb  에서 따로

' _list,html.erb 내 post 변수는 index.html.erb의 post 변수의 정보를 가지고 있다! ' 라는 설명이 넘어오지 않는 한 그냥 허울뿐인 이름에 지나지 않습니다.

## app/views/posts/_list.html.erb

<%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>

 

6. 교정 후 최종적인 코드는 다음과 같이 작성해주면 됩니다.

(이해를 돕고자 _list.html.erb 내 post 변수를 t 변수로 바꾸겠습니다.)

1) app/views/posts/index.html.erb

## app/views/posts/index.html.erb
 
<p id="notice"><%= notice %></p>
 
<h1>Posts</h1>
 
<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>
 
  <tbody>
    <% @posts.each do |post| %>
      <%= render "/posts/index_list", t: post %>
    <% end %>
  </tbody>
</table>
 
<br>
 
<%= link_to 'New Post', new_post_path %>

2) app/views/posts/_index_list.html.erb

## app/views/posts/_list.html.erb
 
<tr>
    <td><%= link_to 'Show', x %></td>
    <td><%= link_to 'Edit', edit_post_path(x) %></td>
    <td><%= link_to 'Destroy', x, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>

render에서 부가적으로 정보를 알릴 때, ' t는 @posts 변수의 객체로부터 상속받은 post 변수다 ' 라고 위와같이 알려줌으로서 오류 해결이 됩니다.

 

 

  • render함수 : 들여다보기

위와같이 저희는 2가지 render Case 예시 봤는데요,

예제들에는 공통적인 규칙이 있습니다.

 

  • render로 지목되는 파일 이름은 항상 맨 첫 이름이 _(밑줄) 이 들어가야 한다.
  • <%= render '...' %> 에서 파일을 지목할 땐, 확장자, 밑줄 작성은 생략한다.
  • 파일의 주소 경로는  app/views  에서 부터 시작된다.

위와같이 3개의 공통점을 가지게 되는데, render을 사용함에 있어 기본적으로 지켜줘야 합니다.

또 더불어 render 함수를 쓰면서 당부드리고 싶은 말이 있습니다.

 

1. 너무 연이어서 render을 쓰지마세요.

render에 render에 render에... (나중에 코드 찾기 복잡해지면서 힘들어짐.)

 

2. render대상 파일 이름은 성격에 맞게 잘 지어주세요.

 ex  식당 메뉴 관련 결과를 보여주는 render 파일이라면  _meal.html.erb 

 

3. 같은 render속성 끼리는 하나의 폴더를 더 만들어서 분류정리를 잘 해주세요.

정리 제대로 안하면 나중에 유지보수가 힘들어집니다.

 

 

  •  render 함수의 장점
  • 분산화 해서 작업할 때 편리하다. (C언어의 '함수'의 장점과 유사.)
  • _(파일이름) 파일은 재 사용이 가능하다 보니 코드 작성의 수고가 줄어든다.
  • 코드가 간결해 지면서 가독성 부여

 

루비온 레일즈 Ruby on Rails ROR

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함