开发者

How can I refactor this Rails 3 code?

Can anybody figure a way to refactor this further?

@hourly_pay = {}
HourlyPay.all.each { |hp| @hourly_pay[t("hourly_pay.#{hp.amount}")] = hp.amount }

Thanks!


Edit: based on the answers I've received, here's how I refactored

HourlyPay.all.map(&:a开发者_运维问答mount).index_by { |hp| t("hourly_pay.#{hp.amount}") }

Placing this into my model directly, this becomes

  def self.get_options
   all.map(&:amount).index_by { |hp| I18n.t("hourly_pay.#{hp.amount}") }
  end

However, I'm not sure if this is more calculation intensive, since I'm calling map on the values returned from the database, and then calling index_by on that. Since my HourlyPay model only includes an id and an amount, I'm not worried about selecting everything. However, if I had a lot more fields, I would do the following instead:

def self.get_options
 select(:amount).map(&:amount).index_by { |hp| I18n.t("hourly_pay.#{hp.amount}") }
end

So only the amount field is selected

Thanks for the responses!


The intention is not very clear here but I suggest that you look at using the index_by method in enumerable class. You'll get the complete HourlyPay object as the value in the hash though and can get the hash in one line.

Consider putting this code in the model if not already there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜