So, I've read it all:
But I can't make it work. Here's my situation:
I have a calc_distance(place1, place2) method and an attribute places to my User model and I want to define a method calc_total_distance in the User model.
I want to access the calc_distance method through a Utils lib and not to load the whole utils when using it.
In /lib/utils.rb
module Utils
def calc_distance a, b
# Blah blah blah
end
end
In /config/application.rb I have:
config.autoload_paths += %W(#{config.root}/lib)
In the console, I can do
include Utils then calc_distance(place1, place2) and it works. But Utils::calc_distance(place1 place2) doesn't work ...
Extra-question is can I do this ?
Then in my User.rb model:
def get_total_distance
# Blah blah blah
dist += calc_distance(place1, place2)
# Blah blah blah
end
returns me undefined method 'include' for #<User:0x00000006368278>
and
def get_total_distance
# Blah blah blah
dist += Utils::calc_distance(place1, place2)
# Blah blah blah
end
returns me undefined method 'calc_distance' for Utils:Module
How can I achieve this, knowing that I really prefer the second method (which as I reckon, doesn't load the whole Utils module ...
If you don't wan't to do mixin, but just to define some Utils' methods, then you can define the methods on module level (using self. prefix):
module Utils
def self.calc_distance a, b
# Blah blah blah
end
end
and then call them this way:
Utils.calc_distance(place1, place2)
instead of
Utils::calc_distance(place1, place2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With