defget_gc_version_from_userputs"Type a version d.d.d or leave blank to get the latest gc:"@gc_version=get_user_inputenddefget_gv_version_from_userreturnunless@config[:import_gv]puts"Type a version d.d.d or leave blank to get the latest gv:"@gv_version=get_user_inputenddefget_game_combo_version_from_userreturnunless@config[:import_game_combo]puts"Type a version d.d.d or leave blank to get the latest game combo:"@game_combo_version=get_user_inputend
After refactor, use array to create methods. define_method is used to define new methods dynamically.
do |argument| means your could pass parameters in. instance_variable_set is used to set a instance varaible
after_refactor
1234567
['gc','gv','game_combo'].eachdo|item|define_method("get_#{item}_version_from_user")do|argument|returnunlessargumentputs"Type a version d.d.d or leave blank to get the #{item}"instance_variable_set("@#{item}_version",get_user_input)endend
I found it’s unconvenient to pass parameter everytime. Methods should determine if it’s executed or not.
So i did a little updated. Use instance_variable_get to access instance variable and determine return or not.
after_refactor2
1234567
['gc','gv','game_combo'].eachdo|item|define_method("get_#{item}_version_from_user")returnunlessinstance_variable_get("@config")["import_#{item}".to_sym]puts"Type a version d.d.d or leave blank to get the #{item}"instance_variable_set("@#{item}_version",get_user_input)endend
Originally i will retrieve the latest version from mvn if user doens’t specific the target deployment version.
before_refactor
1234567891011121314151617181920
defcheck_gc_versionif@gc_version.nil?@gc_version=MvnUtils.find_latest_gc_versionabort("Can't find the latest gc version.")if@version.nil?endenddefcheck_gv_versionreturnunless@config[:import_gv_game]if@gv_version.nil?@gv_version=MvnUtils.find_latest_gv_versionabort("Can't find the latest gv version.")if@gv_version.nil?endenddefcheck_game_combo_versionreturnunless@config[:import_game_combo]if@game_comb_version.nil?@game_comb_version=MvnUtils.find_latest_game_combo_versionabort("Can't find the latest game comb version.")if@game_comb_version.nil?endend
Use .send() to invoke object’s method
after_factor
123456789
['gc','gv','game_combo'].eachdo|item|define_method("check_#{item}_version")returnunlessinstance_variable_get("@config")["import_#{item}".to_sym]ifinstance_variable_get("@#{item}_version").nil?instance_variable_set("@#{item}_version",MvnUtils.send("find_latest_#{item}_version"))abort("Can't find the latest #{item} version.")ifinstance_variable_get("@#{item}_version").nil?endendend