addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwchatcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobegmailgoogleimageimagesinstagramlinklocation-pinmagnifying-glassmailminusmoremuplabelShape 3 + Rectangle 1outlookpersonplusprice-ribbonImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruseryahoo

Re: [ruby-81] code scope trouble

From: Wayne V.
Sent on: Monday, August 11, 2008 3:46 PM
Hi Loqi,
In a case like this, I'd probably put this method in a module named Util:
module Util
  def Util.random_text ...
and put the above code in a file named util.rb in lib.
Then when the other code calls it as Util.random_text or Util::random_text, Rails will automatically find it, no require required.
Wayne Vucenic
No Bugs Software
Agile Ruby/C#/Vista Contract Programming in Silicon Valley.

On Mon, Aug 11, 2008 at 2:29 PM, Loqi <[address removed]> wrote:
Hey Rubies,

I'm having code scope problems. I can't seem to find an ideal place for utility functions that I'd like to be available for any of my rails code that needs them. I want to use this object-independent function in my controllers and tests, and maybe some other places I haven't thought of yet:

 # Generate a string of chars chosen at random from a palette, to a specified length.
 def random_text(len, palet='[masked]ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
   text = ''
   len.times { |i| text << palet[rand(palet.length)] }

So where's the best place for my controllers and tests to see it?

My first thought is I should put it in a file called utils.rb, and put...
require 'utils.rb' the top of any file that needs it. Should this file go somewhere in /vendor or /app or somewhere else? Or should I instead attach it to ApplicationController as a class method and call it like this...
? And if so, would some rails code files be unable to see it?

Or is there a better way to accomplish this seemingly simple goal? (Maybe it is I who is seemingly simple.)


Please Note: If you hit "REPLY", your message will be sent to everyone on this mailing list ([address removed])
This message was sent by Loqi ([address removed]) from The East Bay Ruby Meetup Group.
To learn more about Loqi, visit his/her member profile:
To unsubscribe or to update your mailing list settings, click here:
Meetup Support: [address removed]
632 Broadway, New York, NY 10012 USA

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