views:

71

answers:

2

I have a Ruby on Rails application and I need to duplicate some computations in both Ruby and JavaScript. Ruby is used in the server side but I also need to compute a students grade on the browser using JavaScript.

My first thought is to build up a JavaScript function using strings, convert it to JSON, ship it to the browser where it is decoded and used as a normal JavaScript function. Does this sound workable to you? I've tried something simple like

def letterGradeCalc
  "function calcLetterGrade(score) {
    if( score >= 90 ) { return 'A'; }
    else if( score >= 80 ) { return 'B'; }
    else if( score >= 0 ) { return 'F'; }
    else return '';
  }".to_json
end

but it is not a valid JavaScript function when the browser gets it. It kinda looks like one but it has double quotes around it.

Am I barking up the wrong tree here? I get the feeling that there is some insanely easy way to do this and but I'm completely missing it. :)

+5  A: 

For something trivially simple like that, I'd suggest writing a pure JS file with the function and including it. Generating JS from ruby for this sounds like severe overkill. Then write the same function in Ruby.

If it's a moderately complex algorithm, I'd suggest only writing it in Ruby, and making a web service to call from JS.

Edit, adding code that got mungled in my comment below:

function calcLetterGrade(score, lowCutoff, hiCutoff) 
{ 
  if( score >= hiCutoff ) { return 'A'; } 
  else if( score >= lowCutoff ) { return 'B'; } 
  else if( score >= 0 ) { return 'F'; } 
  else return ''; 
}
Marc Hughes
Good suggestion. The function is generally not complex (if..then) but it is built using user input. Therefor I don't think I can construct the function before hand. :(
RNHurt
Build using user input? Sounds like those are just parameters to me.function calcLetterGrade(score, lowCutoff, hiCutoff) { if( score >= hiCutoff ) { return 'A'; } else if( score < lowCutoff ) { return 'B'; } else if( score >= 0 ) { return 'F'; } else return ''; }
Marc Hughes
+2  A: 

Make it an AJAX call to the web server from JavaScript, if it's not something that needs to be done quickly. With Rails, just call

remote_function :url    => remote_request_url,
                :update => dom_id_to_update

And have it render the result in the controller method as text.

Stephen Touset
Another good suggestion, but I really need the UI to update quickly. Since the user could be entering information pretty fast I think a call would overwhelm my system.
RNHurt