当我使用lib和助手时未初始化的常量

时间:2019-02-23 08:17:39

标签: ruby-on-rails helper ruby-on-rails-5.2

我对滑轨有问题。 我正在做的是创建一个基本日历,创建逻辑放在文件夹/lib/中,我用一个名为calendar_helper.rb的助手来邀请它,然后从应用程序视图中调用它,并传递相应的参数。我也通过相应的驱动程序获取日期数据 我有以下

/lib/calendar.rb

class Calendar < Struct.new(:view, :date, :callback)
HEADER = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday]
START_DAY = :sunday

delegate :content_tag, to: :view

def table
  content_tag :table, class: "calendar table table-bordered table-striped" do
    header + week_rows
  end
end

def header
  content_tag :tr do
    HEADER.map { |day| content_tag :th, day }.join.html_safe
  end
end

def week_rows
  weeks.map do |week|
    content_tag :tr do
      week.map { |day| day_cell(day) }.join.html_safe
    end
  end.join.html_safe
end

def day_cell(day)
  content_tag :td, view.capture(day, &callback), class: day_classes(day)
end

def day_classes(day)
  classes = []
  classes << "today" if day == Date.today
  classes << "not-month" if day.month != date.month
  classes.empty? ? nil : classes.join(" ")
end

def weeks
  first = date.beginning_of_month.beginning_of_week(START_DAY)
  last = date.end_of_month.end_of_week(START_DAY)
  (first..last).to_a.in_groups_of(7)
end

结束

/app/helpers/calendar_helper.rb

module CalendarHelper
 def calendar(date = Date.today, &block)
    Calendar.new(self, date, block).table
  end

end

/ app / controllers / index_controller

class IndexController < ApplicationController
    helper CalendarHelper
  def index
    @date = params[:date] ? Date.parse(params[:date]) : Date.today
  end
end

/app/views/index/index.html.erb

<div class="row">
  <div class="col-md-12 text-center">
    <div class="well controls">
      <%= link_to calendar(date: @date - 1.month), class: "btn btn-default" do %>
        <i class="glyphicon glyphicon-backward"></i>
      <% end %>
      <%= "#{@date.strftime("%B")} #{@date.year}" %>
      <%= link_to calendar(date: @date + 1.month), class: "btn btn-default" do %>
        <i class="glyphicon glyphicon-forward"></i>
      <% end %>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-md-12">
    <%= calendar @date do |date| %>
      <%= date.day %>
    <% end %>
  </div>
</div>

我收到以下错误:

uninitialized constant CalendarHelper::Calendar
Extracted source (around line #3):

module CalendarHelper
 def calendar(date = Date.today, &block)
    Calendar.new(self, date, block).table
  end

end

我的问题是我该如何解决?谢谢。

1 个答案:

答案 0 :(得分:2)

默认情况下,Rails 5不会添加lib来自动加载路径,请将以下内容添加到config/application.rb中:

config.paths.add "lib", eager_load: true