(rails) SimpleCalenderGemのコードを読みながら、Report機能の処理を考え直す

  • SimpleCalenderのコードを読む

    • view_contextというViewクラスのインスタンスを操作していた
    • Calenderクラスを継承し、WeekCalender, MonthCalendeの2つのクラスが作られ処理を分けて書いていた。
  • params[:period]で条件分岐して、別のReportインスタンスを作成する(WeeklyReport, MonthlyReport)

  • それぞれのクラスでnext_period, prev_periodというメソッドを定義して、Viewからメソッドにアクセスできるようにする

  • SimpleCalender gem のコードを読もうとしたが、まだまだ分からない部分が多かった。プロを目指す人のためのRuby入門に書かれていたコードが多く出てきたが、理解しにくい。教科書と応用の差を感じた。

  • Railsの仕組みを少し知ることができた。(コントローラのインスタンス変数がViewでそのまま使えるのはなぜか?など)

class StatisticsController < ApplicationController
  before_action :require_user_logged_in, :set_current_user

  def report
    set_params(statistics_params)
    if period == :week
      @chart  = GenerateReport::Report::WeeklyReport.new(current_user, column, period, date_begin, date_end).call
    else period == :month
      @chart  = GenerateReport::Report::MonthlyReport.new(current_user, column, period, date_begin, date_end).call
    end
  end

private

  def set_params(params)
    column = params[:column].nil? ? :activity : params[:column].to_sym
    period = params[:period].nil? ? :week : params[:period].to_sym
    date_begin = params[:date_begin].nil? ? Date.today.begininng_of_week : params[:date_begin].to_date
    date_end = params[:date_end].nil? ? Date.today.end_of_week : params[:date_end].to_date
  end

  def statistics_params
    params.permit(:column, :date_begin, :date_end, :period).to_h
  end
end