spohlenz / tinymce-rails

Integration of TinyMCE with the Rails asset pipeline
Other
813 stars 256 forks source link

Asset pipeline support for tinymce content_css option #227

Closed juliendargelos closed 6 years ago

juliendargelos commented 6 years ago

The configuration class got an OPTION_TRANSFORMERS constant which purpose is to transform options when calling options_for_tinymce.

The content_css transformer splits the value with commas (TinyMCE content_css), then for each file, it looks for an existing stylesheet in the asset pipeline. If such stylesheet exists, it replace the path with the corresponding path generated by the asset pipeline, if not, the path remains unchanged. The value is then joined again with commas.

With this feature, we are able to do things like this:

# config/tinymce.yml
content_css: reset.css, application.css

And then get a configuration like this:

<script>
  // Using the tinymce_configuration helper
  var tinymceOptions = {
    content_css: '/assets/reset.self-b7133ed7c815140f95153cf7e6986f33fdb2e8235138031a856bc8a6d7f31193.css?body=1,/assets/application.self-c1c3ac386bde898b4c2c58fcd54fce97ab512972ba5fe65b5d87342e50dd6dd7.css?body=1'
  }
</script>

Option transformers:

OPTION_TRANSFORMERS = {
  # Check for files provided in the content_css option to replace them with their actual path.
  # If no corresponding stylesheet is found for a file, it will remain unchanged.
  "content_css" => -> (value) {
    value.split(OPTION_SEPARATORS["content_css"]).map do |file|
      ActionController::Base.helpers.stylesheet_path(file.strip) || file
    end.join(OPTION_SEPARATORS["content_css"])
  }
}

options_for_tinymce method:

def options_for_tinymce
  result = {}

  options.each do |key, value|
    if OPTION_SEPARATORS[key] && value.is_a?(Array)
      result[key] = value.join(OPTION_SEPARATORS[key])
    elsif value.to_s.starts_with?("function(")
      result[key] = Function.new(value)
    else
      result[key] = value
    end

    if OPTION_TRANSFORMERS[key]
      result[key] = OPTION_TRANSFORMERS[key].call result[key]
    end
  end

  result
end
spohlenz commented 6 years ago

This is great, thanks! I've rebased and added a couple of specs.