Native Module GuideThis guide is dedicated to helping Ruby developers, from beginners to seasoned pros, to seamlessly work with JavaScript environments using Opal's Native module. We aim to provide a clear pathway for Rubyists to harness the power of JavaScript without stepping away from the comfort of Ruby syntax.
Native ModuleTo start using the Native module in your project, require it at the beginning of your Ruby file:
require 'native'
This line loads the Native module, granting you access to JavaScript's global objects, functions, and properties directly from Ruby.
Native Module UsageThe global JavaScript object, typically window in a browser environment, can be referenced in Opal using the $$ or $global variables:
win = $$ # References the global JavaScript `window` object
Access and modify JavaScript object properties straightforwardly:
# Access a property
puts win[:location][:href] # Output: the current page URL
# Modify a property
win[:location][:href] = "https://example.com" # Redirects the browser to example.com
Invoke methods on JavaScript objects with ease:
win.alert('Hello, Opal!')
You can define Ruby methods on JavaScript objects for more complex interactions:
class << win
def close!
close # Calls the JavaScript close method on the window object
end
def href=(url)
self[:location][:href] = url
end
end
win.href = "https://example.com" # Sets the page URL
win.close! # Closes the browser window