Don’t Repeat Yourself
“Don’t Repeat Yourself”
DRY – “Don’t Repeat Yourself” – suggests that writing the same code over and over again is a bad thing.
今天在写代码的时候,又犯了以前的坏习惯,把一段同样的代码重复了好多次,这与 Rails 的哲学不符。
我在做 city 的 CRUD 的时候, 在 show, edit, update, destroy 这4个action 里都用到 @city = City.find params[:id],重复了4次!经高人指点,我可以使用 before_action 来避免这样的重复: