Search code examples
ruby-on-railsrruby-on-rails-4paperclippaperclip-validation

Upload code files with paperclip


What should be the validates_attachment_content_type configuration in order to be able to upload code files. In my case I want to upload .R files.

I want to do something like this:

class RFile < ActiveRecord::Base
  has_attached_file :r, url: "/system/:attachment/:id/:basename.:extension"
  validates_attachment_content_type :r, content_type: 'text/r'
end

Do I have to define a mime type? How should I do that?

EDIT:

With this code, using text/plain:

class RFile < ActiveRecord::Base
  has_attached_file :r, url: "/system/:attachment/:id/:basename.:extension"
  validates_attachment_content_type :r, content_type: 'text/plain'
end

I get the following errors:

R has contents that are not what they are reported to be
R is invalid
R content type is invalid

I looked at this list of mime types

http://hul.harvard.edu/ois/systems/wax/wax-public-help/mimetypes.htm

But I don't find the one for .R files. But when executing this command:

file --mime-type compare_datasets.R 

I get this result:

compare_datasets.R: text/plain

Why the text/plain does not work?


Solution

  • I manage to be able to get it working by doing this in the mime type initializer:

    Paperclip.options[:content_type_mappings] = {r: "text/plain"}
    

    And this in the model:

    class RFile < ActiveRecord::Base
      has_attached_file :r, url: "/system/:attachment/:id/:basename.:extension"
      validates_attachment_file_name :r, matches: [/r\Z/, /R\Z/]
      do_not_validate_attachment_file_type :r
    end