Difference Between "<%=" and "<%" When Mixing Ruby with HTML

Is it correct to have files that mix Javascript and ruby? ie. (.js.erb)?

RJS templates were essentially the way things were done for a long time, which is why you still see such a prevalence of the technique in tutorials. That being said, as you've noticed, they're on the way out, and with good reason.

I'm sure there are many reasons why RJS templates are a very bad thing, but a big one is how tightly they couple your view JS to your view HTML. Many problems arise from this, a few being:

  1. Lack of flexibility.

    Using your bit of code as an example. What if you wanted to be able to create posts from a different view? And have a different effect? Maybe there's no <table> on the page at all and you just want to pop up a "success" message? Etc.

    What if you just wanted a data representation of your posts, but your javascript templates were written to manipulate HTML?

    How do you handle all this in one create.js.erb, which is tightly coupled to, most likely, the posts new.html.erb template?

  2. Complexity.

    RJS templates operate in somewhat of a vacuum. Generated on server side, their execution is not bound to DOM events. This makes it tricky to do things like, say, update a <form> on a page after an object is being created, as you have no frame of reference to select the appropriate <form> in the JS template (e.g. <form id="new_post_123">). There are workarounds for this, but they're more convoluted than they need to be.

    By binding to a form client-side and dealing with the result, this problem is eliminated. You don't need to find the proper form to update after a response.

    With RJS you have no such binding, and you're forced to use the known structure of the HTML to retrieve and manipulate the appropraite elements. One example of unnecessary complexity.



Regarding your question:

I really need to be enlightened on this, and maybe get the concepts right because I have read that rails 3.1 will separate JS from Ruby completely through assets ?(Is this correct?)

This is essentially true. The asset pipeline, while cool, doesn't offer anything brand new. Asset frameworks like Sprockets and Sass, and the workflows they enable, have been around for a while. The Rails 3.1 asset pipeline just brings them into standard practice. It's more a matter of perspective, as DHH talked about in his recent RailsConf keynote. By bringing greater organization to these assets, js files in particular, it makes them feel more like first-class citizens, so to speak, deserving of as much attention as your back-end code. As opposed to the "junk drawer" feel of public/javascripts.



As for the implementation:

You might do it something like this (although untested and a bit simplified, e.g. in Rails 3 you might use responders for this rather than a respond_to block:

# as you have, but returning the object as data which can be handled client-side,
# rather than RJS generated by the server
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.js { render :json => @post }
else
# ...
end
end
end

// Then in your client side JS, a handler for your remote form.
$(function(){
$('#your-create-form').bind('ajax:success', function(data, status, xhr) {
// simply repeating what you had in the template, replacing the erb with
// attributes from the returned json
$tr = $('<tr>');
$td1 = $('<td>').text(data.title);
$td2 = $('<td>').text(data.content);
$tr.append($td1, $td2);
$('table tbody').append($tr);
});
}

Mix HTML and non-HTML strings in Rails ERB

Short of just writing the HTML entities themselves using < and >, thus avoiding Rails from having to do the work:

<%= ('Here is an example of sample code you can write in the text-area:<br>' + 
h('<br>') + '<br>' +
h('<p>Hello, dear Mr. X, new announcement</p>')+'<br>' +
h('<h2>The project</h2>') + ...).html_safe %>

This uses the html_escape helper to turn the HTML you want to render into the entities, and then you can call html_safe on the entire resulting string to avoid the problems you'd normally run into with the HTMLSafe buffer.

I'd probably clean it up by just avoiding html_safe altogether and using the built-in escaping that Rails does:

Here is an example of sample code you can write in the text-area:<br>
<%= '<br>' %><br>
<%= '<p>Hello, dear Mr. X, new announcement</p>' %><br>
<%= '<h2>The project</h2>' %>

The latter approach is much cleaner.

Help with HAML: Mixing text and other HTML tags

There's no reason you shouldn't use inline HTML tags in your Haml document. See this post explaining why Haml isn't good for inline markup.

<p>
Welcome to <span>#{name1}</span>, <span>#{name2}</span> and <span>#{name3}</span>.
</p>

When to mix languages?

Well, the most obvious (and the most common) situation would be when you use some high level language to make most of your program, reaping the benefits of fast development and robustness, while using some lower level language like C or even assembly to gain speed where it is important.

Also, many times it is necessary to interface with other software written in some other language. A good example here are APIs exposed by the operating system - they're usually written with C in mind (though I remember some old MacOS versions using Pascal). If you don't have a native binding for your language-compiler infrastructure, you have to write some interface code to "glue" your program with "the other side".

There are also some domain-specific languages that are tuned specifically to efficiently express some type of computation. You usually don't write your entire program in them, just some parts where it is the appropriate tool. Prolog is a good example.

Last but not least, you sometimes have heaps of old and tested code written in another language at hand, which you could benefit from using. Instead of reinventing the wheel in a new and better language, you may simply want to interface it to your new program. This is probably the most usual (if not the only) case when languages geared for similar uses are mixed together (was that C++ and Fortran you mentioned?).

Generally, different languages have different strengths and weaknesses. You should try to use the appropriate tool for the job at hand. If the benefits from expressing some parts of the program in a different language are greater than the problems this introduces, then it's best to go for it.

Mixing Ruby code and literal markup with Haml

=some_ruby_code + ":"
-# and
=some_ruby_code + "<br/>"

EDIT 1:

I'm not sure exactly what you are looking for. Would you like one of these?

==#{some_ruby_code}:
-# and
==#{some_ruby_code}<br/>

or

==#{some_ruby_code}:
-# and
=some_ruby_code
%br

There is no way to use %br in HAML unless it is the first non-whitespace thing on the line, as far as I know.

Is there any way to mix plain text and HTML email on Rails?

No, you can't mix the two of them in one file. Rails will render both the .text and .html variants of the template separately and then deliver them together in a multipart email. Clients capable of display HTML emails will see the HTML variant, while clients only capable of text will get the text.

You can provide only or the other template if desired, but if you use only text, then you can't use HTML (obviously), and if you use only HTML then clients incapable of HTML display will display the HTML source code as the message, making it effectively unreadable. If your email is simple and there is no need for markup, then you can provide just a .text template and everything should work acceptably well.

How can I mix inline ruby code with my client side RJS?

puts "*"*100 is always printed because during the processing of your js.erb file, all Ruby code inside the file is executed.

The JavaScript code is only executed when it runs in your browser, so the if (false) statement has no effect during the ERB processing of the file.

So, this has nothing to do with the PrivatePub gem, but it is because you are mixing JS and Ruby code.

For your last (chat) code example, try render_to_string, but perhaps that's not enough because the @messages variable is empty during the compilation of the JS file.

I would like to add that mixing JS and Ruby can lead to some headaches. Sometimes it's better to set data-attributes on your HTML elements with Ruby/ERB in your view file, and then let the JS code read and use the value of those data-attributes. That way you don't have to use Ruby code inside your JS code.

mixing file.write and system calls that write to same file

to answer my own question:

File.open('test.txt', 'w') {|f|
`echo 11 > #{f.path}`
f.seek(0, IO::SEEK_END)
f.write "2\n"
f.flush
`echo 33 >> #{f.path}`
}

What are situations with western languages where you'd use HTML 5's Ruby element?

As a linguist, I can see the benefits in using <ruby> for marking up linguistic examples with various theoretical notational conventions. One example that comes to mind is indicating tonal levels in autosegmental phonology. Here's a quick example I threw together that can be seen in the latest Webkit/Chromium (at least):

http://miketaylr.com/code/western_ruby.html

Currently, this type of notation is left for LaTex and friends, and if on the web, generally a non-accessible image.



Related Topics



Leave a reply



Submit