Topic: Where do I put routines that can be accessed by models?

I cant figure out where to put a routine that can be accessed by a model, other than the model itself.
The original code came from the new Agile Web Development With Rails book, but Im trying to add some path processing to the upload files.

models/path.rb
class Path < ActiveRecord::Base
  def processfilename(fullfilename)
    ...
  end
end

models/uploadedfile.rb
class UploadedFile
  def uploaded_file=
    ...
    filename, parent = Path.processfilename(file_field.original_filename)
    ...
  end
end


I have tried adding the 'processfilename' method to my Path < ActiveRecord::Base class (which is where I want it to live since many classes will be using it) but each time my UploadedFile class tries to access it, it says 'undefined method for Path:Class.

I have also tried to put it in the controller and the helper, and I always get the same result.

Any help/suggestions would be greatly appreciated.

Last edited by poschs (2007-01-02 10:47:32)

Re: Where do I put routines that can be accessed by models?

Is UplaodedFile a subclass of Path? As in

class UploadedFile < Path
end

?

It needs to be that for starters. Then secondly, you defined processfilename as an instance method, not a class method, but you are trying to call it like a class method. drop the "Path." part of the call and it should work.

class UploadedFile < Path
  def uploaded_file=
    ...
    filename, parent = processfilename(file_field.original_filename)
    ...
  end
end

Re: Where do I put routines that can be accessed by models?

Thanks for the reply tortoise.

Thats fine for this particular class, but I will need to access the processfilename routine from other models. Is there any way to do that?

Re: Where do I put routines that can be accessed by models?

OK, I figured it out. When you mentioned class method vs. instance method, I looked it up and found that I needed to declare the processfilename like this:

class Path < ActiveRecord::Base

  def Path.processfilename(fullfilename)
  ...
  end
end


Meaning, I forgot to prepend Path. in front of the method name to make it a class method vs. instance method.

Thanks again!

Re: Where do I put routines that can be accessed by models?

ah ok, you wanted to go the other way. that works too.