【问题标题】:Virtual attributes with multiple parameters具有多个参数的虚拟属性
【发布时间】:2012-10-30 05:20:49
【问题描述】:

我有以下功能很好用

def holiday_hours_for(holiday)
  hours["holiday_hours"][holiday.to_s] if hours["holiday_hours"][holiday.to_s]
end

我只是在学习虚拟属性,在弄清楚这个函数的 setter 版本时遇到了一些麻烦。我该如何实现这个功能...

def holiday_hours_for(holiday)=(hours)
  self.hours["holiday_hours"][holiday.to_s] = hours if hours["holiday_hours"][holiday.to_s]
end

谢谢!

更新:我想出了以下方法,这是最好的方法吗?

  def update_holiday_hours_for(holiday, hours_text)
    self.hours = Hash.new unless hours
    self.hours["holiday_hours"] = Hash.new unless hours["holiday_hours"]
    self.hours["holiday_hours"][holiday.to_s] = hours_text.to_s
  end

【问题讨论】:

    标签: ruby-on-rails-3 mongoid virtual-attribute


    【解决方案1】:

    要理解的重要一点是,setter 方法的末尾带有“=”符号。像这样:

    def holiday_hours=(some_parameters)
      # some code
    end
    

    这类似于实例变量@holiday_hours 的setter 方法。方法名称是“holiday_hours=”,它需要一个或多个参数,根据您的应用程序的要求来派生@holiday_hours 属性的值。当 Ruby 看到类似的代码时

    holiday.holiday_hours = some_value
    

    它调用你定义的setter方法。即使此分配中有一些空白不在 setter 方法中。 Ruby 将此赋值解释为

    holiday.holiday_hours=(some_value)
    

    在假期对象上调用 holiday_hours= 方法,参数为 some_value

    从您的帖子中不清楚您的示例方法所在的类是什么,我可以猜到变量 hours_text 是什么,但是参数 holiday 是什么?

    【讨论】:

    • holiday 将是指定哪个假期的参数。圣诞节、新年等
    • 我认为您没有使用虚拟属性。您只是在设置一个哈希值。虚拟属性是指为对象调用 setter 方法,但实际上它并没有由 setter 命名的属性。当方法被调用时,它会设置一个实际的属性。
    猜你喜欢
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2014-10-18
    相关资源
    最近更新 更多