Michał Darda Michał Darda - 7 months ago 18
Ruby Question

Emacs and embedded ruby <% %> tags

I'm looking for a way to quickly put <% %> tags on the marked region.
I'm using rinari with rhtml-mode. I want to do such a thing (I'm in rhtml-mode):

I've got a ruby code for example

a.each do |e|
puts e
end


and I'm selecting it with select-region, put some magic key and I've got:

<% a.each do |e| %>
<%= puts e %>
<% end %>


I require it should do it smart, for instance if I selected ruby code with some HTML tags mixed in, it should apply <% %> only to ruby code, leaving the rest unharmed. Also, if I select nothing, it should put <% %> with point just in the middle, waiting for my input. I'm wondering is something like that exist as a emacs function or package maybe?

I was trying to do it, as a snippet for YAsnippet mod, but it is far from what I like it to be.

Answer

In case you use OS which has built-in GNU Awk you could use that simple one-ungly-line script:

(defun make-it-erb (begin end)
    "Add <%=? %> for each string"
    (interactive "r")
    (shell-command-on-region begin end "gawk '/^[ \t]*(puts)|(print)/{ printf \"<%=\" $0 \"%>\"; next } // { printf \"<%\" $0 \"%>\" } '" nil ""))
  (global-set-key [f7] 'make-it-erb)

You should add it in your .emacs file and evaluate functions above.

Comments