如何使用 Sandi Metz 规则重写此代码片段?
How to rewrite this code snippet using Sandi Metz rules?
假设我有一个 Survey
rails 模型 has_many: questions
并且需要能够重新排序问题...
我应该在哪里放置 renumber_questions
方法(调查模型、问题模型或其他 class,为什么?)以及如何在 [=14 之后最好地编写下面这个丑陋的方法=]?
def renumber_questions
last_page = 0
new_page = 0
new_seq = 0
questions.unscope(:order).order(page: :asc, seq: :asc).each do |question|
if last_page != question.page
new_page = new_page + 1
end
last_page = question.page
new_seq = new_seq + 1
question.page = new_page
question.seq = new_seq
question.save
end
end
把它放在另一个 class 上,因为单一职责(在你给的 link 中提到)。
Despite the large number of private methods we wrote, keeping classes short proved easy. It forced us to consider what the single responsibility of our class was, and what should be extracted.
class RenumberQuestions
def initialize(questions)
@questions = questions.unscope(:order).order(page: :asc, seq: :asc)
@last_page = 0
@new_page = 0
@new_seq = 0
end
def call
@questions.each do |question|
counting_var(question)
mutate_(question)
end
end
def counting_var(question)
@new_page += 1 if @last_page != question.page
@last_page = question.page
@new_seq += 1
end
def mutate_(question)
question.page = @new_page
question.seq = @new_seq
question.save
end
end
抱歉命名错误。我不知道你是做什么的,所以我只是按照我的理解命名它。你可以让它更干净。
假设我有一个 Survey
rails 模型 has_many: questions
并且需要能够重新排序问题...
我应该在哪里放置 renumber_questions
方法(调查模型、问题模型或其他 class,为什么?)以及如何在 [=14 之后最好地编写下面这个丑陋的方法=]?
def renumber_questions
last_page = 0
new_page = 0
new_seq = 0
questions.unscope(:order).order(page: :asc, seq: :asc).each do |question|
if last_page != question.page
new_page = new_page + 1
end
last_page = question.page
new_seq = new_seq + 1
question.page = new_page
question.seq = new_seq
question.save
end
end
把它放在另一个 class 上,因为单一职责(在你给的 link 中提到)。
Despite the large number of private methods we wrote, keeping classes short proved easy. It forced us to consider what the single responsibility of our class was, and what should be extracted.
class RenumberQuestions
def initialize(questions)
@questions = questions.unscope(:order).order(page: :asc, seq: :asc)
@last_page = 0
@new_page = 0
@new_seq = 0
end
def call
@questions.each do |question|
counting_var(question)
mutate_(question)
end
end
def counting_var(question)
@new_page += 1 if @last_page != question.page
@last_page = question.page
@new_seq += 1
end
def mutate_(question)
question.page = @new_page
question.seq = @new_seq
question.save
end
end
抱歉命名错误。我不知道你是做什么的,所以我只是按照我的理解命名它。你可以让它更干净。