0

我正在验证这样的父母的子对象:

validate :overdue_tasks_valid
validate :created_overdue_tasks_valid

然后我有这样的方法:

private
def overdue_tasks_valid
  validate_notification(overdue_tasks, :overdue_tasks)
end

def created_overdue_tasks_valid
  validate_notification(created_overdue_tasks, :created_overdue_tasks)
end

def validate_notification(notification, key)
  return if notification.valid?

  notification.errors.full_messages.each do |message|
    errors.add key, message
  end
end

我想知道的是,我可以只将一个参数传递给 validate_notfication 并以某种方式确定方法中的符号吗?

所以验证通知会这样调用:

validate_notification(overdue_tasks)

该方法如下所示:

def validate_notification(notification)
  return if notification.valid?

  notification.errors.full_messages.each do |message|
    errors.add [SOMEHOW GET THE SYMBOL], message
  end
end
4

1 回答 1

0

不可以,但您可以改为发送符号:

def overdue_tasks_valid
  validate_notification :overdue_tasks
end

def created_overdue_tasks_valid
  validate_notification :created_overdue_tasks
end

def validate_notification(method)
  notification = send method
  return if notification.valid?

  notification.errors.full_messages.each do |message|
    errors.add method, message
  end
end

秘诀当然是Object#send

于 2013-08-20T05:06:30.787 回答