在以下情況下,include_class偏好在哪里,我可以以某種方式動態更改 的值include_class并重新加載Image,以便它包含 的新值include_class嗎?
module Foo
included do
@test_var = :foo
end
end
module Bar
included do
@test_var = :bar
end
end
Config.include_class = Foo
class Image
include Config.include_class
end
# ... run tests with default configuration for Image, where Image.test_var = :foo
Config.include_class = OtherClass
# ... how can I reload or re-evaluate Image such that Image.test_var = :bar?
語境
我正在嘗試測驗配置選項(通常由初始化程式設定)是否對應用程式有正確的影響。因為這是測驗套件的一部分,所以模塊和類可能會在測驗之前加載,并且所有配置更改都需要在測驗之后重置。
uj5u.com熱心網友回復:
我建議改用改進,在這種情況下,類將在測驗后重置(在任何其他東西上)。我實作了一個沒有 的例子active_concern,但這個想法應該很清楚。此示例可以使用純 ruby?? 作為單個腳本執行。
# This part is just to keep close to your example
class Config
def self.include_class=(klass)
@@include_class = klass
end
def self.include_class
@@include_class ||= nil
end
end
# Assuming Bar is a default module and Foo will be used in tests
module Bar
def print_something
puts 'I am Bar'
end
end
module Foo
def print_something
puts 'I am Foo'
end
end
# Setting default module
Config.include_class = Bar
# Defining Image class
class Image
include Config.include_class
end
#Changing config
Config.include_class = Foo
# This is a refinement
module ImagePatch
# It will include current Config.include_class
# Note that methods from Bar that are not present in Foo will not be removed
refine Image do
include Config.include_class
end
end
# Here we will create module where refinement is activated
module TestEnv
# Activating the patch
using ImagePatch
Image.new.print_something #=>I am Foo
end
#Outside of the TestEnv module we enjoy the default Image class
Image.new.print_something #=>I am Bar
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416387.html
標籤:
