diff options
author | David Heinemeier Hansson <david@loudthinking.com> | 2008-09-10 00:26:50 -0500 |
---|---|---|
committer | David Heinemeier Hansson <david@loudthinking.com> | 2008-09-10 00:26:50 -0500 |
commit | b8e8be83e952163e225f9b38bd7251cba9c44f38 (patch) | |
tree | 42887c2ce47fd11cf634406e1a109f35f020bdf8 /activesupport/lib/active_support | |
parent | b141624abbd1be6aa9836708fe4c20c03af5ab3b (diff) | |
download | rails-b8e8be83e952163e225f9b38bd7251cba9c44f38.tar.gz rails-b8e8be83e952163e225f9b38bd7251cba9c44f38.tar.bz2 rails-b8e8be83e952163e225f9b38bd7251cba9c44f38.zip |
Added Inflector#parameterize for easy slug generation ("Donald E. Knuth".parameterize => "donald-e-knuth") #713 [Matt Darby]
Diffstat (limited to 'activesupport/lib/active_support')
-rw-r--r-- | activesupport/lib/active_support/core_ext/string/inflections.rb | 19 | ||||
-rw-r--r-- | activesupport/lib/active_support/inflector.rb | 19 |
2 files changed, 38 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb index 3bbad7dad8..de99fe5791 100644 --- a/activesupport/lib/active_support/core_ext/string/inflections.rb +++ b/activesupport/lib/active_support/core_ext/string/inflections.rb @@ -87,6 +87,25 @@ module ActiveSupport #:nodoc: Inflector.demodulize(self) end + # Replaces special characters in a string so that it may be used as part of a 'pretty' URL. + # + # ==== Examples + # + # class Person + # def to_param + # "#{id}-#{name.parameterize}" + # end + # end + # + # @person = Person.find(1) + # # => #<Person id: 1, name: "Donald E. Knuth"> + # + # <%= link_to(@person.name, person_path %> + # # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a> + def parameterize + Inflector.parameterize(self) + end + # Creates the name of a table like Rails does for models to table names. This method # uses the +pluralize+ method on the last word in the string. # diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index 7ae9e0c6ab..e5f0063285 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -240,6 +240,25 @@ module ActiveSupport def demodulize(class_name_in_module) class_name_in_module.to_s.gsub(/^.*::/, '') end + + # Replaces special characters in a string so that it may be used as part of a 'pretty' URL. + # + # ==== Examples + # + # class Person + # def to_param + # "#{id}-#{name.parameterize}" + # end + # end + # + # @person = Person.find(1) + # # => #<Person id: 1, name: "Donald E. Knuth"> + # + # <%= link_to(@person.name, person_path %> + # # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a> + def parameterize(string, sep = '-') + string.gsub(/[^a-z0-9]+/i, sep).downcase + end # Create the name of a table like Rails does for models to table names. This method # uses the +pluralize+ method on the last word in the string. |