我在哪里把这个矩阵类放在我的 rails 应用程序中 [英] Where do I put this matrix class in my rails app
问题描述
我希望使用此处显示的矩阵类:
I am looking to use the matrix class shown here:
http://rosettacode.org/wiki/Cholesky_decomposition#Ruby
在我的 Rails 应用中.我已将该类复制到 lib/matrix.rb
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 %>
但是我收到错误消息:
undefined method `cholesky_factor' for Matrix[[25, 15, -5], [15, 18, 0], [-5, 0, 11]]:Matrix
我做错了什么吗?(我在 lib/matrix.rb 中也有 require 'matrix' 行)
Is there something I am doing wrong? (I have the require 'matrix' line in lib/matrix.rb too)
推荐答案
从 lib/matrix.rb
中移除 require 'matrix'
.
重命名为lib/extend_matrix.rb
,以便我们可以专门加载它.
Rename to lib/extend_matrix.rb
so we can specifically load it 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
# ...
注意#{::Rails.root.to_s}
..to_s
的使用至关重要,因为 ::Rails.root
返回一个 Pathname
对象.如果没有它,您将在自动加载路径中添加 /lib
(系统级别).我们想要 /path/to/rails/lib
(应用程序级别).
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).
记得重启服务器.
这就是我让它为我工作的方式.如果有人知道如何在没有静态要求的情况下做到这一点,请分享.我相信这可以动态完成.
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.
这篇关于我在哪里把这个矩阵类放在我的 rails 应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!