I'm defining an intercom event in my rails controller like so:
object_controller.rb
@object.save
@intercom_event = 'object-saved'
In a partial that exists in my application.html.erb I am trying to run this script:
<script>
Intercom('trackEvent', '<%= @intercom_event %>');
</script>
The script runs and sends the event up to Intercom like its supposed to. I thought I am placing the ruby variable into the <script> tag correctly except the output for @intercom_event is: <%= @intercom_event %> when it should be: object-saved.
Additionally if I were to wrap this <script> tag in an if statement (so that it doesn't send an event every time the page is reloaded) like so:
<% if @intercom_event.present? %>
<script>
Intercom('trackEvent', '<%= @intercom_event %>');
</script>
<% end %>
It ignores the script altogether, even when @intercom_event is defined.
2 Answers 2
Got it to work by looking to see if the params is present instead of the @intercom_event variable
<% if params[:intercom].present? %>
<script>
Intercom('trackEvent', '<%= params[:intercom] %>');
</script>
<% end %>
Comments
You're on the right track:
<%- if @intercom_event.present? -%>
<%= javscript_tag do -%>
Intercom('trackEvent', '<%=j @intercom_event %>');
<%- end -%>
<%- end -%>
The j method escapes for JavaScript context like the companion method h escapes for HTML. This is important to avoid scripting errors.
For more complicated structures, @intercom_event.to_json would give you a JavaScript compatible representation.
2 Comments
<%- if @intercom_event.present? -%> tag. When I removed the if statement it's now sending nothing up to intercom. I wonder why the variable defined in the controller isn't being seen in the view filelog/development.log.