Garnica1999
Garnica1999

Reputation: 215

uninitialized constant when I use lib and helpers

I have a problem with rails. What I'm doing is creating a basic calendar, the creation logic goes in the folder /lib/, I invite it with a helper, called calendar_helper.rb, and this I call from the application view, passing the respective parameters. I also get the date data through the corresponding driver I have the following

/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

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>

I get the following error:

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

My question is how can I solve it? Thank you.

Upvotes: 1

Views: 839

Answers (1)

Vasfed
Vasfed

Reputation: 18454

Rails 5 by default does not add lib to autoload paths, add the following to your config/application.rb:

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

Upvotes: 4

Related Questions