Skip to content

nl2br, strtr php functions in ruby

November 30, 2011

For those who are php code know very well how important is strtr and nl2br in the web development.

When developing web application in rails I still need these 2 functions. so I dicide just to keep and implement the same name in ruby:
string.rb

class String
  def str_translate values, preserve = false
     self.gsub /{[^}]*}/ do |match|
           key = match[1..-2]
            if preserve
              values[key.to_sym] || match
           else
              values[key.to_sym] || ""
           end
     end
  end

 def nl2br
    self.gsub /n/ do |match|
          <br />
    end
  end
end

string_spec.rb

require "spec_helper"

describe String do
  describe "#str_translate" do
      it "should be translated keys in the string by parameters in the list " do
        str = "The message from {user} sent out on {day} "
        strtr = str.str_translate(:user => "Ilab", :day => "Monday")
        strtr.should eq "The message from Ilab sent out on Monday "
      end

      it "should preserve keys that not in the string by parameters in the list " do
        str = "The message from {user} sent out on {day} "
        strtr = str.str_translate({:day => "Monday"}, true)
        strtr.should eq "The message from {user} sent out on Monday "
      end

      it "should remove the missing key from the string" do
        str = "The message from {user} sent out on {day} "
        strtr = str.str_translate(:day => "Monday")
        strtr.should eq "The message from  sent out on Monday "
      end
  end

  describe "nl2br -new line to br" do
    it "should convert all new line to br" do
      original = ["nthis is a great newnIn the n", "blahnnnblahn"]
      converted = ["<br />this is a great new<br />In the <br />", "blah<br /><br /><br />blah"]
      original.each_with_index do |str, index|
        str.nl2br.should eq converted[index]
      end
    end
  end
end
Advertisements

From → Php, Ruby

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: