Search code examples
rubyruby-on-rails-3erb

Transforming text to bold in ruby


I have both controller and view for a simple game I've created.

This is my function :

def score
    @letters = params[:letters]
    @word = params[:word].upcase
    if !compsrison?(@word.split(''), @letters.split)
      @result = "Sorry, but #{@word} can't be build out of #{@letters}"
    elsif !check_api?(@word)
      @result = "Sorry, but #{@word} doesn't seem to be valid English word..."
    else
      @result = "Congratulations! #{@word} is a valid English word!"
    end
  end

and simply my view for a result :

 <div class="result">
    <%= @result %>
  </div>

I would like my params[:word] and params[:letters] to be a bold text looking sth like that:1

I can't seem to find the build-in method in ruby for a bold text or change it in my erb file.


Solution

  • What you wrote in your controller with **#{@word}** is called markdown which is indeed not supported by Ruby on Rails out of the box. You would need to use a Markdown renderer like Redcarpet (https://github.com/vmg/redcarpet) and do something like this in your view.

    markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true, tables: true)
    
    markdown.render(@result)
    

    However, Markdown is a lightweight markup language which is often used in online forums (e.g. Stackoverflow) to make it easier to write formatted text or if users usually even don't know HTML.

    In your example, you could also just use HTML. To make a text bold you can use the <b> tag.

    @result = "Congratulations! <b>#{@word}</b> is a valid English word!".html_safe
    

    Please also note the html_safe at the end of the string otherwise Rails would escape this string in your view. It's not ideal to use html_safe and I would argue that your code in the controller belongs to the view (and then you don't need the html_safe anymore.

    https://apidock.com/rails/String/html_safe https://github.com/vmg/redcarpet