Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display yes/no with content_tag helper by boolean

I am trying to display a badge pill that says ‘Yes’ or ‘No’ based on it’s boolean value, using a content_tag rails helper.

I currently have my helper method written out as

      def boolean_for(bool = false)
       style = [true, 'true', 1, '1'].include?(bool) ? ['success', t('Yes')] : ['danger', t('No')]
       content_tag(:span, 'Selectable', class: "badge badge-pill badge-%s"% style).html_safe
      end 

which displays this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select tags

My goal is to change the "Selectable" to yes or no, but so far every attempt I have made has been unsuccessful. I’d assume I have to change the second argument, but am unsure to what.
I attempted this which did display yes or no, but would cause me to lose the badge pill styling.

  def boolean_for(bool = false)
   rv=false
   rv=true if bool
   return rv ? t('Yes') : t('No')
   style = [true, 'true', 1, '1'].include?(bool) ? ['success', t('Yes')] : ['danger', t('No')]
   content_tag(:span, rv, class: "badge badge-pill badge-%s"% style).html_safe
  end

Any help with this would be super appreciated!

>Solution :

This (or something like it) will do the trick:

def boolean_for(bool = false)
 style     = ['danger', t('No')]
 pill_text = 'No'
 if [true, 'true', 1, '1'].include?(bool)
   style     = ['success', t('Yes')]
   pill_text = 'Yes'
 end
 content_tag(:span, pill_text, class: "badge badge-pill badge-%s"% style).html_safe
end 

Or if you want to use your locale file like you are for the styles:

def boolean_for(bool = false)
 style     = ['danger', t('No')]
 pill_text = t('No')
 if [true, 'true', 1, '1'].include?(bool)
   style     = ['success', t('Yes')]
   pill_text = t('Yes')
 end
 content_tag(:span, pill_text, class: "badge badge-pill badge-%s"% style).html_safe
end 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading