tinymce-rails

repository·main·Indexed 21 days ago

https://github.com/spohlenz/tinymce-rails

A Rails integration for the TinyMCE rich text editor (compatible with Rails 5.1+) providing tools for asset management, language packs, and configuration via config/tinymce.yml. This version supports TinyMCE 8 and includes helpers for initializing editors in views, managing asset installation methods (:compile, :copy, :copy_no_preserve), and resolving asset paths for Sprockets or Propshaft.

Tokens
3.1K
Snippets
12
Records
15
Agent score
73%

What's inside tinymce-rails

  1. Include TinyMCE assets

    main

    You can include TinyMCE assets using one of the following two methods depending on your asset pipeline:

    Option 1: Sprockets (application.js)

    Add the following line to your application.js:

    //= require tinymce

    Option 2: Layout Helper (Sprockets or Propshaft)

    Add the tinymce_assets helper to your layout file:

    <%= tinymce_assets data: { turbo_track: "reload" } %>

    Note for Propshaft users: The tinymce_assets helper adds multiple script tags, including pre-init code (via tinymce_preinit helper), tinymce/tinymce.js, and tinymce/rails.js. You may choose to include these manually if you have specific requirements.

  2. Add custom TinyMCE plugins and skins

    main

    To use custom plugins or skins, place your files in the asset load path such that they are located under tinymce/plugins/ or tinymce/skins/.

    Example Directory Structure: If you have a plugin named mycustomplugin, place its main JS file at: app/assets/javascripts/tinymce/plugins/mycustomplugin/plugin.js

    Requirement: Ensure your custom asset paths are included in the asset precompile paths.

  3. Install tinymce-rails

    main

    To integrate TinyMCE with your Rails application, follow these steps:

    1. Add the gem to your Gemfile in the global group (do not put it in the assets group):
      gem 'tinymce-rails'
    2. Run bundle install.

    This gem is compatible with Rails 5.1 and higher. Note that this branch is for TinyMCE 8, which is licensed under the GPL and requires a license key.

    gem 'tinymce-rails'
  4. Configure TinyMCE via config/tinymce.yml

    main

    Create a config/tinymce.yml file to define global configuration options. This file supports YAML anchors for defining multiple configuration sets. The Rails server does not need to be restarted when this file is updated in development mode.

    Important: As of TinyMCE 8, a license_key must be specified.

    Example Configuration

    license_key: gpl
    toolbar:
      - styleselect | bold italic | undo redo
      - image | link
    plugins:
      - image
      - link

    Defining Multiple Configurations

    You can use YAML anchors to define a default set and then create alternate configurations that inherit from it:

    default: &default
      license_key: gpl
      plugins:
        - image
        - link
    
    alternate:
      <<: *default
      toolbar: styleselect | bold italic | undo redo | table
      plugins:
        - table
  5. Configure TinyMCE options for Rails

    main

    The TinyMCE::Rails::Configuration class manages the conversion of Ruby configuration hashes into a JavaScript object format compatible with tinymce.init().

    Default Options

    By default, the configuration includes:

    • selector: "textarea.tinymce"
    • cache_suffix: A versioned string used for cache busting.

    Key Features

    • Array Joining: Arrays passed in the configuration are automatically joined into strings using specific separators required by TinyMCE (e.g., plugins uses commas, while font_formats uses semicolons).
    • Function Support: Strings that match JavaScript function patterns (e.g., function(arg) { ... } or arrow functions) are treated as Function objects to ensure they are passed correctly to the JavaScript runtime.
    • Asset Path Resolution: The content_css option automatically attempts to resolve relative file paths to their actual Rails stylesheet paths using stylesheet_path.
    # Example of how configuration is structured conceptually
    # (Note: Actual usage typically happens via the gem's helper methods)
    config = TinyMCE::Rails::Configuration.new_with_defaults({
      "plugins" => ["advlist", "autolink", "lists"],
      "content_css" => ["application.css"],
      "toolbar" => "undo redo | styleselect | bold italic"
    })
    
    # The resulting JavaScript string for tinymce.init() would look like:
    # {
    #   'plugins': 'advlist,autolink,lists',
    #   'content_css': '/assets/application-hash.css',
    #   'toolbar': 'undo redo | styleselect | bold italic'
    # }
  6. Configure TinyMCE asset installation method

    main

    Because TinyMCE loads files dynamically, it requires specific handling during rake asset:precompile. You can control the installation method by setting config.tinymce.install in config/application.rb.

    Available Methods

    • :compile (Default): Adds TinyMCE paths to Sprockets precompilation paths and creates symlinks from non-digested filenames to digested versions.
    • :copy: Copies TinyMCE assets directly into public/assets and appends the file information into the asset manifest.
    • :copy_no_preserve: Similar to :copy, but does not attempt to preserve file modes.

    Usage

    # In config/application.rb
    config.tinymce.install = :copy
    config.tinymce.install = :copy
  7. How TinyMCE asset paths are resolved

    main

    The engine provides helper methods to determine the base URL for TinyMCE assets. This is used to ensure assets are loaded correctly regardless of whether you are using a CDN, a specific asset host, or a relative URL root.

    • Base Path: The engine calculates the base path using Rails.application.config.assets.prefix and the relative_url_root.
    • Asset Host: The engine respects config.action_controller.asset_host.
      • If the host is a callable object, it returns nil (as callables cannot be used during precompilation without a request object).
      • If the host contains a placeholder like %d, it uses the first host (host % 0).
      • If the host does not include a protocol (e.g., cdn.example.com), it is normalized to a protocol-relative URL (//cdn.example.com).
  8. Manually initialize TinyMCE

    main

    If you prefer not to use the tinymce helper or the global configuration file, you can initialize TinyMCE manually using standard JavaScript:

    <%= text_area_tag :editor, "", rows: 40, cols: 120 %>
    
    <script type="text/javascript">
      tinymce.init({
        selector: 'textarea.editor'
      });
    </script>
  9. Initialize TinyMCE in views

    main

    To use TinyMCE, follow these steps:

    1. Add the CSS class: Add the tinymce class to your textarea and ensure it has a unique ID.

      <%= text_area_tag :content, "", class: "tinymce", rows: 40, cols: 120 %>
      # OR using form builders
      <%= f.text_area :content, class: "tinymce", rows: 40, cols: 120 %>
    2. Invoke the helper: Call the tinymce helper to initialize the editors on the page.

      <%= tinymce %>

    Overriding Configuration

    You can pass custom options to the tinymce helper to override config/tinymce.yml:

    <%= tinymce theme: "simple", language: "de", plugins: ["wordcount", "paste"] %>

    To use a specific configuration set defined in config/tinymce.yml:

    <%= tinymce :alternate %>
  10. Configure TinyMCE::Rails engine settings

    main

    You can customize the behavior of the tinymce-rails engine by setting options on config.tinymce within your Rails configuration (e.g., in config/application.rb or an environment file).

    Available configuration keys:

    • config.tinymce.base: An explicit base path for TinyMCE assets. If unset, it defaults to a path constructed from the asset prefix and tinymce (e.g., /assets/tinymce).
    • config.tinymce.config_path: The path to your TinyMCE configuration file. If unset, it defaults to config/tinymce.yml in your Rails root.
    • config.tinymce.install: The method used to install TinyMCE assets. Options are:
      • :compile: Adds TinyMCE to the Sprockets load paths and creates non-digested symlinks to the digested versions. (Default)
      • :copy: Copies TinyMCE assets statically.
    • config.tinymce.default_script_attributes: A hash of attributes to be added to script source tags. Defaults to {"data-turbolinks-track" => "reload"}.
    # Example configuration in config/application.rb
    Rails.application.configure do
      config.tinymce.install = :copy
      config.tinymce.config_path = Rails.root.join('config', 'my_tinymce_config.yml')
      config.tinymce.base = '/custom/tinymce/path'
      config.tinymce.default_script_attributes = { 'data-turbo-track' => 'reload' }
    end
  11. Initialize TinyMCE in Rails views with `tinymce`

    main

    Use the tinymce helper to generate the JavaScript required to initialize TinyMCE editors on the current page.

    By default, it targets all <textarea> elements with the class tinymce. It also automatically attempts to use the current Rails locale for the TinyMCE language, falling back to English if the language pack is unavailable.

    You can override the selector and other TinyMCE configuration options by passing them in the options hash.

    Key options:

    • selector: Overrides the default .tinymce class selector.
    • language: Overrides the default locale-based language.
    • Any other valid TinyMCE configuration key (e.g., theme, plugins, toolbar).
    <%= tinymce(selector: "editorClass", theme: "inlite") %>
  12. Retrieve TinyMCE configuration with `tinymce_configuration`

    main

    The tinymce_configuration helper returns a Ruby hash representing the TinyMCE configuration. It merges the global configuration (defined in tinymce.yml) with any local options provided.

    If your global configuration contains multiple named configurations, you can specify which one to fetch by passing the name as the config argument.

    <%= tinymce_configuration(:my_custom_config, { toolbar: 'undo redo' }) %>