Search code examples
ruby-on-railsrubyif-statementhamlstring-interpolation

Correct format for writing conditionals in ruby and then converting output into string using string interpolation inside HAML tag


I am fixing a bug in a ruby on rails open source project at the front end of the project. I am a newbie to ruby on rails, HAML etc. The following line of code is giving me a lot of trouble.

I am wondering what would be correct way to format this. Further, is there a way to write a helper function to turn the conditionals into a function call? Any help will be appreciated.

I have tried several formats but the devs want me to break up the if-else into several lines. I am unable to make that work.

6:       %strong =
7:       "#{
8:         - if @enterprise.is_primary_producer
9:           = t('.producer_profile')
10:         - else
11:           = t('.profile')

I expect the view to be rendered but instead I get syntax errors.


Solution

  • Something like this?

    %strong
      - if @enterprise.is_primary_producer
        = t('.producer_profile')
      - else
        = t('.profile')
    

    Personally, I would do something like:

    - t_key = @enterprise.is_primary_producer ? '.producer_profile' : '.profile'
    %strong= t(t_key)
    

    If you want to move this to a helper, just define it somewhere like in application_helper.rb

    def some_name_for_the_method(enterprise)
      t_key = enterprise.is_primary_producer ? '.producer_profile' : '.profile'
      I18n.t(t_key)
    end
    

    and on the view

    %strong= some_name_for_the_method(@enterprise)