何时使用 before 过滤器和即将组织代码 (DRY)

发布于 2024-08-28 03:19:07 字数 3389 浏览 2 评论 0原文

我编写了一些 Ruby 脚本来废弃一些 Web 数据;然后我将该脚本与一个小型 Sinatra 应用程序合并,以“发布”一些其余方法来获取报告...

我的 Sinatra 应用程序正在向 Nagios3 发出请求并浏览一些表单(实际上有 3 个步骤),这工作正常。
然后在第 3 步中,我“按下”提交按钮,几秒钟后我就得到了一份包含服务组可用性的巨大 html 报告。此时,我使用 Nokogiri 只提取一个字段,这对于任何服务组也都可以正常工作(它可以管理任何服务组维度)。

要让 /index 包含服务组列表,我只需转到步骤 1 和步骤 2。
Step3 只需要 /check (构建报告并获取/打印可用性)

好吧,一切都工作正常,所以我提出的问题很奇怪,因为问题是我不知道如何正确干燥它。
我在过滤器之前写了#Initialize Mechanize 的东西,Step1 和Step2。 /index 和 /check 都需要它们,但事实上我不知道这是否是正确的地方。

任何代码架构技巧:)

提前致谢。
弗朗西斯科

require 'rubygems'
require 'sinatra'
require 'mechanize'
require 'nokogiri'
require 'logger'

configure :production do
    enable :logging, :dump_errors
    enable :inline_templates
    disable :run
end

error do
    e = request.env['sinatra.error']
    puts e.to_s
    puts e.backtrace.join("\n")
    "Application Error!"
end

not_found do
    "Page not found!"
end

before do
    content_type 'text/html', :charset => 'utf-8'

    # Initialize Mechanize
    @agent = Mechanize.new
    @agent.keep_alive = false
    @agent.open_timeout = 3600
    @agent.read_timeout = 3600
    @agent.max_history = 0
    @agent.log = Logger.new('mechanize.log')
    @agent.auth('myusername', 'mysecretpass')
    @page = @agent.get('http://nagios3/nagios/cgi-bin/avail.cgi')

    # Step1 and Step2 are use in both /index and /check  

    # Step1 - Form1 (Select Report Type[hostgroups,hosts,hostgroups,servicegroups*,services])
    @form1 = @page.forms.first
    @form1.field_with(:name => 'report_type').options[2].select
    @page = @agent.submit(@form1)

    # Step2 - Form2 (Select Servicegroup)
    @form2 = @page.forms.first
    @total_services_list = @form2.field_with(:name => 'servicegroup').options  
end

get '/' do
    # When under /index we don't go further to Step3 - Form3 (generate report)
    erb :index
end

get '/check/:servicegroup' do

    @servicegroup = params[:servicegroup].to_i

    # Step3 - Form3 (Select Report Options)
    @form2.field_with(:name => 'servicegroup').options[@servicegroup].select
    @page = @agent.submit(@form2)

    @form3 = @page.forms.first
    @form3.field_with(:name => 'timeperiod').options[7].select
    @page = @agent.submit(@form3)

    # Step4 - Extract Average from computed data
    page_html = Nokogiri::HTML.parse(@page.body)
    @total_hostservices_size = page_html.xpath("html/body/div[3]/table/tr[*]/td[2]").to_a.size
    puts @average = page_html.xpath("html/body/div[3]/table/tr[#{@total_hostservices_size}]/td[2]").inner_text

    erb :check, :layout => false
end


__END__


@@layout
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head><title>Nagios Availability Checker</title></head>
    <body>
        <strong>Nagios Availability Checker</strong>
        <hr />
        <div>
            <%= yield %>
        </div>
        <hr />
    </body>
</html>

@@index
<h3>List Service Groups</h3>
<% @total_services_list.each_with_index do |name,id| %>
    <a href="/check/<%= id %>"><%= id %> - <%= name %></a><br />
<% end %>

@@check
    <%= @average %>

I have coded some Ruby script to scrap some web data; then I merged that script with a small Sinatra application to "publish" some rest methods to fetch reports...

My Sinatra app is making a request to Nagios3 and navigate through some forms (3 steps in fact), this is just working fine.
Then under step3, I "press" the submit button and after a few seconds I have a huge html report with servicegroups availabilities. At this point I am using Nokogiri to extract just one field, this is working fine too for any servicegroup (it can manage any servicegroup dimension).

To have the /index with a list of servicegroups, I need to goto Step1 and Step2 only.
The Step3 is needed just for /check (build the report and fetch / print availability)

Well, all is just working fine so the question I'm making is like weird because the thing is I don't know how to dry it correctly.
I'm writting the #Initialize Mechanize stuff, Step1 and Step2 under before do filters. They are needed in both /index and /check, but in fact I don't know if this is the right place to do it.

Any code architectural tip :)

thanks in advance.
Francisco

require 'rubygems'
require 'sinatra'
require 'mechanize'
require 'nokogiri'
require 'logger'

configure :production do
    enable :logging, :dump_errors
    enable :inline_templates
    disable :run
end

error do
    e = request.env['sinatra.error']
    puts e.to_s
    puts e.backtrace.join("\n")
    "Application Error!"
end

not_found do
    "Page not found!"
end

before do
    content_type 'text/html', :charset => 'utf-8'

    # Initialize Mechanize
    @agent = Mechanize.new
    @agent.keep_alive = false
    @agent.open_timeout = 3600
    @agent.read_timeout = 3600
    @agent.max_history = 0
    @agent.log = Logger.new('mechanize.log')
    @agent.auth('myusername', 'mysecretpass')
    @page = @agent.get('http://nagios3/nagios/cgi-bin/avail.cgi')

    # Step1 and Step2 are use in both /index and /check  

    # Step1 - Form1 (Select Report Type[hostgroups,hosts,hostgroups,servicegroups*,services])
    @form1 = @page.forms.first
    @form1.field_with(:name => 'report_type').options[2].select
    @page = @agent.submit(@form1)

    # Step2 - Form2 (Select Servicegroup)
    @form2 = @page.forms.first
    @total_services_list = @form2.field_with(:name => 'servicegroup').options  
end

get '/' do
    # When under /index we don't go further to Step3 - Form3 (generate report)
    erb :index
end

get '/check/:servicegroup' do

    @servicegroup = params[:servicegroup].to_i

    # Step3 - Form3 (Select Report Options)
    @form2.field_with(:name => 'servicegroup').options[@servicegroup].select
    @page = @agent.submit(@form2)

    @form3 = @page.forms.first
    @form3.field_with(:name => 'timeperiod').options[7].select
    @page = @agent.submit(@form3)

    # Step4 - Extract Average from computed data
    page_html = Nokogiri::HTML.parse(@page.body)
    @total_hostservices_size = page_html.xpath("html/body/div[3]/table/tr[*]/td[2]").to_a.size
    puts @average = page_html.xpath("html/body/div[3]/table/tr[#{@total_hostservices_size}]/td[2]").inner_text

    erb :check, :layout => false
end


__END__


@@layout
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head><title>Nagios Availability Checker</title></head>
    <body>
        <strong>Nagios Availability Checker</strong>
        <hr />
        <div>
            <%= yield %>
        </div>
        <hr />
    </body>
</html>

@@index
<h3>List Service Groups</h3>
<% @total_services_list.each_with_index do |name,id| %>
    <a href="/check/<%= id %>"><%= id %> - <%= name %></a><br />
<% end %>

@@check
    <%= @average %>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

电影里的梦 2024-09-04 03:19:07

您可以使用助手:

helpers do
  def select_report_type
    # ...
  end

  def something_else
    # ...
  end
end

before { select_report_type }
get "/" do
  select_report_type
  # ...
  haml :index
end

You can use helpers:

helpers do
  def select_report_type
    # ...
  end

  def something_else
    # ...
  end
end

before { select_report_type }
get "/" do
  select_report_type
  # ...
  haml :index
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文