Search code examples
ruby-on-railsrubymiddleman

middleman blockquote ruby function


I am trying to create a method in ruby to handle block quotes from my slim blog posts. Right now, I have the following view helper:

  def blockquote(content,author,source=nil,source_link=nil)
    data = '
      <blockquote>
      <p>'+content.html_safe+'</p>
      <footer>
        <strong>'+author+'</strong>'

    if source && source_link
      data = data + '
        <cite>
          <a href="'+source_link+'">'+source+'</a>
        </cite>
      '
    end

    data = data + '</footer></blockquote>'
    return data
  end

Which works for posts like..

= blockquote("When you grow up you tend to get told that the world is the way it is and you're life is just to live your life inside the world. Try not to bash into the walls too much. Try to have a nice family life, have fun, save a little money. That's a very limited life. Life can be much broader once you discover one simple fact: Everything around you that you call life was made up by people that were no smarter than you. And you can change it, you can influence it… Once you learn that, you'll never be the same again.","Steve Jobs, Apple Computers")

however, would there be a better way? I want to wrap the text in something like

- blockquote
  When you grow up you tend to get told that the world is the way it is and you're life is just to live your life inside the world. Try not to bash into the walls too much. Try to have a nice family life, have fun, save a little money. That's a very limited life. Life can be much broader once you discover one simple fact: Everything around you that you call life was made up by people that were no smarter than you. And you can change it, you can influence it… Once you learn that, you'll never be the same again.

but I need a way to pass in the author, and option source + source link.

The current method also requires the quote to be on a single line, instead of multiple lines. Thoughts?


Solution

  • I would create a quote_template partial instead of coding html into a method like you did. Then just do something like this:

      def blockquote(options={})
        ... #checks and business logic
        render partial: 'quote_template', options
      end
    

    And you can initialize it like:

      blockquote({
        author: "Steve Jobs",
        quote: "Some awesome quote...",
      ...
      })
    

    _quote_template.html.erb partial might look something like this:

    <blockquote>
      <p><%= options[:quote] %></p>
    
      <footer>
        <strong><%= options[:author] %></strong>
    
        <% if options[:source] %>
          <cite>
            <a href="<%= options[:source_link] %>"><%= options[:source] %></a>
          </cite>
        <% end %>
      </footer>
    </blockquote>