1

My scenario is that, some user who has the font_user role can use font, but others can't.

In ckeditor/config.js, I can't get any variable from Rails. How do I achieve this?

I have tried something like this:

  1. Modify config.js to config.js.erb.
  2. Add the following code.

    <% current_user.has_role?(font_user) %>
      XXXXX
    <% else %>
      XXXX
    <% end %>
    

    and I added the following method in application_controller.rb:

    helper_method :current_user
    

    But it seems config.js.erb can't get the current_user variable.

sawa
  • 165,429
  • 45
  • 277
  • 381
rj487
  • 4,476
  • 6
  • 47
  • 88
  • Please have a look [link](https://stackoverflow.com/questions/7451517/using-a-rails-helper-method-within-a-javascript-asset) – Vivek Singh May 11 '18 at 08:16

1 Answers1

1

This is because asset JavaScript is compiled ones. Not each time a view is rendered. You should make use of unobstructive JavaScript. For example:

View example:

<div class="ckeditor" data-ckeditor-font="<%= current_user.has_role?(font_user) %>"></div>

Alternatively (not checked):

You could also use the #content_tag for this, although you have to check how to exactly pass along the data attributes. If I'm not mistaken:

<% data = {
  'ckeditor-font': current_user.has_role?(font_user),
  # other data...
} %>

<%= content_tag :div, class: 'ckeditor', data: data %>

But I currently don't have the setup to test the above code. So you'll have to check it yourself.


Than in your asset JavaScript (CoffeeScript):

initCkeditor = (element) ->
  fontUser = element.dataset.ckeditorFont == 'true'

  # further CKEditor initialization code...


document.addEventListener 'turbolinks:load', ->
  document
    .querySelectorAll '.ckeditor'
    .forEach initCkeditor

If you don't set the data-ckeditor-font attribute the code still works. Since element.dataset.ckeditorFont would return undefined, and undefined == 'true' is still false. (Keep in mind that the CoffeeScript == equals JavaScript ===.)

See:

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • My question is that I can't get the current_user variable from the backend. – rj487 May 11 '18 at 09:18
  • You can pass it along the same way. Just create an attribute `data-ckeditor-current-user-id`. The question is what are you going to do with the `id` when you have it there? The better option is to set CKEditor options in the view by passing along via the data attributes. Thus having something like `
    ` in your view.
    – 3limin4t0r May 11 '18 at 09:32
  • Thanks, I understand what you mean now. I will try this way. – rj487 May 11 '18 at 10:08