Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make this code more Ruby-way?
    primarykey
    data
    text
    <p>I am new to Ruby and Rails (switched from Python and Python frameworks). I'm writing a simple dashboard website which displays information about the S.M.A.R.T. state of hard disks. Here I wrote a helper to display a badge in a table cell near the relevant S.M.A.R.T attribute if it's value meets a condition. At first, the helper code was as simple as in <strong>Listing 1</strong>, but then I decided to draw a summary of all badges for the specific drive, in addition to the badges near individual S.M.A.R.T. attributes in the table. So at first I added a simple method like: </p> <pre><code>def smart_chk_device(attrs) attrs.each { |item| smart_chk_attr(item) } end </code></pre> <p>But this approach <strong>didn't work</strong> and it caused the entire array of attributes to be output to the resulting page. It only started to work when I made it as in <strong>Listing 2</strong>, but I believe there's something wrong there, and the same thing can be done in a more simple way. Please show me the right, Ruby-way of doing it.</p> <p><strong>Listing 1:</strong> </p> <pre><code>module HomeHelper def smart_chk_attr(attr) case attr[:id].to_i when 1,197 content_tag(:span, "Warning", :class =&gt; "label label-warning") if attr[:raw].to_i &gt; 0 when 5,7,10,196,198 content_tag(:span, "Critical", :class =&gt; "label label-important") if attr[:raw].to_i &gt; 0 end end end </code></pre> <p><strong>Listing 2 (works, but I don't like it):</strong> </p> <pre><code>module HomeHelper def smart_chk_attr(attr) case attr[:id].to_i when 1,197 return content_tag(:span, "Warning", :class =&gt; "label label-warning") if attr[:raw].to_i &gt; 0 when 5,7,10,196,198 return content_tag(:span, "Critical", :class =&gt; "label label-important") if attr[:raw].to_i &gt; 0 else return String.new end return String.new end def smart_chk_device(attrs) output = "" attrs.each { |item| output &lt;&lt; smart_chk_attr(item) } return output.html_safe end end </code></pre> <p><strong>attrs</strong> is an Array of Hashes, where each Hash contains keys <strong>:id</strong> and <strong>:raw</strong> with the numeric code of a S.M.A.R.T attribute and its RAW value, both in Strings.</p> <p>Also, RoR complaints if to remove the last "return String.new" in Listing 2. Why is it so? Doesn't the "case" block all the possible cases, so that control should never reach the end of the function?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload