Search code examples
javascriptruby-on-railsrubychessboard.js

Renaming my file to .js.erb allows me to write erb inside javascript but not javascript inside erb


I am using chessboard-0.3.0.js on a rails application. Because of the rails asset pipeline thing, I have had to edit every part of the js code that renders an image, Pieces for example. Line 445 of chessboard.js says

cfg.pieceTheme =  'img/chesspieces/wikipedia/{piece}.png'

which of course would pose a problem for rails, so I had renamed chessboard with the .erb extension and changed that line to

cfg.pieceTheme =  <%= asset_path('chesspieces/wikipedia/{piece}.png') %> 

after putting all the required images in the assets/images folder.

My problem here is that the images still does not get rendered, I guessed its because of the way {piece}.png is placed in that line, thats basically js inside a rails helper, right? And I think that is why my images do not get rendered. Of course, I could read the whole 'almost 2000' lines of code and try to figure out a way to access each images one after the other, but I could break something else along the way, 2k lines isn't fun to manage for a beginner like myself.

Is there a way to fix this without rewriting the better part of the code??


Solution

  • There is an alternative which would require rewriting some of the js.

    Basically the reason the code doesn't work is because the erb is compiled before its rendered but the js is executed after rendering so the asset_path is incorrect and not dynamic.

    You could create an object listing all of the available routes and then use that to insert the path names.

    Assuming your loop is something like

    var piecesList = [
      "first",
      "second"
    ]
    $.each(var piece in piecesList) function(piece) {
      var image_path = "img/path/{piece}.png"
    }
    

    You could manually assign all of those pieces in an object like so

       var piecesRoutes = {
         "first" : "<%= image_path('chesspieces/first.png') %>",
         "second" : "<%= image_path('chesspieces/second.png') %>",
       }
    

    And then in the loop, call them like so

    var image_path = piecesRoutes[piece]