require - Is there a way to force a required file to be reloaded in Ruby? -
yes, know can use load instead of require. not solution use case:
when app boots, requires config file. each environment has own config. config sets constants.
when app boots, 1 environment required. however, during testing, loads config files multiple times make sure there no syntax errors.
in testing environment, same config file may loaded more once. don't want change require load because every time spec runs, reloads config. should done via require, because if config has been loaded, raises already initialized constant warnings.
the cleanest solution can see manually reset require flag config file after config spec.
is there way in ruby?
edit: adding code.
when app boots calls init file:
init.rb: require "./config/environments/#{ env[ 'rack_env' ]}.rb" config/environments/test.rb: app_setting = :foo config/environments/production.rb: app_setting = :bar spec/models/config.rb: # it's not model spec... describe 'config' specify load './config/environments/test.rb' end specify load './config/environments/production.rb' end
yes can done. must know path files want reload. there special variable $loaded_features stores has been loaded, , used require decide whether load file when requested again.
here assuming files want re-require have unique path /myapp/config/ in name. can see work rule path name can code.
$loaded_features.reject! { |path| path =~ /\/myapp\/config\// } and that's . . .
some caveats:
requirenot store or follow kind of dependency tree, know "should" have loaded. need ensure full chain ofrequires startingrequirecommand run in spec re-load config, , including need loaded, covered removed paths.this not unload class definitions or constants, re-load files. in fact literally
requiredoes, callsloadinternally. warning messages re-defining constants need handled un-defining constants expect see defined in files.there design of config , specs avoids need this.
Comments
Post a Comment