python python - 18 days ago 6
Ruby Question

How to define ruby code inside a haml file present in javascript folder

For my project, I am using

Ruby on Rails
and
Angular
and I have a
haml
file present in
/project_name/app/assets/javascript
folder. I want to call a ruby class from the
haml
file but unfortunately I am not able to do that.

.small-12.columns
.booking-time
%span.bold
- if ABC::D.data(:hide_hours_field) #ruby code
{{ item | timeformat }}
- else
{{ item | differentTimeFormat }}


Whenever I start the server, it's is showing it can't access the ruby class. I can easily access the ruby class in other
haml
files but not the one present in javascript folder. Can anyone help me here?

Answer

Disclaimer: I'm bad at Angular (and didn't even touch version 2). What follows is not a best practice or anything.

So, you need to configure your angular view with some knowledge from ruby side. You can't conditionally render it and you can't call ruby from angular controllers (obviously). I suggest smuggling data via window object.

In an appropriate view in your application, put this JS snippet.

<script type='text/javascript'>
    window.jsEnv = {
      hide_hours_field: <%= ABC::D.data[:hide_hours_field] %> 
    }
</script>

Then you can reference that via $window object in angular

Controller

function MyController($window) {
  this.hideHours = function() {
    return !!$window.jsEnv.hide_hours_field;
  }
}

MyController.$inject = ['$window'];

angular.module('myApp').controller('MyController', MyController);

View

.small-12.columns(ng-controller='MyController as vm')
  .booking-time
    %span.bold(ng-if='vm.hideHours()')
      {{ item | timeformat }}
    %span.bold(ng-unless='vm.hideHours()')
      {{ item | differentTimeFormat }}