Skip to content

Instantly share code, notes, and snippets.

@FND
Last active March 18, 2020 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FND/acce868387e1d2cf6476b2f2027733ca to your computer and use it in GitHub Desktop.
Save FND/acce868387e1d2cf6476b2f2027733ca to your computer and use it in GitHub Desktop.
JavaScript in Ruby
  1. (optional) create .bundle/config to install gems locally:

    ---
    BUNDLE_PATH: vendor/bundle
    BUNDLE_DISABLE_SHARED_GEMS: '1'
    
  2. bundle install downloads dependencies

  3. (optional) node demo.js runs reference code

  4. bundle exec ruby demo.rb runs corresponding Ruby code

/* higher-order components */
function AppShell({ lang = "en", title }, ...content) {
return `<!DOCTYPE html>
<html lang="${lang}">
<title>${title}</title>
<body>
<h1>${title}</h1>
${Image({
uri: context.uri("static", "logo.png")
})}
${content.join("\n\t\t")}
</body>
</html>`;
}
/* atomic components */
let Image = ({ uri }) => `<img src="${uri}">`;
let Text = (_, content) => `<p>${content}</p>`;
/* view functions */
function FrontPage({ lang, user }) {
let params = {
lang,
title: `Hello, ${user.name}`
};
return AppShell(params,
Text(null, "lorem ipsum dolor sit amet"),
Image({
uri: context.uri("static", "tracker.gif")
}));
}
let fs = require("fs")
let context = {
uri: (id, params) => `http://example.org/${id}/${params}`
};
let bundle = fs.readFileSync("./bundle.js", "utf-8");
eval(bundle);
let html = FrontPage({
user: { name: "J. Doe" }
});
console.log(html);
require 'mini_racer'
context = MiniRacer::Context.new
context.attach('context.uri', proc { |id, params|
"http://example.org/#{id}/#{params}"
})
context.eval File.read('./bundle.js')
define_method :render do |view, params|
puts context.eval("#{view}(#{params.to_json})")
end
render 'FrontPage', {
user: { name: 'Jane Doe' }
}
puts '----'
render 'FrontPage', {
lang: 'de',
user: { name: 'John Doe' }
}
source 'https://rubygems.org'
gem 'mini_racer'
GEM
remote: https://rubygems.org/
specs:
libv8 (7.3.492.27.1)
mini_racer (0.2.9)
libv8 (>= 6.9.411)
PLATFORMS
ruby
DEPENDENCIES
mini_racer
BUNDLED WITH
2.1.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment