Function to be used in model

Where is the best place to put a function that will be used in both
several controller and several models?

ryan wrote:

Where is the best place to put a function that will be used in both
several controller and several models?
You could stick it in a utility class in lib/:

  • lib/my_utility.rb
    class MyUtility
    def self.my_function(bar)

    code

    end
    end

then use it:

foo = MyUtility::my_function(bar)

That could get kinda messy though.

It really depends on what you’re actually trying to do. You may be able
to write something extends an existing class. For example, if you have
a string format that you use throughout your site, you can add a method
into the String class:

  • lib/string.rb
    class String
    def to_foo
    "foo "+self
    end
    end

which results in:

mystring = “bar”
mystring.to_foo -> “foo bar”

Hope that provides some thought food :0)

Steve

What I am trying to do is to write a quota system. The limits are
stored in the DB and I want to use a function to get the object that
contains the limits (to honor the DRY principle). Obviously both models
and views will need to access the quota limits.

Eventually it would be nice to have a Quota plugin, but right now I’m
still trying to understand some of the finer points of where to put
objects that need various degrees of coupling to the rest of the system.

But thanks for the help, it seems that putting a utility class in the
lib directory should work for now.

Stephen B. wrote:

ryan wrote:

Where is the best place to put a function that will be used in both
several controller and several models?
You could stick it in a utility class in lib/:

  • lib/my_utility.rb
    class MyUtility
    def self.my_function(bar)

    code

    end
    end

then use it:

foo = MyUtility::my_function(bar)

That could get kinda messy though.

It really depends on what you’re actually trying to do. You may be able
to write something extends an existing class. For example, if you have
a string format that you use throughout your site, you can add a method
into the String class:

  • lib/string.rb
    class String
    def to_foo
    "foo "+self
    end
    end

which results in:

mystring = “bar”
mystring.to_foo -> “foo bar”

Hope that provides some thought food :0)

Steve

Something like this is perfect for a Module.

Read up on modules and mixins and you will find what you need.

http://www.rubycentral.com/book/tut_modules.html