如何将这个Ruby on Rails代码更改为Laravel?



最近我开始学习Ruby on Rails。我目前正在将现有的Ruby on rails项目转换为Laravel。但是由于我是Ruby on Rails的新手,我不了解现有部分的某些部分。

在现有的Ruby on rails项目application_controller.rb中有一个函数。我不明白该功能的含义。有人可以解释一下代码的含义吗?

application_controller.rb

def new_year_holidays?
t = Time.now
@notification = t >= Rails.application.config.new_year_holidays_start_at &&
t <= Rails.application.config.new_year_holidays_finish_at
start_date = Rails.application.config.new_year_holidays_start_at 
end_date   = Rails.application.config.new_year_holidays_finish_at
@new_year_holidays_start_at = start_date.strftime("%Y年%m月%d日(#{%w(日 月 火 水 木 金 土)[start_date.wday]})")
@new_year_holidays_finish_at = end_date.strftime("%Y年%m月%d日(#{%w(日 月 火 水 木 金 土)[end_date.wday]})")
end

在视图中,他们使用了此变量通知

<% if @notification %>
<p style="border: 1px solid #dab682; background: #fef4d0; text-align: center; width:98%; margin: 0 auto 20px; padding: 10px; color:#a9692b; font-size: 14px; font-weight: bold; line-height: 1.7;">  
<%= @new_year_holidays_start_at  %>より<%= @new_year_holidays_finish_at %>までの年末年始の間、<br>
お見積もりや資料の発送・配送に通常よりお時間を頂く可能性がございます。ご了承ください。</div>
</p>
<% end %>

我只知道new_year_holidays这里的一个函数,但我不知道为什么有一个问号。我知道通知和new_year_holidays_start_at@new_year_holidays_finish_at variable here.在控制器中,他们使用了application_controller.rb

Kakaku::PackageEstimatesController < ApplicationControllerhere

我是Ruby on Rails的初学者。

在 ruby 中,通常的做法是在方法名称中使用问号,该方法返回布尔值(真/假( 您的方法只需检查当前时间是否在假期内。我重构了一下

def new_year_holidays?
t = Time.now # it is better to use Time.current, it works with timezones
# it is two dates from configuration file, you can redefine them anytime
start_date = Rails.application.config.new_year_holidays_start_at 
end_date   = Rails.application.config.new_year_holidays_finish_at 
# if current time is between start and end dates from config, @notification == true, otherwise - false
@notification = t >= start_date && t <= end_date
@new_year_holidays_start_at = start_date.strftime("%Y年%m月%d日(#{%w(日 月 火 水 木 金 土)[start_date.wday]})")
@new_year_holidays_finish_at = end_date.strftime("%Y年%m月%d日(#{%w(日 月 火 水 木 金 土)[end_date.wday]})")
end

所有 @ 变量在视图中都可用,因此如果@notificationtrue用户将看到带有假日日期的块

new_year_holidays?中的问号表示该方法返回布尔值,如truefalse。代码new_year_holidays?似乎决定了今天是否是新年假期。

问号在 Ruby 世界中的方法名称末尾有效。

这只是一个约定,这意味着它将返回一个布尔值。在其他语言的惯例中,它可能是is_new_year_holidaysisNewYearHolidaysIsNewYearHolidays

Ruby 隐式返回上次计算表达式的值。所以在new_year_holidays?方法中,它返回的值@new_year_holidays_finish_at,它似乎没有返回布尔值。我会说这是一个糟糕的方法名称。

最新更新