【发布时间】:2015-07-16 22:46:15
【问题描述】:
在我的习惯模型中,我创建了一个新方法:
def current_level_days
current_level[n_days]
end
我们如何在新方法中调用n_days的case变量,这样我就可以实现Counting the Days from the current_level?的更大目标
habit.rb
class Habit < ActiveRecord::Base
belongs_to :user
has_many :comments, as: :commentable
has_many :levels
serialize :committed, Array
validates :date_started, presence: true
before_save :current_level
acts_as_taggable
scope :private_submit, -> { where(private_submit: true) }
scope :public_submit, -> { where(private_submit: false) }
attr_accessor :missed_one, :missed_two, :missed_three
def save_with_current_level
self.levels.build
self.levels.build
self.levels.build
self.levels.build
self.levels.build
self.save
end
def self.committed_for_today
today_name = Date::DAYNAMES[Date.today.wday].downcase
ids = all.select { |h| h.committed.include? today_name }.map(&:id)
where(id: ids)
end
def current_level_strike
levels[current_level - 1] # remember arrays indexes start at 0
end
def current_level_days
current_level(:n_days) # remember arrays indexes start at 0
end
def current_level
return 0 unless date_started
committed_wdays = committed.map { |day| Date::DAYNAMES.index(day.titleize) }
n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday } - self.missed_days
case n_days
when 0..9
1
when 10..24
2
when 25..44
3
when 45..69
4
when 70..99
5
else
"Mastery"
end
end
end
要点:https://gist.github.com/RallyWithGalli/c66dee6dfb9ab5d338c2
非常感谢您的专业知识!
【问题讨论】:
-
n_days的范围是current_level方法,它只返回其中一个值以防万一。只要它返回n_days就会超出范围。此外current_level不接受参数,因此如果您希望n_days可访问,您将获得ArgumentError,或者将其构建为方法并在需要时引用它,或者将其创建为实例变量并引用它。同样current_level不返回Array它返回一个字符串或整数,因此current_level[n_days]最终将是一个字母nil,或者如果是整数,这将是位引用0 或1
标签: ruby-on-rails ruby methods model