2016-05-14 59 views
-2

如果滿足多個條件,我試圖從下拉列表中替換一個值。我試圖用gsub方法做到這一點。具有條件的ruby gsub

enter image description here

場景1:如果當前選定的值是9.3.9然後值9.4.1不應該可用

場景2: 如果當前選擇的值爲9.3.10然後值9.4.1和9.4.4不應該可用

對不起,不包括代碼段。以下是我用來獲取我的RDS實例的方法。我已經使用gsub來檢查當前使用的版本是否爲9.3,並防止升級到9.4。我想將其改爲上面的場景。

def available_engine_versions(instance) 
     if instance.engine == RdsGeneric::RDS_TYPE_MYSQL 
     # This custom override for certain MySQL cases suppresses the option to upgrade to 5.6 from 5.5. 
     # Amazon cannot do direct updates from MySQL 5.5 to MySQL 5.6 for DBs created before 4/23/2014. 
     # instance.instance.created_at -> Uses Amazon's date of creation, not the one stored by ActiveRecord 
     if instance.nil? || instance.engine_version.start_with?('5.6.') || instance.instance.nil? || instance.instance.created_at >= Time.parse('2014-04-23') 
      RdsConfiguration::rds_configurations[RdsGeneric::RDS_TYPE_MYSQL][:engine_versions] 
     else 
      RdsConfiguration::rds_configurations[RdsGeneric::RDS_TYPE_MYSQL][:engine_versions].select{ |type| type.to_f <= 5.5 } 
     end 
     elsif instance.engine == RdsGeneric::RDS_TYPE_POSTGRES 
     RdsConfiguration::rds_configurations[RdsGeneric::RDS_TYPE_POSTGRES][:engine_versions].select{ |type| type.gsub(/(\d+\.\d+).*?$/,"\\1") == instance.engine_version.gsub(/(\d+\.\d+).*?$/,"\\1") } # no upgrades from e.g. 9.3.x to 9.4.y 
     else 
     RdsConfiguration::rds_configurations[instance.engine][:engine_versions] 
     end 
    end 
+1

你如何存儲版本列表和選定的版本?需要看一些代碼來提供答案;例如,gsub是一個字符串操作符,但我希望你實際上正在檢查一個數組 –

+0

這看起來像一個JavaScript問題。你確定你需要Ruby來做到這一點嗎? – tadman

+1

您也可能想要將這些「版本化」排序,而不是按默認排序順序排序:'sort_by {| v | v.split.collect(&:to_i)}' – tadman

回答

1

我相信這將工作:

selected_value = instance.engine_version.gsub(/(\d+\.\d+\.\d+).*?$/,"\\1") 
RdsConfiguration::rds_configurations[RdsGeneric::RDS_TYPE_POSTGRES][:engine_versions].reject do |type| 
    dropdown_entry = type.gsub(/(\d+\.\d+\.\d+).*?$/,"\\1") 

    (dropdown_entry == "9.4.1" && selected_value == "9.3.9") || (["9.4.1", "9.4.4"].include?(dropdown_entry) && selected_value == "9.3.10") 
end 

注意,我改變selectreject

瞭解數據看起來會有多大幫助。現在你可能根本不需要gsub。

+0

數據只是通過aws API提取的版本號,因此其格式是一致的,例如, 9.3.x等。如果9.3版本當前正在使用,則gsub用於隱藏引擎選項的較新版本(9.4.x等)。如果可能,我仍然希望匹配數據格式。但你是對的,也許gsub是矯枉過正的。我很想聽聽你的建議。 – user1576738

+0

我知道你可以簡單地刪除gsub並做一個直接的比較,但我想確保格式是一致的(至少從我的結尾)。 – user1576738

+0

順便說一句,感謝您的建議,上面的工作。 ;-) – user1576738