Re: [ruby-81] code scope trouble

From: Loqi
Sent on: Friday, August 22, 2008 11:26 AM
Hey thanks for the tips, Wayne, Alex, and Sam.

I settled on extending the String and Fixnum classes with my utility 
routines. I put the code in Ruby files in the lib directory:

------------------ lib/string.rb
class String    # Extend the String class with some util routines.
...
...
   # (Returns String): Generate string of chars randomly chosen from a palette.
   def self.random_text(len­=RANDOM_TEXT_DEFLEN,­ palet=RANDOM_TEXT_DE­FPAL)
     return palet * len if palet.length < 2
     text = ''
     len.times { |i| text << palet[rand(palet.len­gth)] }
     text
   end

   # (Returns String): Remove leading and trailing whitespace and 
replace all whitespace
   # runs (one or more consecutive TAB, CR, LF, or ' ') with a single ' '.
   def trim_whitespace
     self.tr_s(" \r\n\t", '    ').strip
   end

   # (Returns String): Perform trim_whitespace "in place" on self.
   def trim_whitespace!
     self[0..-1] = self.trim_whitespace­
   end
...
...
end
--------------------­-

Then I require those Ruby scripts in the Application Helper, like so:

------------------ app/helpers/applicat­ion_helper.rb
module ApplicationHelper
   require 'string'
   require 'fixnum'
...
...
--------------------­--

I think the /lib directory is the proper place for such extensions on 
the Ruby base classes, and the Application Helper is my first guess 
at where those items should be included. I'm not sure though.

Please correct me if this deviates from convention.

Loqi


P.S. My 'trim_whitespace!'  method uses "self[0..-1] = ..." to 
accomplish an in-place modification of a String object. This works, 
but feels slightly kludgy to me. What's the canonical way to write a 
'!' method?

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy