2010-04-05 2 views
6

나는 닭고기와 계란에 문제가 있다고 생각합니다. Paperclip을 통해 업로드 한 파일의 content_type을 설정하고 싶습니다. 문제는 기본 content_type은 확장명을 기반으로하지만 다른 모듈을 기반으로하고 싶습니다.레일즈 용 content_type 덮어 쓰기 클립 클립

은 내가 before_post_process

class Upload < ActiveRecord::Base 
    has_attached_file :upload 
    before_post_process :foo 

    def foo 
    logger.debug "Changing content_type" 

    #This works 
    self.upload.instance_write(:content_type,"foobar") 

    # This fails because the file does not actually exist yet 
    self.upload.instance_write(:content_type,file_type(self.upload.path) 
    end 

    # Returns the filetype based on file command (assume it works) 
    def file_type(path) 
    return `file -ib '#{path}'`.split(/;/)[0] 
    end 
end 

과 콘텐츠 _를 설정할 수있을 것 그러나 종이 클립이 after_create 때까지 파일을 작성하지 않기 때문에 ... 나는 파일의 내용 유형을 기반으로 할 수 없다.

그리고 그것은 (컨트롤러에서도 다시) 저장하거나 after_create 콜백 후 나는 어떻게 든 실제 파일 개체에 대한 액세스를 얻을 수 있다면

그래서 내가 알고 싶은 콘텐츠 _를 설정할 수없는 것 (원래 파일에 아무 것도하지 않는 프로세서가 없다고 가정하여) 저장하기 전에 file_type 명령을 실행할 수 있습니다. 또는 객체가 생성 된 후에 content_type을 수정하는 방법이 있습니다.

답변

4

아마 upload.to_file을 사용할 수 있습니다. 클립 클립 임시 파일 (Paperclip::Tempfile)을 제공합니다. 당신이

self.upload.instance_write(:content_type,file_type(self.upload.to_file.path) 

을 사용할 수 있도록 당신은 내가 필요 정확히이었다 임시 파일에 도착 upload.to_file.to_tempfile

+1

사용 Tempfile를 얻을 수 path 속성이 있습니다. 나는 또한 before_post_process에서 before_save로 변경했다. – Fotios