Ruby: Display SNMP output in Sinatra - ruby

i am trying to make a little website with Sinatra, where i want to display SNMP data.
require 'sinatra'
#require 'sinatra/reloader'
require 'snmp'
get'/' do
'Hello World'
SNMP::Manager.open(:host => 'localhost') do |manager|
response = manager.get(["sysDescr.0","sysName.0"])
response.each_varbind do |vb|
puts "#{vb.name.to_s} #{vb.value.to_s} #{vb.value.asn1_type}"
end
end
end
Unfortunately this code outputs the result on the console and not on the Web Page.
I hope you can help me.

It looks like your calling puts as you iterate through your data, this will print the results to the console as ruby cannot input items directly onto the web page, and because puts is only able to print into your console/ terminal. if you want to display the results on your web page you will need to pass them as params in to your :erb file, then display them within the erb file like so:
get'/' do
'Hello World'
SNMP::Manager.open(:host => 'localhost') do |manager|
#response = manager.get(["sysDescr.0","sysName.0"]) # add the # symbol to then pass as params into the erb file
end
erb(:index) # load up your erb file
end
then simply load your values in the erb file like so
<%=#response.each_varbind do |vb|%>
<p>
<%={vb.name.to_s} + {vb.value.to_s} + {vb.value.asn1_type}%>
</p>
<%end%>
Now the controller will load the index.html.erb file whenever the route get('/') is called and you should see your values displayed within the paragraph tag on screen
Hope that helps!

Related

ruby/sinatra: will code outside the routes run only once or each time site is pinged?

I have a slim Sinatra site.
If I include code outside the get routes, will it run in the background only once, or will it trigger each time the IP address is pinged.
For example will the function 'start' only run once on server creation / gitpush or will it run anew each site visit.
--
other-code.rb
$variable
$count = 0
def start
$variable = "hello world + #{$count}"
$count += 1
end
start
--
index.rb
require 'sinatra'
require 'json'
require 'other-code'
get '/' do
content_type :json
puts $variable
end
Require only loads the ruby code from the required file once.
Here is how you can tell:
#index.rb
require 'sinatra'
require 'json'
require_relative 'other_code'
get '/' do
content_type :json
puts $variable
end
# other_code.rb
$variable
def start
$variable = 'hello world'
end
puts 'other code called'
start
Now start your sinatra server
ruby index.rb
You will see this in the console:
other code called
== Sinatra (v2.0.5) has taken the stage on 4567 for development with backup from Puma
Puma starting in single mode...
Then hit your browser a few times and look at your console, you will only see other code called output 1 time. However each time you hit your get route, you should see output hello world!

Zero Bytes Sent When Sending Axlsx Gem Generated File From Sinatra

Attempting to prompt a download window and stream an XLSX file using Ruby Sinatra and the AXLSX gem, my excel file serializes successfully to local file, so I know its a valid excel doc, but I need it to transfer content to the end user. There haven't been any docs online with examples of AXLS and Sinatra used together, only rails. Help is appreciated!
class Downloads < Sinatra::Base
get '/downloads/report' do
## ...
Axlsx::Package.new do |p|
p.workbook.add_worksheet(name: 'tab name') do |sheet|
## ...
end
content_type 'application/xlsx'
attachment 'cost-code-dashboard.xlsx'
p.to_stream # unsuccessful
# p.to_stream.read # unsuccessful as well
end
end
end
I have also tried the following snippet unsuccessfully
Axlsx::Package.new do |p|
## ...
send_file p.to_stream.read, type: "application/xlsx", filename: "cost-code-dashboard.xlsx"
end
It appears that the issue had everything to do with how Axlsx::Package.new was called, the helper functions were not available inside Axlsx, the following solution worked - online documentation said that the below content_type was better
get '/downloads' do
content_type :'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
p = Axlsx::Package.new
p.workbook.add_worksheet(name: 'Test') do |sheet|
sheet.add_row ['Hello world']
end
p.to_stream
end

Mechanize (Ruby gem) not recognizing a form from a saved HTML file, but it recognizes the form when accessing the actual website?

I'm trying to write Rspec tests for my Mechanize agent.
My agent is supposed to go to a website, log into the form, then scrape some data off the website. I also downloaded FakeWeb to stub the HTTP requests, and make my tests faster.
Here is my account_spec.spec file:
require 'spec_helper'
describe Account do
before(:each) { #account = Account.new('bob', '1234') }
describe '#login' do
before(:each) do
home_page = File.read('spec/html/home_page.html')
login_page = File.read('spec/html/login_page.html')
FakeWeb.register_uri(:get,
"https://www.example.com/",
body: home_page,
status: ["200", "Success"],
content_type: "text/html")
FakeWeb.register_uri(:get,
"https://www.example.com/account/login",
body: login_page,
status: ["200", "Success"],
content_type: "text/html")
#web_crawler = Mechanize.new
#home_page = #web_crawler.get("https://www.example.com/")
#login_page = #web_crawler.get("https://www.example.com/account/login")
end # -- before :each
it 'finds the login form' do
login_form = #login_page.form_with(:class => "form login")
puts login_form.class # ==> nil:NilClass
end
end # -- #login
end # -- Account
However, when I comment out the FakeWeb uri for example/account/login (it then accesses the real server), it actually returns the correct form. Basically, if I am searching for the form in my locally saved HTML file, Mechanize can not find it, but if I check the actual website, it does find it. I would like to know if there is a way around this, and why this happens.
Any help would be greatly appreciated.

Save page with css, js and images using watir

How can I save page with all its content using watir-webdriver?
browser.html save only browser's elements. If I open file where I dumped browser.html there is no styling.
Also browser.html doesn't save iframes. I can loop through iframes and save them separately, but they will be separated from the main page.
I record only htmls for now, maybe later I'll save screenshots, because there is no simple way to dump whole page with its css and images.
require 'fileutils'
class Recorder
attr_reader :request, :counter, :browser
# request should contain w(login_id start_time)
def initialize(request)
#request, #counter = request, 1
# Settings class contains my configs (enable recording, paths, etc.)
FileUtils.mkpath(path) if Settings.recorder.record and !File.exists?(path)
end
def record(hash)
return unless Settings.recorder.record
#browser = hash["browser"]
record_html(hash)
record_frames(hash)
#counter += 1
end
private
# hash should contain (method_name browser)
def record_html(hash)
File.open("#{path}#{generate_file_name(hash)}", "w") do |file|
file.write("<!--#{browser.url}-->\n")
file.write(browser.html)
end
end
def record_frames(hash)
browser.frames.each_with_index do |frame, index|
File.open("#{path}#{generate_file_name(hash, index + 1)}", "w") do |file|
file.write("<!--#{browser.url}-->\n")
file.write(frame.html)
end
end
end
def path
"#{Settings.recorder.path}/#{request["login_id"]}/#{request["start_time"]}/"
end
def generate_file_name(hash, frame=nil)
return "#{counter}-#{hash["method_name"]}.html" if frame.nil?
"#{counter}-frame#{frame}-#{hash["method_name"]}.html"
end
end
I don't know about Watir but for those who might want to save a page (including CSS and JavaScript that are directly in the page) using Selenium WebDriver (which Watir wraps around), the easiest way is to use the page_source method (of the WebDriver class). As its name suggests, it gives so whole source. Then it's just a matter of saving to a new file, like so :
driver = Selenium::WebDriver.for(:firefox)
driver.get(URL_of_page_to_save)
file = File.new(filename, "w")
file.puts(driver.page_source)
file.close
It won't save the JavaScript or CSS inside other files though.

Why doesn't the sinatra-redirect-with-flash gem work with shotgun?

I want to show flash messages using sinatra-redirect-with-flash gem.
Here's my ruby code:
require 'sinatra'
require 'sinatra/base'
require 'sinatra/flash'
require 'sinatra/redirect_with_flash'
require 'data_mapper'
require 'haml'
require 'builder'
# ...
class App < Sinatra::Base
enable :sessions
register Sinatra::Flash
helpers Sinatra::RedirectWithFlash
use Rack::MethodOverride
get '/' do
#notes = Note.all :order => :id.desc
#title = 'All TODOs'
if #notes.empty?
flash.now[:error] = 'No TODOs found. Add your first below.'
end
haml :home
end
post '/' do
n = Note.new
n.content = params[:content]
n.created_at = Time.now
n.updated_at = Time.now
if n.save
redirect '/', :notice => 'TODO saved successfully.'
else
redirect '/', :error => 'Failed to save TODO.'
end
end
# ...
end
And views/layout.haml is:
!!! 5
%html{:lang => "en"}
%head
%meta{:charset => "utf8"}
%body
%header
%hgroup
%h1
%a{:href => "/"}= SITE_TITLE
%h2= SITE_DESCRIPTION
#main
=styled_flash
=yield
After adding a TODO successfully, I expected to see the flash message 'TODO saved successfully.' on the home page. But no flash messages are shown after redirection when I run my app using shotgun. Flash messages are shown well when I run ruby app.rb or rackup.
How can I solve this problem?
Another problem is also happening when I run the app using shotgun. In get '/' method, if I use flash[:error] instead of flash.now[:error], the flash message doesn't show up on the page.
I am shadowning this tutorial, but I made some differences:
erb -> haml
Classic Sinatra app -> Subclassing Sinatra::Base
rack-flash -> sinatra-flash
You can browse whole codes here.
Thanks for any answers/comments.
The shotgun gem reloads Sinatra after every request. The README says:
Each time a request is received, it forks, loads the application in
the child process, processes the request, and exits the child process. The
result is clean, application-wide reloading of all source files and templates on
each request.
As a result, you will need some sort of mechanism to preserve state between requests that doesn't rely on data stored in each child process.

Resources