2015-06-24 35 views
0

所以我想要變得聰明,做一個通用的方法,可以創建變量名稱並正確使用它們。我將2個符號傳入此方法,並創建正確的變量並嘗試使用它們。紅寶石字符串插值和動態編程

def are_numeric_fields_valid (column_name) 
    single_name = column_name[0].to_s 
    aggregate_name = column_name[1].to_s 
    short_column_attribute = single_name.sub("_single", "") 

    effective_on_attribute = :"#{short_column_attribute}_effective_on" 
    expire_on_attribute = :"#{short_column_attribute}_expire_on" 

     if ("loa_item.#{effective_on_attribute}".present? && "loa_item.#{expire_on_attribute}".present?) && (no_values_present?(single_name, aggregate_name)) 
      loa_item.errors.add(:base, "You must provide single and aggregate values when providing dates at the #{short_column_attribute} role level") 
      end 

end 

但是這始終是真實的,即使在實際值爲空:

if ("loa_item.#{effective_on_attribute}".present? && "loa_item.#{expire_on_attribute}".present?) 

我需要別的東西所以這將正確評價?像發送?

回答

0

是的,它需要不同–你打電話present?上,有一個值的字符串:"loa_item.interpolated_value"其中interpolated_value是串代表effective_on_attribute的評價。

它不能不是present?因爲有一個直接的非內插值。

你想要的東西更接近:

loa_item.send(effective_on_attribute.to_sym) etc. 
+0

我喜歡你喲* *看起來.. :) –

+0

@ArupRakshit我很無聊瓦特/正常畫面;)! –

0

是的,您需要使用sendeval的形式將字符串「更改」爲變量。現在,它只是檢查是該字符串present?

例子:loa_item.send(effective_on_attribute).present?