重构ruby:想要将属性名称传递给方法

时间:2015-06-05 20:20:02

标签: ruby-on-rails ruby

我有一个DataPoint模型,我有三个方法可以做同样的事情,只是在data_points数据库的不同字段上。

def self.currently_employed(data_points)
    data_points.where(currently_employed: true).count / data_points.count.to_f * 100
end

def self.undergrad_degree(data_points)
    data_points.where(undergrad_degree: true).count / data_points.count.to_f * 100
end

def self.grad_degree(data_points)
    data_points.where(grad_degree: true).count / data_points.count.to_f * 100
end

我认为我应该能够重构这个以接受哪个列作为参数执行计算,但是在互联网上大量的时间/尝试的东西都没有产生结果。

有人可以告诉我是否/如何将其重构为单一方法?

如果它影响答案:data_points参数是用户指定的DataPoint.all的子集 - 即用户输入他们想要查看结果的年龄,年工作经验等等(年龄和年龄_工作经验是DataPoint属性),然后我想显示该子集的摘要统计信息。

谢谢!

2 个答案:

答案 0 :(得分:1)

属性的名称实际上只是哈希中的一个键。

data_points.where(currently_employed: true)

相当于

data_points.where({:currently_employed => true})

考虑到这一点,很容易将这些方法重构为一个:

def self.percent_with_attribute(data_points, attribute)
    data_points.where(attribute => true).count / data_points.count.to_f * 100
end

答案 1 :(得分:0)

您可以在此处使用字符串插值。

def self.status(data_points, key)
  data_points.where("#{key}": true).count / data_points.count.to_f * 100
end

与@ Ajedi32的不同之处仅在于此处key将转换为Symbol,而不是普通String