1

I am looking to use the matrix class shown here:

http://rosettacode.org/wiki/Cholesky_decomposition#Ruby

in my rails app. I have copied the class into lib/matrix.rb

In my view page I have tried to test this class by using the code:

<%= Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor %>

However I get the error message:

undefined method `cholesky_factor' for Matrix[[25, 15, -5], [15, 18, 0], [-5, 0, 11]]:Matrix

Is there something I am doing wrong? (I have the require 'matrix' line in lib/matrix.rb too)

Zakoff
  • 12,665
  • 5
  • 22
  • 35

2 Answers2

2

Remove require 'matrix' from lib/matrix.rb.

Rename to lib/extend_matrix.rb so we can specifically load it in.

In config/application.rb:

require File.expand_path('../boot', __FILE__)
require 'rails/all'

require 'matrix' # <-- moved here

#...bundler stuff...

module MyApp # <-- don't overwrite this!
  class Application < Rails::Application
     # ...
    config.autoload_paths << "#{::Rails.root.to_s}/lib" # <-- set path
    require "extend_matrix" # <-- forcibly load your matrix extension
  # ...

Notice #{::Rails.root.to_s}. Use of .to_s is critical because ::Rails.root returns a Pathname object. Without it, you will be adding /lib (system level) to the autoload path. We want /path/to/rails/lib (application level).

Remember to restart the server.


This is how I got it to work for me. If anybody knows how to do this without static requires, do share. I'm sure this can be done dynamically.

Substantial
  • 6,684
  • 2
  • 31
  • 40
  • Thanks for the suggestions, it works when I try with a simple function but not with the Matrix class. I think there must be something wrong with the way I am extending the inbuilt Matrix class – Zakoff Jan 30 '12 at 20:29
0

I think the problem is that the lib/matrix.rb in never read. If you're using Rails 3, the files in the dir directory are not autoloaded. As suggested in this answer, add the following line in your application.rb and restart your server:

config.autoload_paths += Dir["#{config.root}/lib/**/"] # include all subdirectories
Community
  • 1
  • 1
Baldrick
  • 23,882
  • 6
  • 74
  • 79