共有5个级别。
每个级别都有一定的天数,在习惯升级到下一级别之前必须通过(按n_days
分解):
case n_days
when 0..9
1
when 10..24
2
when 25..44
3 #Level 3
when 45..69
4
when 70..99
5
else
"Mastery"
end
end
如何使用n_days
这样的习惯指数从当前级别调用<%= habit.current_level.n_days.count_off_from_zero_to_show %>
?
例如,如果我们在第3级专门处于50
,则会在习惯指数中显示第5天。
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
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
level.rb
class Level < ActiveRecord::Base
belongs_to :habit
end
模式
create_table "habits", force: true do |t|
t.integer "missed_days", default: 0
t.text "committed"
t.integer "days_lost", default: 0
t.datetime "date_started"
t.string "trigger"
t.string "target"
t.string "reward"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "order"
end
add_index "habits", ["user_id", "created_at"], name: "index_habits_on_user_id_and_created_at"
add_index "habits", ["user_id"], name: "index_habits_on_user_id"
create_table "levels", force: true do |t|
t.integer "habit_id"
t.integer "days_lost", default: 0
t.integer "missed_days", default: 0
t.integer "current_level"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "levels", ["habit_id"], name: "index_levels_on_habit_id"
要点:https://gist.github.com/RallyWithGalli/c66dee6dfb9ab5d338c2
答案 0 :(得分:0)
在-lboost_regex
方法中,您有两行逻辑,最终代表current_level
的值。如果要在该方法或case语句之外重用该值,则应将值存储在实例变量中,或将逻辑移动到另一个方法中。如果逻辑只对这个类很重要,那么我可能会把它变成私有方法。
n_days
私有方法可以进一步完善,但希望这可以让您了解如何继续提取共享逻辑。