Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Accessing module method in model

So, I've read it all:

  • Best way to load module/class from lib folder in Rails 3?
  • Rails doesn't load my module from lib
  • Rails /lib modules and
  • How to create and use a module using Ruby on Rails 3?

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 ...

like image 950
Augustin Riedinger Avatar asked May 02 '26 19:05

Augustin Riedinger


1 Answers

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)
like image 134
Alexander Avatar answered May 05 '26 08:05

Alexander