Peter R
Peter R

Reputation: 3516

Ruby / Rails - File naming conventions and dealing with uppercase model names (i.e. CSV vs Csv)

So I'm using a model to track CSV uploads. When using FactoryGirl in my specs, OR when trying to access the model via an association (i.e. user.csv_uploads) I get the following error when trying to use the linter.

Failure/Error: FactoryGirl.lint

LoadError:
  Unable to autoload constant CsvUpload, expected .../APP_NAME/app/models/csv_upload.rb to define it


user.csv_uploads

LoadError: Unable to autoload constant CsvUpload, expected .../APP_NAME/app/models/csv_upload.rb to define it

That file does define a model called CSVUpload, but strictly following naming conventions, I guess it should be CsvUpload. Currently the model loads correctly, and typing something like CSVUpload.new in the console works as expected. But certain other situations have the load error. I assume this is when trying to convert a symbol or filename into a class name, and then trying to use that. i.e. :csv_upload.to_s.camelize.constantize. Is there a simple way to fix this? Or will a be a constant uphill battle that is best fixed by going with CsvUpload?

Upvotes: 3

Views: 1262

Answers (1)

Simple Lime
Simple Lime

Reputation: 11035

Rails uses the ActiveSupport::Inflector for things like constantize-ing strings, so you can tell the inflector that csv should be an acronym and not a part of the usual "first character uppercase and the rest lowercase" that is used for most things. You do this in an initializer (looks to be there by default config/initializers/inflections.rb) by using the following code:

ActiveSupport::Inflector.inflections(:en) do |inflect|
   inflect.acronym 'CSV'
end

Upvotes: 9

Related Questions