Extending rails via /lib - problems

I wanted to group some functions which I use in some models in one
place. Controllers have application.rb and views have helpers but I
couldn’t find anything about models. Using the /lib directory seemed to
be the only way.

Alright… so I have something like this:

/lib/code.rb
class ActiveRecord::Base
def method_a(n)

end

def method_b(n)

end
end

/models/some_model.rb
class SomeModel < ActiveRecord::Base
def self.some_method(a, b)

end

def other_method

end
end

I also added require 'code' to enviroment.rb

My problem is that, for some reason, I can’t use any method declared in
code.rb inside self.some_method. However, the methods work perfectly
well inside other_method. I have to include all the code for those
methods inside self.some_method to be able to get things done which
goes against the reason I wanted to separate that code in the first
place.

Is there any other way to make some methods available to all models?

Many thanks.

Hi,

comments inline below:

On 15-Feb-06, at 11:31 AM, Alexandru T. wrote:

def method_a(n)

end

def method_b(n)

end
end

You have just declared two instance methods called method_a() and
method_b()

You have declared a class method called some_method() and an instance
method called other_method()

I also added require 'code' to enviroment.rb

My problem is that, for some reason, I can’t use any method
declared in
code.rb inside self.some_method. However, the methods work perfectly
well inside other_method. I have to include all the code for those
methods inside self.some_method to be able to get things done which
goes against the reason I wanted to separate that code in the first
place.

This is because method_a and method_b both operate on instances.

Is there any other way to make some methods available to all models?

Your methods are available to all models, you’re just confusing class
and instance methods.

Class Foo
def self.wibble
puts “class wibble”
end

def wibble
puts “instance wibble”
end
end

Foo.wibble => “class wibble”
foo_instance = Foo.new
foo_instance.wibble => “instance wibble”

The two methods are called “wibble” but one operates on the class Foo
and the other operates on instances of Foo.

I hope this clears it up for you.

Regards,
Trevor


Trevor S.
http://somethinglearned.com

Many thanks. Indeed, everything is clear now.

Kind regards,
Alex

The two methods are called “wibble” but one operates on the class Foo
and the other operates on instances of Foo.

I hope this clears it up for you.

Regards,
Trevor


Trevor S.
http://somethinglearned.com