Cannot load converter in rails app – not autoloading?

  Kiến thức lập trình

I am working on a Rails app with Rails 7.0.8.4 using subclasses for products with variable attributes. Part of the workflow revolves around uploading a CSV with product specs which are then validated and dumped into the database.

However, one issue is that CSV values by default are entered as strings, and there are fields that I want to convert to floats (for example).

After writing some code to get the job done, I tried to move it out into a separate file but I cannot get the app to properly detect the converter.

Initially, when I settles on one subclass of product I ran a test by uploading some specs. When I discovered the issue with the CSV default type of string, I entered some code into my input service to fix some of the values and everything worked fine:

 product_data = row.to_hash.compact.merge(brand_id: brand.id)
 product_data[:tire_width_inch] = row[:tire_width_inch].to_f if row[:tire_width_inch].present?
 product_data[:tire_width_mm] = row[:tire_width_mm].to_f if row[:tire_width_mm].present?
 product_data[:weight_g] = row[:weight_g].to_f if row[:weight_g].present?

Once this was done, I figured it would be better to create a directory under the app folder to house all of the conversions for each subclass.

I created a folder called converters underneath app, and then created a ruby file called tire_conversions.rb with the following code:

module Converters
  module TireConversions
    def self.convert(row)
      row[:tire_width_inch] = row[:tire_width_inch].to_f if row[:tire_width_inch].present?
      row[:tire_width_mm] = row[:tire_width_mm].to_f if row[:tire_width_mm].present?
      row[:weight_g] = row[:weight_g].to_f if row[:weight_g].present?
      row
    end
  end
end

Now, the in csv import code when processing the data I use:

    row = convert_row_based_on_type(row)

from

def convert_row_based_on_type(row)
    return row unless row[:type].present?

    converter_module = "Converters::#{row[:type]}Conversions".constantize
    converter_module.convert(row)
  rescue NameError
    row
  end

But it doesn’t work. When I added some logging to try and figure out what is going on I get:

Attempting to load converter module: Converters::TireConversions
Converter not found for type: Tire
uninitialized constant Converters

So the proper subtype is being detected, but the converter isn’t found. I have double and triple checked that my converters folder is located in my app folder, and even tried adding the specific directory to my autoload paths but that didn’t help either.

Any ideas why my converter isn’t being found?

3

LEAVE A COMMENT