Two extended classes - one works and the other doe

2019-08-12 07:20发布

问题:

I have had some difficulties in using extended classes in rails, in particular extending the Matrix class - and I have also asked some questions related to this:

Am I extending this inbuilt ruby class correctly

Using custom functions in rails app

Where do I put this matrix class in my rails app

In general the answers have been around autoloading in rails 3. However, when I extend 'Math' new functions work, when I extend 'Matrix' new functions don't work - even if I treat them in the same way

I've tried many iterations and change module names, requires, autoloads but here are my latest key files:

application.rb:

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

require 'rails/all'
require 'matrix'

# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)

module SimpleFixed
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Custom directories with classes and modules you want to be autoloadable.
    # **I have tried all these autoload variants**
    #  config.autoload_paths += %W(#{config.root}/extras)
    #  config.autoload_paths += %W(#{config.root}/lib)
    #  config.autoload_paths += Dir["#{config.root}/lib/**/"]
    #  config.autoload_paths << "#{Rails.root}/lib"
      config.autoload_paths << "#{::Rails.root.to_s}/lib" # <-- set path
      require "extend_matrix" # <-- forcibly load your matrix extension

*other standard code here*

lib/extend_math.rb

module Math
  class << self

    def cube_it(num)
      num**3
    end

    def add_five(num)
      num+5
    end

  end
end

lib/extend_matrix.rb

module Extend_matrix **An error is raised if I call this Matrix**

  class Matrix

    def symmetric?
      return false if not square?
      (0 ... row_size).each do |i|
        (0 .. i).each do |j|
          return false if self[i,j] != self[j,i]
        end
      end
      true
    end

    def cholesky_factor
      raise ArgumentError, "must provide symmetric matrix" unless symmetric?
      l = Array.new(row_size) {Array.new(row_size, 0)}
      (0 ... row_size).each do |k|
        (0 ... row_size).each do |i|
          if i == k
            sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
            val = Math.sqrt(self[k,k] - sum)
            l[k][k] = val
          elsif i > k
            sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
            val = (self[k,i] - sum) / l[k][k]
            l[i][k] = val
          end
        end
      end
      Matrix[*l]
    end

  end

end

my view page:

<%= Math.add_five(6) %> **works*

<%= Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor %> **doesn't work**

Could it be because Math is a Module in ruby but Matrix is a class? If so, how do I correct for this?

回答1:

If you have a look at the implementation of Matrix, you will see the reason. For me, it is located in .../ruby192/lib/ruby/1.9.1/matrix.rb. The definition is (omitted all methods):

class Matrix
  include Enumerable
  include ExceptionForMatrix
  ...
end

That means that Matrix is not contained in a module. Your source for your additions should begin:

class Matrix

  def symmetric?
    ...
  end
  def cholesky_factor
    ...
  end
end

So your addition to a class or module has to match the current definition. Matrix is known as Matrix in the Ruby constants, and not as Extend_matrix::Matrix which is what you have defined.