2012-04-07 43 views
1

我有幾個小班是在/應用/型號的單個文件,類似於:強制導軌自動加載類

# /app/models/little_class.rb 
class LittleClass; ...do stuff; end; 
class AnotherLittleClass; ...do stuff; end; 

的Rails似乎只面向自動加載的類文件中反映的類名。所以引用AnotherLittleClass以外的文件提出了「未初始化常量」,如下直到LittleClass被引用錯誤:

irb(main):001:0> AnotherLittleClass 
NameError: uninitialized constant AnotherLittleClass 
irb(main):02:0> LittleClass 
=> LittleClass 
irb(main):03:0> AnotherLittleClass 
=> LittleClass2 

這將是一個痛苦和混亂的他們分割成單獨的文件。有沒有辦法自動加載這些類,所以沒有LittleClass引用AnotherLittleClass不會引發錯誤?

回答

1

試試這招:

1.9.2p312 :001 > AnotherLittleClass.new 
# => NameError: uninitialized constant AnotherLittleClass 
1.9.2p312 :002 > autoload :AnotherLittleClass, File.dirname(__FILE__) + "/app/models/little_class.rb" 
# => nil 
1.9.2p312 :003 > AnotherLittleClass.new 
# => #<AnotherLittleClass:0xa687d24> 
+0

嗯,是得到它。我不得不手動指定所有的類。謝謝@WarHog – 2012-04-07 20:34:57

+0

然而,如果你關心這個技巧,Rails會重新加載類。因此,如果您將對這些類進行任何更改,則必須重新啓動該應用程序。 – 2016-04-07 16:28:21

4

你可以把它們放入一個模塊和這個命名空間SomeLittleClasses::LittleClass.do_something

# /app/models/some_little_classes.rb 
module SomeLittleClasses 

    class LittleClass 
    def self.do_something 
     "Hello World!" 
    end 
    end 

    class AnotherLittleClass 
    def self.do_something 
     "Hello World!" 
    end 
    end 

end 
+0

另一個不錯的選擇 – 2012-04-07 20:36:37

1

這是你的選擇,因爲我看到它內部使用它們:

  1. 將你的文件分割成每個類的一個文件,把它們放在一個根據rails慣例命名的dir中(SomeClass =>some_class.rb),並在啓動文件(比如,創建config/initializers文件),請致電:

    autoload_paths Rails.application.config.root + "/path/to/lib" 
    
  2. 這樣添加的東西到啓動文件:

    %W[ 
        Class1 Class2 
        Class3 Class4 Class4 
    ].map(&:to_sym).each dp |klass| 
        autoload klass,Rails.application.config.root + "/path/to/lib/file" 
    end 
    

    這當然每次將新類添加到文件時都必須更新。

  3. 將所有類移動到一個模塊/類的命名空間,並呼籲autoload將其添加爲上述

  4. 只是require加載整個文件的前期的啓動文件。問問你自己:額外的努力是否有必要延遲這個文件的加載?

0

以下文件app/models/statistic.rb給出:

class Statistic 
    # some model code here 
end 

class UsersStatistic < Statistic; end 
class CommentsStatistic < Statistic; end 
class ConnectionsStatistic < Statistic; end 

創建一個文件config/initializers/autoload_classes.rb,並添加以下代碼:

# Autoloading subclasses that are in the same file 


# This is the normal way to load single classes 
# 
# autoload :UsersStatistic, 'statistic' 
# autoload :CommentsStatistic, 'statistic' 
# autoload :ConnectionsStatistic, 'statistic' 


# This is the most dynamic way for production and development environment. 
Statistic.subclasses.each do |klass| 
    autoload klass.to_s.to_sym, 'statistic' 
end 



# This does the same but loads all subclasses automatically. 
# Useful only in production environment because every file-change 
# needs a restart of the rails server. 
# 
# Statistic.subclasses