Accessing Rails variable in CoffeeScript - ruby-on-rails

I want to use the current user's through my coffee script. But if I try to use current_user in my CoffeeScript, I get the undefined variable current_user in console of browser.
Is there any way to access it in coffee script? What I exactly wish to do is as follows:
current_user.updated_at < Date.now().getTime()
I need it to implement this in my Rails app.

For raw javascript + erb
<script type="text/javascript">
var my_foo = <%= some_ruby_expression %>
</script>
e.g.
<script type="text/javascript">
var user_name = "<%= current_user.name %>";
</script>
except var keyword, this is a valid coffeescript code, I believe.
Btw, is it really what you are asking for? - I don't know -))
UPDATE
current_user is a ruby/active_record object. You might assign it to a javascript variable, but can't use as you did in ruby.
But below snippet might give you some idea. I've created a rails project, and scaffolded a page model.
<p id="notice"><%= notice %></p>
<p>
<strong>Title:</strong>
<%= #page.title %>
</p>
<p>
<strong>Email:</strong>
<%= #page.email %>
</p>
<p>
<strong>Comments:</strong>
<%= #page.comments %>
</p>
<script type="text/javascript">
var mypage = '<%= raw #page.to_json %>'; // attention to single quotes
console.log(mypage);
</script>
<%= link_to 'Edit', edit_page_path(#page) %> |
<%= link_to 'Back', pages_path %>
Then you can parse and use it as an ordinary javascript object. Below picture show, how I did it.
UPDATE #2
do it in coffeescript file.
window.onload = ->
myvar = '<%= raw #page.to_json %>'
myvarAsObj = JSON.parse(myvar)
do_something_with myvarAsObj
return

Coffee script is turned into javascript and runs on the browser. What you want to do is render current_user.updated_at into a node in HTML, then use coffee script to extract that value.

Javascript files are (more or less) static files which will be executed by the browser. I don't know if you ever deployed an rails app in production. You'll run the command bin/rake assets:precompile which will generate one (or more) massive javascript file(s). So how would you find out the current user at this time? there's no HTTP request at all, so how could there be a user?
So to do this, you could either write the current user to a HTML node and then read it again with javascript (coffeescript) (which in my opinion is the best way) or you could print a script tag into your view containing what you want from your user.

Related

Use template from DB in usermailer and interpret ruby code inside the string?

Ok so this one is hurting my brain:
I have something like this in send_invoice_html.erb which is one of my user_mailer views:
<% if #cust_inv_template %>
<%=raw #cust_inv_template.cust_mail_invoice_template%>
<%else%>
So I have the user setup their email template inside another view, save that to the database, and then I want to say "if there is a template, use that, else, use my default".
Inside my template is some HTML and some Rails code:
<html>
Aloha <%= #user.first_name %>,<br />
<p>Please find attached your invoice for Job #<%= #job.job_number %> which we completed on <% ed = Date.parse(#job.end_date.to_s);
endDate = Date.strptime(ed.to_s, "%m-%d-%Y") %><%= endDate.to_s %>.</p>
<p>If you have any questions, please call us at <%= number_to_phone(#admin.phone_number) %> or email us at <%= #admin.email %></p>
<br />Thanks,
<br/><%= #admin.name %>
</html>
So when the message gets sent to my mailbox (Gmail) - I see :
Aloha <%= #user.first_name %>,
Please find attached your invoice for Job #<%= #job.job_number %> which we completed on <% ed = Date.parse(#job.end_date.to_s); endDate = Date.strptime(ed.to_s, "%m-%d-%Y") %><%= endDate.to_s %>.
If you have any questions, please call us at <%= number_to_phone(#admin.phone_number) %> or email us at <%= #admin.email %>
TEST TEST TEST TEST TEST
Thanks,
<%= #admin.name %>
Ergo - my HTML is being respected just fine with the <%=raw part (I tried html_safe previously) - but the Rails code is being spit out as-is. I want that Rails-y goodness to be interpreted BEFORE the message is sent.
When I take out the if else stuff and just use the exact same template the Rails code IS respected.
Which means there has to be some kind of "spit out what's inside this string var AND if there's any cool rails stuff in there go ahead and interpret that" method in some class :)
Anyone know what that is?
raw is about not escaping the HTML, but it will not interpret your ruby code. To interpret your ruby code you need to use evaluate the erb template.
<%=raw Erb.new(#cust_inv_template.cust_mail_invoice_template).result %>
Check the docs for more info.

why does the script affect everything on my Rails 3 app even when cased in this code?

I have a third party script which is
<script type="text/javascript" src="http://thirdpartysite.com/front.asp?id=xxxx"></script>
What the script does is put a watermark on an image to show that it is copyrighted.
This is the code that I'm using in view, but no matter what, the script applies to all posts
<% if post.copyright == true %>
<script type="text/javascript" src="http://thirdpartysite.com/front.asp?id=xxxx"></script>
<% else %>
<% end %>
When I test it using text only, it works correctly
<% if post.copyright == true %>
Sample text here only applies to post where copyright==true
<% else %>
<% end %>
How can I get the script to only apply to certain posts?
After your clarified in a comment
Yeah, including javascript will apply pagewide if nothing else is specified in the javascript.
You need to do something like:
<div class="post <%= 'copyright' if post.copyright%>">
<img src="somesrc.jpg"></img>
</div>
and then apply the javascript only to the css selector 'div.copyright img'. Something along the lines of that. Depends on what the javascript supports or if you can change the source.

Classic ASP Redirect URL using variable

I have a variable tag <%test_variable%> that was from a resultset.
I want to use this <%=test_variable%> to redirect to a link, say
http://www.helloworld.someurl.com/testUrl?somevariable=<%=test_variable%>&test=ok
How can I do this in the <% %> tag? For example,
<%=test_variable%>
<%
' I want to redirect the url with the above tag, something like:
Response.Redirect(" http://www.helloworld.someurl.com/testUrl?somevariable=<%=test_variable%>&test=ok")
%>
But I don't think we can have "nested tags", right?
I'm pretty new to ASP.
<%= %> is shorthand for <% Response.Write(" ... "); %>:
http://www.helloworld.someurl.com/testUrl?somevariable=<%=test_variable%>&test=ok
After your clarification:
<%
Response.Redirect("http://www.helloworld.someurl.com/testUrl?somevariable="
+ test_variable
+ "&test=ok");
%>
Your code should be
Response.Redirect("http://www.helloworld.someurl.com/testUrl?somevariable=" & test_variable & "&test=ok")
Thanks all for your suggestions...
I've decided to use this instead:
<script type="text/javascript">
window.location = "http://www.helloworld.someurl.com/testUrl?somevariable="+<%=test_variable%>+"&test=ok"
</script>

Javascript yield in application.html.erb, unable to make it work. Ruby on Rails?

I have this statement in application.html.erb:
<%= yield(:javascript) %>
and I have the following Javascript, which should respond to the yield:
<% content_for : javascript do %>
<script type="type/javascript">
$(function() {
call_to_function();
});
</script>
<% end %>
If I place the above block in home/index.html.erb, it works alright, but I want to somehow make it available to application.html.erb all the time, not just when I call home#index.
How can I achieve this, any pointers would be much appreciated?
Instead of using
<%= yield(:javascript) %>
you can directly put your java script to application.html.erb in app/views/layout to share code throw out all the pages.
There is no need to use yield when you have same contents through out. Yield is used when we have code specific to each page is different, from each page we call yield to actually replace the content of yield block.
So, replace <%= yield(:javascript) %> by
<script type="type/javascript">
$(function() {
call_to_function();
});
to appear in all your pages.

Rails 3 UJS driver events

According to Simone Carletti blog post, Rails 3 ajax helpers have changed a lot. We are supposed to write more javascript with rails 3 than we used to with rails 2.
I tried to figure out how to show up an ajax loading gif -while an ajax query is running- in the "rails 3 way". I came up with this kind of code, which uses javascript events sent by the Rails 3 UJS driver. This example uses prototype:
<div id="wait" style="display:none">
<img src="/images/ajax-loader.gif"> Please wait...
</div>
<div>
<%= link_to 'Get', 'finished', :id => "mylink", :remote => true %>
</div>
<%= javascript_tag do %>
Event.observe('mylink', 'ajax:before', function(event) {
$('wait').show();
});
Event.observe('mylink', 'ajax:complete', function(event) {
$('wait').hide();
});
<% end %>
This works well, but I wish it was possible to write these ajax events "triggers" with the help of the prototype and scriptaculous helpers, just like when we use link_to_function for example:
<%=
link_to_function("toggle visibility") do |page|
page.toggle "wait"
end
%>
Is there a way to do that, or are we supposed to write ajax events "triggers" in javascript directly, either prototype or jquery?
Best regards,
Philippe Lang
The idea of UJS is to move the javascript code out of the views into separate js files. The way you're doing it is defeating that goal. Instead, I believe you should have a js file with a "dom:loaded" or similar handler that sets up handlers for rails callbacks and other events.
Something like (using prototype):
(function () {
$(document).on('dom:loaded', function (event) {
$$('a[data-remote=true]').each(function (link) {
link.on('ajax:complete', function (request) {
// do something
});
});
});
}());
This way all javascripts are separated from the view, which is the idea of unobtrusive javascript.
After looking at rails source code, I came up with this solution:
def javascript_event_tag(name, event, &block)
content = "Event.observe('#{name}', '#{event}', function() {"
content = content + update_page(&block)
content = content + "});"
content_tag(:script, javascript_cdata_section(content))
end
This makes it easier to react to UJS events:
<div id="wait" style="display:none">
<img src="/images/ajax-loader.gif"> Please wait...
</div>
<%= link_to 'ajax call', 'code_on_controller', :id => "mylink", :remote => true %>
<%=
javascript_event_tag('mylink', 'ajax:before') do |page|
page.show 'wait'
end
%>
<%=
javascript_event_tag('mylink', 'ajax:complete') do |page|
page.hide 'wait'
end
%>
Instead of having to write raw prototype or jquery code, you can use rails helpers.

Resources