Ruby on Rails: String manipulation

Es gibt einige Sachen, die ich gerne mit Strings machen möchte. Aber natürlich ist nicht ALLES in Rails schon drin. Also habe ich mir mit einem Plugin wie folgt geholfen.

z. B.: “2″.numstring? gibt mir an, ob der string nur Ziffern enthält.

/vendor/plugins/future/init.rb

require 'string_manipulation'

/vendor/plugins/future/lib/string_manipulation.rb

require 'digest/sha1'
module StringManipulation
 
  # Remove ALL unneccessary whitespaces from string
  #    "   hello   world   " #=> "hello world"
  def strip_all
    self.gsub(/ +/, ' ').strip.chomp
  end
 
  # Remove everything that is not a-z or 0-9 or space
  def strip_illegal
    self.gsub(/[^a-zA-Z0-9 ]/, '')
  end
 
  # Returns the basename of a file
  def strip_extention
    self.gsub(/(\.(.*))$/,'')
  end
 
  # Strips RAILS_ROOT/public from string
  def url_from_path
    self.gsub("#{RAILS_ROOT}/public", '')
  end
 
  # Strips RAILS_ROOT from string
  def root_from_path
    self.gsub("#{RAILS_ROOT}", '')
  end
 
  # Hashes a string with SHA1
  def hashed
    Digest::SHA1.hexdigest(self)
  end
 
  # Make a nice downcase keyword list as string, seperated by single spaces
  #    keyword_list("   My §$% KEY   wordlist   ") #=> "my key wordlist"
  def keywordlist
    self.strip_illegal.downcase.strip_all
  end
 
  # Checks if a string contains only numerical characters
  def numstring?
    self =~ /^\d+(\.\d+|\d*)$/
  end
 
end
 
class String
  include StringManipulation
end

Als Unterfunktion von Object sind die Funktionen überall verfügbar. Sehr praktisch.

Ähnliche Posts:
» Mysql on Leopard: Startupitem, Prefpane, LaunchDemon
» MCV Ruby on Rails – was gehört wohin?
» Passenger für Ruby on Rails aus TextMate “automatisch” neu starten
» Railscasts.com – die beste Ruby on Rails Resource

0 Response to “Ruby on Rails: String manipulation”


  • No Comments

Leave a Reply