0

Avi Tzurel wrote this helper for a better simple_format:

  def simple_format_no_tags(text, html_options = {}, options = {})
    text = '' if text.nil?
    text = smart_truncate(text, options[:truncate]) if options[:truncate].present?
    text = sanitize(text) unless options[:sanitize] == false
    text = text.to_str
    text.gsub!(/\r\n?/, "\n")                    # \r\n and \r -> \n
    text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline   -> br
    text.html_safe
  end

In my view I have this:

<%= simple_format_no_tags(article.text) %>

I'm new to programming and rails - what is the syntax for passing the option to truncate 144 characters?

1 Answer 1

1
simple_format_no_tags(article.text,{},{:truncate => 144})

simple_format_no_tags method looks at options parameter for truncate key. Since options is the third parameter, you will have to pass empty hash or nil for the second if you don't have any html options to pass in.

Found this implementation here. See if this will work for you

def smart_truncate(text, char_limit)
  size = 0
  text.split.reject do |token|
    size += (token.size + 1)
    size > char_limit
  end.join(" ") + (text.size >= char_limit ? " ..." : "" )
end
Sign up to request clarification or add additional context in comments.

3 Comments

I tried that but getting undefined method `smart_truncate'
I assumed that you also copied smart_truncate from wherever you copied simple_format_no_tags
great. that works! I can't seem to find how to add "read more" and have it inline with the end of the truncate. If I open a new erb tag with link_to read more it goes to the next line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.