Nice programing

Rails : Partials는 인스턴스 변수를 인식해야합니까?

nicepro 2020. 11. 26. 19:54
반응형

Rails : Partials는 인스턴스 변수를 인식해야합니까?


예를 들어 Ryan Bates의 nifty_scaffolding은

edit.html.erb

<%= render :partial => 'form' %>

new.html.erb

<%= render :partial => 'form' %>

_form.html.erb

<%= form_for @some_object_defined_in_action %>

숨은 상태가 불편해서 평소에하는 게 좋아요

edit.html.erb

<%= render :partial => 'form', :locals => { :object => @my_object } %>

_form.html.erb

<%= form_for object %>

그래서 어느 것이 더 낫습니다 : a) 부분적으로 인스턴스 변수에 액세스 하거나 b) 필요한 모든 변수를 부분적으로 전달합니까?

나는 늦게 b)를 선택했지만 약간의 피클이 발생했습니다.

some_action.html.erb

<% @dad.sons.each do |a_son| %>
<%= render :partial => 'partial', :locals => { :son => a_son } %>
<% end %>

_partial.html.erb

The son's name is <%= son.name %>
The dad's name is <%= son.dad.name %>

son.dad는 아빠를 가져 오기 위해 데이터베이스 호출을합니다! 따라서 @dad에 액세스해야합니다. a) 부분 액세스 인스턴스 변수를 사용 하거나 로컬에서 @dad를 전달하여 render : partial을 <% = render : partial => 'partial'로 변경해야합니다. , : locals => {: dad => @dad, : son => a_son} %> 그리고 어떤 이유로 든 내 부분에 vars를 전달하면 불편 함을 느낍니다. 다른 사람들도 이런 식으로 느끼는 것 같습니다.

그게 말이 되길 바랍니다. 이 모든 것에 대한 통찰력을 찾고 있습니다 ... 감사합니다!


최신 버전의 Rails에서는 부분을 렌더링하고 로컬을 전달하는 것이 훨씬 쉽습니다. 이 대신.

<%= render :partial => 'form', :locals => { :item => @item } %>

할 수 있습니다.

<%= render 'form', :item => @item %>

이전 버전과의 호환성을 유지하기 위해 Nifty Scaffold 생성기에서이 작업을 수행하지 않지만 향후 릴리스에서이를 변경할 것입니다.

부분적으로 인스턴스 변수를 사용하는 것이 허용되는지 여부. 그렇다고 생각합니다. 모든 실용성에서 단점은 무엇입니까? 일관성이 없으면 일이 잘 풀릴 수 있지만이 지침을 적용하고 싶습니다.

  1. 부분적으로 공유하기 위해 인스턴스 변수를 만들지 마십시오. 일반적으로 이것은 컨트롤러 리소스 개체 만 공유한다는 것을 의미합니다.

  2. 부분이 리소스와 동일한 이름이면 <%= render @item %>.

  3. 부분이 여러 컨트롤러에서 공유되는 경우 로컬 만 사용하십시오.

어쨌든 이것은 나에게 잘 맞는 것입니다.

보너스 팁 : 많은 지역 사람들을 부분으로 전달하고 그중 일부를 선택적으로 전달하려는 경우 부분을 렌더링하는 도우미 메서드를 만듭니다. 그런 다음 항상 도우미 메서드를 사용하여 부분 렌더링을위한 선택적 인수로 깨끗한 인터페이스를 만들 수 있습니다.


@instance_variables를 부분적으로 사용하는 것은 잘못된 디자인입니다.

partials에서 인스턴스 변수를 사용하면 작동하지만 변경이 필요한 경우 응용 프로그램을 유지 관리하기가 더 어려워 질 수 있습니다.

부분에서 인스턴스 변수를 사용하는 단점은 부분의 범위 (커플 링)를 벗어난 것에 대한 종속성을 부분에 생성한다는 것입니다. 이로 인해 부분을 재사용하기가 더 어려워지고 한 부분을 변경하려는 경우 응용 프로그램의 여러 부분에서 강제로 변경할 수 있습니다.

인스턴스 변수를 사용하는 부분 :

  • 부분을 ​​사용하는 컨트롤러의 인스턴스 변수가 인스턴스 변수 이름이나 유형 또는 데이터 구조를 변경하면 변경해야합니다.
  • 인스턴스 변수가 사용되는 방식이 변경 될 때 부분을 사용하는 모든 컨트롤러 동작이 동일한 방식으로 동시에 변경되도록합니다.
  • 동일한 이름과 데이터로 인스턴스 변수를 설정하는 작업에서만 쉽게 재사용 할 수 있으므로 재사용을 권장하지 않습니다.

대신 지역을 부분에 전달하십시오.

<%= render 'reusable_partial', :item => @item %>

이제 부분 만 참조 item하고는 참조 하지 않으므로 @itemreusable_partial을 렌더링하는 뷰를 렌더링하는 작업은 reusable_partial 및이를 렌더링하는 다른 작업 / 뷰에 영향을주지 않고 자유롭게 변경할 수 있습니다.

<%= render 'reusable_partial', :item => @other_object.item %>

또한 @item이없는 컨텍스트에서 재사용 할 수 있습니다.

<%= render 'reusable_partial', :item => @duck %>

If my @duck changes in the future and no longer quacks like reusable_partial expects it to (the object's interface changes), I can also use an adapter to pass in the kind of item that reusable_partial expects:

<%= render 'reusable_partial', :item => itemlike_duck(@duck) %>

Always?

There are plenty of situations where you probably don't need de-coupled partials like this, and it's easier in the short run to use an instance variable. However, it's hard to predict the future needs of your application.

As such, this makes for good general practice while having relatively low cost.


You can have it both ways. At the top of your partial:

<% item ||= @item %>

That way, it works with or without passing the local variable, providing a sane default, but not inhibiting alternate usage of the partial.


I vote for a) for a very specific reason - DRY! If you start passing a variable - like that - the next thing you know - it's a mess - let's say you need to change the way your variable is named or something else about it - then you need to go to ALL your views and change them instead of ONE partial. Also - if you change your partial - let's say it produces a table with some result, it will change on all your views, so you'll need to know which views are used, a proper IDE should be able to help you with that, but I also like having a small comment section at the top of the view - where I just mention where it's used and why - helps another programmer and it helps you to remember in case you need to come back to a partial and modify. But the whole point of the partial is to call it WITHOUT having to pass anything from the view, so that you don't have to modify all places where partial is called from if that variable changes somehow.

Ultimately this is a design choice - and to be honest unless you are running a facebook the extra lookup you do is not that big of a deal, but it's just not very DRY.

P.S.: Just thought about it - you can actually abstract the way you call partial in a helper method, so then if the way you call your partial needs to change - then you just need to modify one place.

참고URL : https://stackoverflow.com/questions/2503838/rails-should-partials-be-aware-of-instance-variables

반응형