HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Helper that swaps out some text for certain icons

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
iconshelpertextswapsthatsomeforcertainout

Problem

I have a Rails helper that swaps out some text for certain icons.

Example:

Helper Sample

...
            '+1' => '',
            '+2' => '',
            '−1' => '',
            '−2' => '',
            '−10' => '',
            '{T}' => '',
            '{P}' => '',
            '{C}' => ''
            }
card.gsub(/\{.+?\}|\+\d+|\−\d+|\{[T]}|X/){|k| hash[k] || k }.html_safe


There is about 30 lines above that, but I'm about to have to duplicate this +1, +2, -1, -2 one etc to include every number between 1 and 20. This seems -extremely- poor practice and I'm wondering if there is a better way to do it? Below is my entire helper, and I might be able to cross apply it to text too, but it seems very silly to me to have to do it for all numbers, both positive and negative.

(As you can tell ms-loyalty-down is for negative numbers and ms-loyalty-up is for positive.) I was thinking about a 'case' and 'when case +' loyalty-up, but I wasn't getting the number appended to the end, nor was it continuing through the cycle.

Entire Helper

```
module CardsHelper
def card_text_swap card
if card.nil ?
return
else
hash = {
'{hw}' => ' ',
'{W}' => '',
'{R}' => '',
'{U}' => '',
'{G}' => '',
'{B}' => '',
'{S}' => '',
'{X}' => '',
'X' => '',
'{W/U}' => '',
'{W/B}' => '',
'{W/P}' => '',
'{2/W}' => '',
'{U/B}' => '',
'{U/R}' => '',
'{U/P}' => '',
'{2/U}' => '',
'{B/R}' => '',
'{B/G}' => '',
'{B/P}' => '',
'{2/B}' => '',
'{R/G}' => '',
'{R/P}' => '',
'{R/W}' => '',
'{2/R}' => '',
'{G/W}' => '',
'{G/B}' => ''

Solution

You can create the entries programmatically:

repetitive_entries = (1..10).map do |i|
  ["+#{i}", ""]
end.to_h


So then your overall strategy would be:

  • Create the one-off entries in card as you have now



  • Create the repetitive entries that differ only by a number



  • Repeat step 2 as many times as needed, eg, for the "up" and "down" versions.



  • Use array merge to combine the hashes from the previous steps into one large hash.



This allows you to keep your current approach, which I like for its simplicity, and avoid repeating yourself.

Code Snippets

repetitive_entries = (1..10).map do |i|
  ["+#{i}", "<i class=\"ms ms-loyalty-up ms-loyalty-#{i}\"></i>"]
end.to_h

Context

StackExchange Code Review Q#148371, answer score: 3

Revisions (0)

No revisions yet.