AnthonyGalli.com AnthonyGalli.com - 1 month ago 6
Ruby Question

What should I do with a repeatedly used chunk of code that includes ruby & CSS?

I've neglected the DRY principle of ruby on rails for a long time. I use this same chunk of code over and over in different view files:

<div class="challenge-accomplished-date-banner">
<% if @correct_user %>
<%= challenge.notes.count.to_s.rjust(2, "0") %>
<% else %>
<%= challenge.notes.publish.count.to_s.rjust(2, "0") %>
<% end %>
</div>
<% if challenge.categorization == "adventure" %>
<%= link_to categorization_path(categorization: :adventure) do %>
<span class="glyphicon glyphicon-picture", id="challenge-flag"></span>
<% end %>
<% elsif challenge.categorization == "health" %>
<%= link_to categorization_path(categorization: :health) do %>
<span class="glyphicon glyphicon-heart", id="challenge-flag"></span>
<% end %>
<% elsif challenge.categorization == "work" %>
<%= link_to categorization_path(categorization: :work) do %>
<span class="glyphicon glyphicon-briefcase", id="challenge-flag"></span>
<% end %>
<% elsif challenge.categorization == "gift" %>
<%= link_to categorization_path(categorization: :gift) do %>
<span class="glyphicon glyphicon-tree-deciduous", id="challenge-flag"></span>
<% end %>
<% else %>
<%= link_to categorization_path(categorization: :wacky) do %>
<span class="glyphicon glyphicon-glass", id="challenge-flag"></span>
<% end %>
<% end %>
<% if challenge.duels.present? && challenge.duels.last.duelers.order(id: :asc).last.accept =! false %>
<span class="glyphicon glyphicon-tower", id="challenge-flag"></span>
<% elsif challenge.conceal == true %>
<span class="glyphicon glyphicon-eye-close", id="challenge-flag"></span>
<% else %>
<span class="glyphicon glyphicon-eye-open", id="challenge-flag"></span>
<% end %>


Not sure what to do with it? Do I put it in...

module ApplicationHelper
def banner
# See Above Code Chunk
end
end


But it doesn't work with CSS? Is there a way to allow CSS in the helper? Or do I put this chunk of code somewhere else like in the model, but then I run into the same CSS problem? Thanks!

Answer

Create a CATEGORIES constant

CATEGORIES = {
  adventure: 'glyphicon-picture',
  health:    'glyphicon-heart',
  work:      'glyphicon-briefcase',
  gift:      'glyphicon-tree-deciduous'
}

CATEGORIES.default = 'glyphicon-glass'

Create partials

_flag.html.erb

<span class="glyphicon <%= class_name %>", id="challenge-flag"></span>

_link.html.erb

<%= link_to categorization_path(categorization: category) do %>    
  <%= render 'flag', class_name: class_name %>
<% end %>

And use them

<% category = challenge.categorization %>
<% class_name = CATEGORIES[category.to_sym] %>

<%= render 'link', class_name: class_name, category: category %>