1

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.

daremkd
8,4588 gold badges45 silver badges70 bronze badges
asked Sep 24, 2014 at 15:20

2 Answers 2

4

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 %>
answered Oct 22, 2014 at 19:52
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Sep 24, 2014 at 15:26

2 Comments

Hmm still not sending when wrapped in a <%- 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 file
Controller instance variables are automatically propagated down to the view level. Are you sure you're hitting the right action? Always check log/development.log.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.