Групиране на общ код във view-тата

18 views
Skip to first unread message

Kiril Mitov

unread,
Sep 1, 2015, 2:04:28 AM9/1/15
to ruby-on-rai...@googlegroups.com
Здравейте,

Някой сблъсквал ли се е със следния проблем (на английски защото го питам и по други форуми ):

Question: How could I extract common view divs into another view, called _section?

I have two models Episode and Playlist with the following two views:

For Episode:

<div class="name">
    <%= link_to episode.name, episode_path(episode) %>
</div>

<div class="description">
    <%= link_to episode.description episode_path(episode) %>
</div>

For Playlist:

<div class="name">
    <%= link_to playlist.name, playlist_path(playlist) %>
</div>

<div class="description">
    <span>Some special span</span>
    <%= raw(playlist.description) %>
</div>

The common things between this two views are the

<div class="name">. <div class="description"> 

but the content of this two divss is different for each view.

Question: How could I extract this two common divs into another view, called _section?

What have I tried:

  1. Cells -> they give me a nice view model with properties, but I could not find a way to added additional HTML elements between the places where the properties will be put.

  2. Yield and Content_for-> I have tried to create a separate _section layout with:

_section.html.erb

<div class="name">
    <%= yield :name %>
</div>

<div class="description">
    <%= yield :description %>
</div>

and then two views. The Episode view will render the following

<% render layout: "section" do %>
 <% content_for :name do %>
     <%= link_to episode.name, episode_path(episode) %>
 <% end %>
 <% content_for :description do %>
     <%= link_to episode.description episode_path(episode) %>
 <% end %>
<% end %>

This kind of works until you get to caching (they said content_for does not work with caching and I need to cache this) and the other problem I had was that you should include an additional empty not named yield.


Поздрави,

Кирил


--
+359 878 93 30 94
"Robopartans"
www.robopartans.com
robopartans-facebook

Do something great today. You are giving a day of your life for it.

Valentin Mihov

unread,
Sep 1, 2015, 2:49:32 AM9/1/15
to ruby-on-rai...@googlegroups.com
Сигурен ли си че това е правилната абстракция която търсиш? Дали всъщност не трябва да имаш отделни view-та за episode и playlist? Мисля че начина да си отговориш на този въпрос е като видиш колко if-а ще трябва да имаш ако са в едно view.

Иначе аз бих подходил с някакъв partial, на който му се подават като параметри данните, или като отделни ключове, или като някакъв вид обект (може да не е active record model, а някакъв твой си обект). Ако усетиш че се налага много custom HTML да инжектираш, според мен това показва че просто трябва да имаш отделни view-та.

--Вальо

Kiril Mitov

unread,
Sep 1, 2015, 3:24:24 AM9/1/15
to ruby-on-rai...@googlegroups.com
Благодаря. 

В момента view-тата са отделни и се търпи донякъде.
Custom HTML-а между двете view-та e около 3-4 реда. Не е много.  Но ме дразнят еднаквите div-ове.
Общият обектът го пробвах и става лесно докато не ти се наложи да сложи малко html. Тогава започваме да пишем html-а по helper-и и по други логики и ни ги изнася от view-то.

Кирил

Valentin Mihov

unread,
Sep 1, 2015, 3:34:46 AM9/1/15
to ruby-on-rai...@googlegroups.com
> Общият обектът го пробвах и става лесно докато не ти се наложи да сложи
> малко html. Тогава започваме да пишем html-а по helper-и и по други
> логики и ни ги изнася от view-то.

Защо не сложиш HTML-а във самото view и там със if-ове кое кога да се
включва? Ако верно става въпрос за нещо малко предполагам дори е
по-добре да оставиш малко дуплициран код докато не дойдат още
изисквания. Тогава най-вероятно вече ще си проличи на къде отиват нещата
и как най-добре да се разцепят работите.

Иначе може да видиш дали декоратори няма да ти свършат работа:
https://github.com/drapergem/draper

Успех!

signature.asc
Reply all
Reply to author
Forward
0 new messages