Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails uninitialized constant when instantiating class

I have created a new class in my Rails application under a folder structure of app/datatables

The class is saved in a file in this directory and it is saved as DatasetIndexDatatable.rb

The contents of the class file is as follows:

class DatasetIndexDatatable
  delegate :params, :h, :link_to, :number_to_currency, to: :@view

  def initialize(view)
    @view = view
  end

end

When I try to instantiate this class from a controller in my application, Rails gives an error:

uninitialized constant DatadescriptionController::DatasetIndexDatatable

The code in the controller which attempts to instantiate the new class is as follows:

class DatadescriptionController < ApplicationController
  layout "datadescription"

  def index
respond_to do |format|
        format.html
        format.json { render json: DatasetIndexDatatable.new(view_context) }
    end
  end

end

Why can't Rails see the new class? I have tried adding the folder containing the class to the config.autoload_paths variable in application.rb:

config.autoload_paths += %W(#{config.root}/lib
                            #{config.root}/datatables)

but the same error occurs. I have also tried instantiating the new class in the controller using the global namespace:

format.json { render json: ::DatasetIndexDatatable.new(view_context) }

and using the containing folder for the class as a namespace:

format.json { render json: Datatables::DatasetIndexDatatable.new(view_context) }

all to no avail. What am I doing wrong?

like image 259
user1022788 Avatar asked Dec 03 '22 21:12

user1022788


1 Answers

The file is named incorrectly. Instead of:

DatasetIndexDatatable.rb

Call it:

dataset_index_datatable.rb

This is a Rails standard naming convention. If you define a CamelCase class, the file that contains the definition should be named camel_case.rb which is lower case with underscore (a.k.a., snake case).

like image 132
lurker Avatar answered Dec 05 '22 10:12

lurker