単一のテキストフィールド内に保存されている複数の仮想属性をフォームで編集する「正しい」レールの方法を探しています。
現在、8 つの仮想属性を 1 つのテキスト フィールドに保存し、次のような簡単に解析できる文字列として保存します。"weekday=monday; repeat_weekly_for= 5; repeat_monthly_for=4; ..."
次に (以下で詳しく説明します)、フォームには各仮想属性の text_field があり、モデルには各仮想属性の getter と setter があります。
属性値が必要な場合、または属性値を設定する必要がある場合、最初に正規表現を使用して文字列をハッシュに解析します。
できます。問題は、ユーザーがフォームを表示して更新するたびに、同じ正規表現パーサーが 16 回呼び出されることです (8 つの仮想属性を「読み取る」ために 8 回、8 つの仮想属性のそれぞれを「書き込む」ために 8 回)。
一度に 8 つの仮想属性すべてに対して getter と setter を実装する方法はありますか?
仕様:
現在、フォームは次のようになっています。
= f.text_field :weekday /first virtual attribute
= f.text_field :repeat_weekly_for /second virtual attribute
= f.text_field :repeat_monthly_for /third virtual attribute
...
したがって、同じように見える仮想属性ごとにゲッターとセッターがあります。
def weekday
self.schedule_to_hash['weekday'] # this gets done 8 times for 8 attributes
end
def weekday=(the_weekday)
schedule_hash = self.schedule_to_hash # this gets done 8 times for 8 attributes
schedule_hash['weekday'] = the_weekday
self.hash_to_schedule(schedule_hash) # this gets done 8 times for 8 attributes
end
各ゲッターとセッターは、次の 2 つのメソッドを使用して、ハッシュ形式と文字列形式を変換します。
def schedule_to_hash()
# takes string self.schedule, does regex to split into hash, returns the hash
end
def hash_to_schedule(some_hash)
# put the hash into a string format compatible with the regex in schedule_to_hash()
end