From 634c9517d85f1c5b221175cdfe7d2fa17e765acd Mon Sep 17 00:00:00 2001 From: Akhil Bansal Date: Sun, 31 May 2009 12:11:04 +0530 Subject: [PATCH] Added to_url method to String core ext --- .../active_support/core_ext/string/conversions.rb | 12 +++++++++--- activesupport/test/core_ext/string_ext_test.rb | 5 +++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb index 2b9f8c7..f65b085 100644 --- a/activesupport/lib/active_support/core_ext/string/conversions.rb +++ b/activesupport/lib/active_support/core_ext/string/conversions.rb @@ -6,17 +6,23 @@ class String def ord self[0] end unless method_defined?(:ord) - + # Form can be either :utc (default) or :local. def to_time(form = :utc) ::Time.send("#{form}_time", *::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec).map { |arg| arg || 0 }) end - + def to_date ::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday)) end - + def to_datetime ::DateTime.civil(*::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec).map { |arg| arg || 0 }) end + + # Convert string to url. e.g: "webonrails.com".to_url => "http://webonrails.com" + def to_url + without_http = self.gsub(/^http:\/\// , '') + return "http://#{without_http}" + end end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 237a843..d584bdd 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -122,6 +122,11 @@ class StringInflectionsTest < Test::Unit::TestCase assert_equal ::Date::ITALY, "2039-02-27 23:50".to_datetime.start # use Ruby's default start value end + def test_string_to_url + assert_equal("http://webonrails.com", "webonrails.com".to_url) + assert_equal("http://webonrails.com", "http://webonrails.com".to_url) + end + def test_string_to_date assert_equal Date.new(2005, 2, 27), "2005-02-27".to_date end -- 1.6.2.1