2013-11-02 64 views
0
module YourApp 
    class Application < Rails::Application 
     config.my_custom_variable = :custom_value 
    end 
end 

這適用於我的Rails應用程序。我只是想從ruby的角度理解這是如何工作的。根據我最小的ruby知識,在config(Rails :: Application :: Configuration)對象中必須有my_custom_variable的getter和setter(my_custom_variable =)。由於這是我的自定義變量,因此它不會出現在Configuration對象實例中。它是如何動態創建/添加的。 ?在Ruby中設置和訪問變量

有人可以請解釋嗎?,指導我正確的文檔來理解這一點。

回答

2

Rails在這裏使用method_missing來捕獲在config上調用的任何方法。然後,它只是將它添加到選項的散列中。

你可以看到相關的源代碼here

0

沒怎麼Rails的實現它,但在Ruby中

require 'ostruct' 

module YourApp 
    class Application 
     @@config = OpenStruct.new 

     def self.config 
      return @@config 
     end 
    end 
end 

YourApp::Application.config.my_custom_variable = :custom_value 
puts YourApp::Application.config.my_custom_variable 
>> custom_value 
實現類似的功能