JavaScript and Ruby in HAML

What I’m trying to do:

For every view file (e.g. new.html.haml), include a file with this
pattern: <action_name>.js. So, in the example of new.html.haml, I’d
like to automatically try to include the file new.js.

Further, I’d like to be able to evaluate Ruby code in the JS. A silly
example:

alert( #{ user.name } );

I’ve tried a few things. At this point, it seems like maybe creating a
partial is the easiest, but I wonder if there’s a cleaner way someone
can think of?

Molto grati

On Oct 9, 2011, at 9:38 PM, heisenberg wrote:

I’ve tried a few things. At this point, it seems like maybe creating a
partial is the easiest, but I wonder if there’s a cleaner way someone
can think of?

<%= content_for( :head, javascript_include_tag( “#{action_name}.js” ) )
%>

Even better, bundle that into a helper, and add some conditional logic
so it still works if that file doesn’t exist.

As for evaluating Ruby within js, you will need to make your .js file
.js.erb, but I’m not sure what environment and variables will be ready
for it when it’s loaded into your page. I presume you’ve read about rjs,
and you don’t want that?

Walter

Yikes, noob alert! I haven’t read about rjs. Let me do that before I
trouble you any further. Thanks much, Walter.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs