Skip to content

Instantly share code, notes, and snippets.

@Velrok
Created May 16, 2024 22:47
Show Gist options
  • Save Velrok/ff9bd26dd25dd2b2edbe91e4383c7fcd to your computer and use it in GitHub Desktop.
Save Velrok/ff9bd26dd25dd2b2edbe91e4383c7fcd to your computer and use it in GitHub Desktop.
ruby in the browser
require "js"
# access to the html document, so we can add visual elements like buttons
document = JS.global[:document]
# jq is a library which provides easer to read function to add elements
jq = JS.global['$']
# write the initial html, we give every element an ID so we can address them later
jq.apply("#main").html(
<<HTML
<p id='click_counter'></p>
<button id='clicker'>Click me</button>
HTML
)
def render_click_counter(clicks)
# we replace the html content of the paragraph element
JS.global['$'].apply("#click_counter").html(
<<HTML
<p id='click_counter'>Click counter: #{clicks}</p>
HTML
)
end
def clicks
# local storage is provided by the browser and allows us to store information
local_storage = JS.global[:localStorage]
item = local_storage.getItem('clicks')
# on first load we may not have any info item == JS::Null, so we return 0 instead
# otherwise we convert the javasript value into a ruby Integer
item == JS::Null ? 0 : item.to_i
end
def inc_clicks
local_storage = JS.global[:localStorage]
# we need to increment so we call clicks and add 1, than write that back into the
# browser provided local_storage
local_storage.setItem('clicks', clicks + 1)
end
# initial render of clicks
render_click_counter(clicks)
# register an on click handler on the button
jq.apply("#clicker").on(
'click',
proc do|event|
# we increment the click by 1
inc_clicks
# than we rerender the counter paragraph
render_click_counter(clicks)
end
)
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<!-- jquery makes it easier to add visual elements to the webpage -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<!-- this allows for ruby code to be loaded and executed in the browser -->
<script src="https://cdn.jsdelivr.net/npm/@ruby/[email protected]/dist/browser.script.iife.js"></script>
<!-- make one main element we can add everything else to -->
<div id='main'></div>
<!-- this loads and runs our code -->
<script type="text/ruby" src='app.rb'> </script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment