Read more

Strip carriage returns in submitted textareas

Henning Koch
September 09, 2010Software engineer at makandra GmbH

When submitting textareas, browsers sometimes include carriage returns (\r) instead of just line feeds (\n) at the end of each line. I don't know when this happens, and most of the time it doesn't matter.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

In cases where it does matter, use the attached trait Show archive.org snapshot to remove carriage returns from one or more attributes like this:

class Note
  does 'strip_carriage_returns', :prose, :code
end

Here is the test that goes with it:

describe Note do

  describe 'before_validation' do
    it_should_run_callbacks(:strip_carriage_returns)
  end

  describe '#strip_carriage_returns' do

    it 'should strip carriage returns from any pasted code and prose' do
      article = Note.new(:prose => "foo\n\rbar", :code => "baz\n\rbam")
      article.should_receive(:prose=).with("foo\nbar")
      article.should_receive(:code=).with("baz\nbam")
      article.send(:strip_carriage_returns)
    end

  end

end
Posted by Henning Koch to makandra dev (2010-09-09 19:03)