Javascript – Sharing business logic between server-side and client-side of web application

client-sidecode-reusejavascriptruby-on-railsserver-side

Quick question concerning shared code/logic in back and front ends of a web application.

I have a web application (Rails + heavy JS) that parses metadata from HTML pages fetched via a user supplied URL (think Pinterest or Instapaper). Currently this processing takes place exclusively on the client-side. The code that fetches the URL and parses the DOM is in a fairly large set of JS scripts in our Rails app.

Occasionally want to do this processing on the server-side of the app. For example, what if a user supplied a URL but they have JS disabled or have a non-standard compliant browser, etc. Ideally I'd like to be able to process these URLS in Ruby on the back-end (in asynchronous background jobs perhaps) using the same logic that our JS parsers use WITHOUT porting the JS to Ruby.

I've looked at systems that allow you to execute JS scripts in the backend like execjs as well as Ruby-to-Javascript compilers like OpalRB that would hopefully allow "write-once, execute many", but I'm not sure that either is the right decision.

Whats the best way to avoid business logic duplication for apps that need to do both client-side and server-side processing of similar data?

Best Answer

Trying to interpret one language into another is going to add too much complexity for not enough benefit.

If the amount of logic is small, just duplicate it on the client side using Javascript.

If the logic is extensive, and your architecture allows it, create a layer of REST services in Ruby that you can call using AJAX.