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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With