我目前正在开发一个应用程序,用于存储用户表中的成绩,如下所示(json编码):
{"6":"6th Grade","7":"7th Grade","8":"8th Grade"}
每个成绩范围的用户模型中都有常量设置加上一个将它们全部组合起来的常量:
ELEMENTARY = %w(Kindergarten 1st\ Grade 2nd\ Grade 3rd\ Grade 4th\ Grade 5th\ Grade)
MIDDLE_SCHOOL = %w(6th\ Grade 7th\ Grade 8th\ Grade)
HIGH_SCHOOL = %w(9th\ Grade 10th\ Grade 11th\ Grade 12th\ Grade)
GRADES = ELEMENTARY + MIDDLE_SCHOOL + HIGH_SCHOOL
我试图找出一个优雅的解决方案来解析存储在users表中的JSON数据,以便吐出用户所属的等级。因此,如果用户具有以下内容:
{"0":"Kindergarten","1":"1st Grade","2":"2nd Grade","3":"3rd Grade","4":"4th Grade","5":"5th Grade", "6":"6th Grade", "9":"9th Grade"}
然后用户处于“一般”等级范围内。
如果用户在任何常量中选择了任何等级,则它们处于该常数等级范围内。例如:
{"0":"Kindergarten"}
会把它们放在小学里。
答案 0 :(得分:2)
当出现这种情况时,我宁愿重新考虑设计,而不仅仅是试图做一种“解决方法”。正如 cmpolis 所展示的解决方案所表明的那样,这种逻辑并不那么简单。那么,为什么不创建一个新类来处理呢?这样可以更容易地进行维护,也更容易阅读(并且测试 - 如果你编写测试的话)。
考虑到这一点,我只是重构了 cmpolis 发布的解决方案,我想出了类似的内容:
class CheckGradeSpan
def initialize(grades)
@grades = JSON.parse(grades)
end
def is_elementary?
(@grades.keys & ["0", "1", "2", "3", "4", "5"]).length > 0
end
def is_middle_school?
(@grades.keys & ["6", "7", "8"]).length > 0
end
def is_high_school?
(@grades.keys & ["9", "10", "11", "12"]).length > 0
end
end
这样你就有了一个很好的API来检查用户的成绩范围:
grade_check = CheckGradeSpan.new('{"0":"Kindergarten","1":"1st Grade","2":"2nd Grade","3":"3rd Grade"}')
grade_check.is_elementary?
我认为你可以得到这个想法:)
答案 1 :(得分:1)
如果你想要优雅,这是一个不错的解决方案:
data = JSON.parse({"0":"Kindergarten","1":"1st Grade","2":"2nd Grade","3":"3rd Grade"})
gradeSpans = []
gradeSpans << 'Elementary' if (data.keys & ["0", "1", "2", "3", "4", "5"]).length > 0
gradeSpans << 'Middle' if (data.keys & ["6", "7", "8"]).length > 0
gradeSpans << 'High' if (data.keys & ["9", "10", "11", "12"]).length > 0
gradeSpans = 'General' if gradeSpans.length == 3