我創建了一個類方法,該方法在創建新物件并從舊的現有物件復制時呼叫。但是,我只想復制一些值。我可以使用某種 Ruby 速記來清理它嗎?這不是完全必要的,只是想知道是否存在這樣的東西?
下面是我想要 DRY up 的方法:
def set_message_settings_from_existing existing
self.can_message = existing.can_message
self.current_format = existing.current_format
self.send_initial_message = existing.send_initial_message
self.send_alert = existing.send_alert
self.location = existing.location
end
顯然這作業得很好,但對我來說看起來有點難看。有什么辦法可以清理這個嗎?如果我想復制每個值都足夠簡單,但因為我只想復制這 5 個(大約 20 個)值,所以我決定這樣做。
uj5u.com熱心網友回復:
def set_message_settings_from_existing(existing)
[:can_message, :current_format, :send_initial_message, :send_alert, :location].each do |attribute|
self.send("#{attribute}=", existing.send(attribute))
end
end
或者
def set_message_settings_from_existing(existing)
self.attributes = existing.attributes.slice('can_message', 'current_format', 'send_initial_message', 'send_alert', 'location')
end
uj5u.com熱心網友回復:
散列可能更干凈:
def set_message_settings_from_existing existing
fields = {
can_message: existing.can_message,
current_format: existing.current_format,
send_initial_message: existing.send_initial_message,
send_alert: existing.send_alert,
location: existing.location
}
self.attributes = fields
end
您可以通過僅選擇所需的屬性來更進一步:
def set_message_settings_from_existing existing
fields = existing.attributes.slice(
:can_message,
:current_format,
:send_initial_message,
:send_alert,
:location
)
self.attributes = fields
end
此時您還可以在某處定義這些欄位,例如:
SUB_SET_OF_FIELDS = [:can_message, :current_format, :send_initial_message, :send_alert, :location]
并將其用于您的過濾器instance.attributes.slice(SUB_SET_OF_FIELDS)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536886.html
上一篇:如何設定和查看環境變數GoogleAppEngine
下一篇:引數名稱的字串
