domingo, 28 de julho de 2013

Mudar folder (ou diretório ou pasta) das imagens da gem CKEditor com Paperclip usando Rails 3.2

Opa!

Por esses dias precisei alterar em uma aplicação Rails 3.2.12, usando as gems CKEditor e Paperclip, a localização do diretório onde as imagens inseridas pelo CKEditor são guardadas. Depois de alguma pesquisa na internet, verifiquei que era necessário alterar os modelos attachment_file.rb e picture.rb do CKEditor, que ficam localizados na pasta app/models/ckeditor, alterando as seguintes linhas:



has_attached_file :data,
      :url  => "/ckeditor_assets/pictures/:id/:style_:basename.:extension",
      :path => ":rails_root/public/ckeditor_assets/pictures/:id/:style_:basename.:extension",
      :styles => { :content => '600>', :thumb => '118x100#' }


Para a localização que eu queria (no caso a pasta system em public por causa do capistrano):

has_attached_file :data,
      :url  => "/system/ckeditor_assets/pictures/:id/:style_:basename.:extension",
      :path => ":rails_root/public/system/ckeditor_assets/pictures/:id/:style_:basename.:extension",
      :styles => { :content => '600>', :thumb => '118x100#' }

Notar que é possível configurar aí o aparecimento do caminho absoluto no link da imagem. É só completar no parâmetro URL do modelo.

Após isso, só faltou configurar o CKEditor para que não aparecesse tantas opções de plugins, o que é facilmente resolvido ao criar e configurar o arquivo app/assets/javascript/ckeditor/config.js  Contudo, notei que ao colocar o arquivo config.js onde é indicado, mesmo que este esteja vazio, o Uploader que vem configurado com o CKEditor deixa de funcionar. 

Novamente saí catando algo na internet e achei um work-around na própria lista de issues da gem CKEditor. O arquivo config.js necessário para resolver esse problema deve ficar assim (notar que a solução não é minha, mas foi compartilhada nessa issue):

/*
 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
 For licensing, see LICENSE.html or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function( config )
{
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';

    /* Filebrowser routes */
    // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
    config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

    // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
    config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

    // The location of a script that handles file uploads in the Flash dialog.
    config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

    // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
    config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

    // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
    config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

    // The location of a script that handles file uploads in the Image dialog.
    config.filebrowserImageUploadUrl = "/ckeditor/pictures";

    // The location of a script that handles file uploads.
    config.filebrowserUploadUrl = "/ckeditor/attachment_files";

    // Rails CSRF token
    config.filebrowserParams = function(){
        var csrf_token, csrf_param, meta,
            metas = document.getElementsByTagName('meta'),
            params = new Object();

        for ( var i = 0 ; i < metas.length ; i++ ){
            meta = metas[i];

            switch(meta.name) {
                case "csrf-token":
                    csrf_token = meta.content;
                    break;
                case "csrf-param":
                    csrf_param = meta.content;
                    break;
                default:
                    continue;
            }
        }

        if (csrf_param !== undefined && csrf_token !== undefined) {
            params[csrf_param] = csrf_token;
        }

        return params;
    };

    config.addQueryString = function( url, params ){
        var queryString = [];

        if ( !params ) {
            return url;
        } else {
            for ( var i in params )
                queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
        }

        return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
    };

    // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
    CKEDITOR.on( 'dialogDefinition', function( ev ){
        // Take the dialog name and its definition from the event data.
        var dialogName = ev.data.name;
        var dialogDefinition = ev.data.definition;
        var content, upload;

        if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
            content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
            upload = (content == null ? null : content.get('upload'));

            if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
                upload.filebrowser['params'] = config.filebrowserParams();
                upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
            }
        }
    });
};

É só.

Fontes:
  • https://github.com/galetahub/ckeditor/issues/238
  • http://stackoverflow.com/questions/3647905/how-exactly-do-you-integrate-ckeditor-with-paperclip-so-it-can-upload-image-file





Nenhum comentário:

Postar um comentário