I was wondering what the best way to include ruby classes in the Volt framework. I want to use the Socket Class to find the IP address of the visitor of the site. I want to use it in a controller, but putting:
require 'socket'
at the top of the file does not work. Any suggestions?
Well, I don't think you can use the Socket class on the client-side since Volt uses OpalRb to run Ruby on the client, and unfortunately I don't think Opal can support the Socket class since that's kind of hard to do in the browser. You can, however, run code on the server side and pass your desired results on to the client. You can do so using Volt's tasks. You can create them like so:
require 'socket'
class SocketTask < Volt::Task
def use_sockets
# do your thing with sockets here...
end
end
and then you can use them elsewhere, e.g., in a controller like this:
class Controller < Volt::ModelController
def some_action
SocketTask.use_sockets
# You can also use the #then method of the returned promise to get the result of the call.
# You can even use the #fail method on the promise to get any thrown errors.
# The following can also run code on the client.
SocketTask.use_sockets.then do |result|
alert result
end.fail do |error|
puts error
end
end
end
There's also a good screencast by Rick Carlino about Volt tasks here.