Question: Displaying Status In View - Rails

Question

Displaying Status In View - Rails

Answers 2
Added at 2017-01-04 14:01
Tags
Question

In my rails application I have a model called JobPosting. A job posting has a status, it can be either:

  1. Waiting Approval
  2. Draft
  3. Open
  4. Interviews Scheduled
  5. Closed

I implemented these statuses using ActiveRecord::Enum like so:

class JobPosting < ApplicationRecord
   enum status: [:waiting_approval, :draft, :open, :interviews_scheduled, :closed]
end

Now I would like to display a different user interface element that is dependant on the status of the job posting. i.e.

For the waiting approval status I want:

<div class="label label-warning">pending approval</div>

And for the open status I want:

<div class="label label-success">open</div>

Note that there is different text and the class is different as the element is styled differently for the different cases. In my index.html.erb, where this styling needs to happen, I could just do a bunch of embedded ruby if statements and check the status of the posting and display the desired element, like so:

<% if posting.waiting_approval? %>
      <div class="label label-warning">pending approval</div>
<% elsif posting.open? %>
      <div class="label label-success">open</div>
<% elsif posting.closed> %>
      etc...
 <% end %>

I feel as if that is not very DRY, is there a better way?

Alternatively, I could create partial and have the logic stored in that and just render the partial, but again is that how it is done?

Answers
nr: #1 dodano: 2017-01-04 15:01

Unless you have decorators, I would've just created a simple helper

def status_label(posting)
  case posting.status
  when :waiting_approval
    content_tag(:div, 'pending approval', class: 'label label-warning')
  when :draft
    ...
end
nr: #2 dodano: 2017-01-04 15:01

I would do something like this:

class JobPosting < ApplicationRecord
   enum status: [:waiting_approval, :draft, :open, :interviews_scheduled, :closed]

   def status_label
     {
       'waiting_approval' => 'pending approval',
       'open' => 'open',
       'interviews_scheduled' => 'interview is scheduled',
       'closed' => 'closed',
       'draft' => 'draft'
     }[self.status]
   end
end

then in view:

<div class="label <%= posting.status %>"><%= posting.status_label %></div>

Since in Rails we've sass you can inherit properties of other css classes:

.waiting_approval{
  @extend .label-warning;
  // customize this css class if needed.
}

// and so on..
Source Show
◀ Wstecz