如何使用元编程进行干燥? [英] How to DRY using metaprogramming?

查看:71
本文介绍了如何使用元编程进行干燥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎应该有一种通过MP来干燥的好方法:

Seems like there should be a good way via MP to DRY this up:

class Dashboard

  def self.num_registrations_past_day
    return User.recent_registrations(24.hours.ago).count
  end

  def self.num_registrations_past_three_days
    return User.recent_registrations(3.days.ago).count
  end

  def self.num_registrations_past_seven_days
    return User.recent_registrations(7.days.ago).count
  end

  def self.num_registrations_past_month
    return User.recent_registrations(30.days.ago).count
  end

  def self.avg_registrations_past_three_days
    return (self.num_registrations_past_three_days / 3.to_f)
  end

  def self.avg_registrations_past_seven_days
    return (self.num_registrations_past_seven_days / 7.to_f)
  end

  def self.avg_registrations_past_month
    return (self.num_registrations_past_month / 30.to_f)
  end

  def self.total_registered_users
    return User.count
  end

  def self.total_activated_users
    return User.total_activated
  end

end

推荐答案

我只是将时间长度作为参数传递:

I would just have the length of time passed in as an argument:

def self.num_registrations_since(time)
  User.recent_registrations(time).count
end

def self.avg_registrations_since(time)
  self.num_registrations_since(time) / ((Time.now - time) / 1.day)
end

看,它仍然很可读:

Dashboard.num_registrations_since(3.days.ago)
Dashboard.avg_registrations_since(7.days.ago)

有趣的是,这是元编程方式:

For fun, here is the metaprogramming way:

{ :day => 24.hours.ago,
  :three_days => 3.days.ago,
  :seven_days => 7.days.ago,
  :month => 30.days.ago }.each do |method_suffix, time|
  define_singleton_method "num_registrations_past_#{method_suffix}" do
    User.recent_registrations(time).count
  end
  define_singleton_method "avg_registrations_past_#{method_suffix}" do
    self.send("num_registrations_past_#{method_suffix}") / ((Time.now - time) / 1.day)
  end
end

这篇关于如何使用元编程进行干燥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆