Reputation: 887
Where should I put my simple classes that are not models (they don't represent any data) and provides only some functionality?
Like for example:
class FileUploader
def save_uploaded_file(filename, tempfile)
path = Rails.root.join('public', 'uploads', filename)
File.open(path, 'wb+') do |file|
file.write(tempfile.read)
end
end
end
What this does is just simply copies file to predefined place.
Do I must to place this under models
? Or do Rails have some other location more suitable for those kind of classes? I tried to put in lib
before, but it was just too much of the pain as Rails cached those files inside lib
directory (edited config to not cache files, but it still cached inside lib
).
So, I placed those files in models
but testing becomes very painful (I'm just starting Rails, maybe I'm doing something wrong with the tests) as rake spits out errors about not having set up a test database (I want to test classes that are not related to database in any form or shape - why do I need to set up a database?).
Upvotes: 2
Views: 1172
Reputation: 29880
For service-type objects I put them in app/services.
For model-type objects I put them in app/models. I do not think it is necessary to inherit from ActiveRecord to be considered a model.
I think your object classifies as a 'service object' since it is designed to wrap the service of uploading a file, it isn't really a domain object like a model would be.
Upvotes: 2
Reputation: 211740
I've taken to adding app/lib
to some of my projects to accommodate this, but there's also the new Rails 4 concerns
locations like app/models/concerns
or app/controllers/concerns
depending on where this sort of thing is used.
You're right that it's best to avoid putting non-model classes in app/models
.
Upvotes: 5