Using Utility Classes

Hi All,
I am trying to create and use our own utility classes that can have
class methods and be used in many controllers. There is an inconsistent
behaviour. I am not sure if I am missing anything. Here are the code
snippets.
In controller

def test
render :text => Utility.datetest
end

utility classes are part of the model folder structure where I added
couple of ruby files and created classes in them.

class ScheduleUtility

def ScheduleUtility.datetest
“Time now is #{Time.now}”
end
def ScheduleUtility.test
“Time now is #{Time.now}”
end
end

class Utility
def Utility.datetest
“yesterdays date:#{Time.now-1.day}”
end
def Utility.test
“yesterdays date:#{Time.now-1.day}”
end
end

When I use the Utility class’s method it works perfectly fine but with
the ScheduleUtility it gives a no method error
undefined method `datetest’ for ScheduleUtility:Class

And a further anomaly is that if I define a method by the name “test”
it doesn’t work in either of the cases .

these are the respective error messages
private method test' called for ScheduleUtility:Class private methodtest’ called for Utility:Class

would be glad if there were any valid reasons for such behaviour
thanks

The models in your models directory have to following a naming
convention so rails know where to reload the classes in development
mode. Your Utility class works fine because it is in
app/models/utility.rb. When it looks for ScheduleUtility class rails
looks in app/models/schedule_utility.rb and finds nothing.

You can sidestep this issue by putting these classes in your lib folder
instead.

As for the test issue, try declaring class methods with self instead of
the class name

def self.datetest

although what you have there should work. Perhaps the test method is
reserved by rails framework somehow? Try any other method name and see
if it works.

You could also force the method public with “public :test” after the
method definition.

That’s pretty interesting. So any class that we create in the model
folder should follow the naming convention in synch with the file that
it is in, even though it is not an active record.
Thanks for the info, I will try it once I get back to work.
Have a great holiday…
Uma