Techioz Blog

月の日付の背景色を確認する

概要

私は毎日の出席を示すカレンダーを持っています。各日付は異なる色で表示されます (例: 従業員が出席している場合は緑色、不在の場合は赤色、休日の場合は灰色)。ステータスに応じて正しい色を選択します。私はwatir Seleniumで以下のコードを試しました:

require 'color'

def get_current_month_and_year_from_calendar(browser)  
  calendar_title_element = @browser.span(class: 'calendar-title')
  calendar_title = calendar_title_element.text
  month, year = calendar_title.split(' ')
  [month, year.to_i]
end

backward_button = @browser.element(xpath: '/html/body/div/section/div[2]/div/div/div[2]/div[1]/div/div/div/a[1]')

current_month, current_year = get_current_month_and_year_from_calendar(@browser)
target_month = "January"
target_year = 2024

while !(current_month == target_month && current_year == target_year)
  backward_button.click
  sleep 1
  current_month, current_year = get_current_month_and_year_from_calendar(@browser)
end

def check_attendance_for_month(browser)
  month_calendar = @browser.elements(xpath: "//table[@class='simple-calendar']//td[contains(@class,'current-month')]")
  
  month_calendar.each do |day|
    color = get_color_for_day(day)
    if day_is_present?(color)
      puts "Day #{day.text} is present"
    elsif day_is_Work_From_Home?(color)
      puts "Day #{day.text} is Work From Home"
    elsif day_is_CompOff_Present?(color)
      puts "Day #{day.text} is CompOff and Present"
    else
      puts "Day #{day.text} has an unknown color"
    end
  end
end

def get_color_for_day(day_element)
  color_style = day_element.style('background-color')
  parse_color(color_style)
end

def parse_color(color_style)
  rgb_match = color_style.match(/\Argba?\((\d+),\s*(\d+),\s*(\d+)/)
  if rgb_match
    red = rgb_match[1].to_i
    green = rgb_match[2].to_i
    blue = rgb_match[3].to_i
    return [red, green, blue]
  end
  nil
end

def day_is_present?(color)
  present_color = [0, 128, 0]  # Green
  compare_colors(color, present_color)
end

def day_is_CompOff_Present?(color)
  compOff_present_color = [255, 165, 0]  # Orange
  compare_colors(color, compOff_present_color)
end

def day_is_Work_From_Home?(color)
  work_from_home_color = [0, 0, 255]  # Blue
  compare_colors(color, work_from_home_color)
end

def compare_colors(color, target_color)
  color && color == target_color
end

check_attendance_for_month(@browser)

end

このコードは、カレンダーを現在の月から 2024 年 1 月に移動しますが、必要なその日の色は表示されません。

解決策

私が見た問題の 1 つは、get_color_for_day() が色を返さないことです。に変更します

def get_color_for_day(day_element)
  color_style = day_element.style('background-color')
  return parse_color(color_style)
end

そして少なくともそのバグは修正されるでしょう。