self.commentify

in itchef/cookbooks/fb_helpers/libraries/fb_helpers.rb [56:140]


    def self.commentify(comment, arghash = {})
      defaults = { 'start' => '#', 'finish' => '', 'width' => 80 }
      arghash = defaults.merge(arghash)

      usage = %{
commentify(text, args)

commentify() takes one required string argument, followed by an optional hash.
If the has is specified, it takes one or more of the following keys:
'start', 'finish', 'width'
}

      
      if !comment.is_a?(String) || comment.match(/^\s*$/)
        fail usage
      end

      
      start = arghash['start']
      finish = arghash['finish']
      width = arghash['width']

      
      
      single_line_pad = 1
      
      end_pad = 1

      
      curr_line = ''
      
      final_comment = ''

      
      
      curr_line = start

      
      if finish == ''
        
        curr_line += ' ' * single_line_pad
        prefix = start + ' ' * single_line_pad
      else
        final_comment += "#{curr_line}\n"
        curr_line = ''
        prefix = ''
      end

      
      words = comment.split(/\s+/)
      words.each do |word|
        
        space_avail = width - (curr_line.size + end_pad)
        
        if word.length > space_avail
          
          if curr_line.empty?
            
            
            final_comment += "#{prefix}#{word}\n"
            curr_line = ''
          else
            final_comment += "#{curr_line.strip}\n"
            curr_line = "#{prefix}#{word} "
          end
        else
          
          if curr_line.empty?
            curr_line = prefix
          end
          curr_line += "#{word} "
        end
      end
      
      
      unless curr_line.empty?
        final_comment += curr_line.strip
      end
      
      if finish != ''
        final_comment += "\n#{finish}"
      end
      final_comment
    end