重构 自己写了个检查 URL 关键字并发送邮件的脚本,大家指正一下

lishoujun · 2016年01月11日 · 最后由 jasl 回复于 2016年02月04日 · 6940 次阅读

http://yyyit.com/2016/01/checkurlinruby/ 我的博客中对应的文章 1 ruby 入门脚本 2 使用 http 发送请求 3 在响应中搜索关键字,如果不匹配则发送邮件 4 脚本中用四个叹号标记的需要替换成你自己的邮箱账号密码、收件人邮箱、目标 url 和关键字

require "open-uri"
require 'net/smtp'

class Http
  def httpget(uri)
    #如果有GET请求参数直接写在URI地址中
    html_response = nil
    open(uri) do |http|
      html_response = http.read
    end
    puts html_response
  end
  def httpgetwithassert(uri, keywords)
    #如果有GET请求参数直接写在URI地址中
    html_response = nil
    open(uri) do |http|
      html_response = http.read
    end
    if !html_response[keywords].nil?
      puts '响应中包含关键字'
    else

      puts '响应中缺失关键字'
      require 'net/smtp'
      msg = [ "Subject: 响应中缺失关键字#{keywords}\n", "to:!!!!收件人邮箱\n","\n" "响应中缺失关键字\n" ]
      Net::SMTP.start( 'smtp.163.com', 25, "163.com", "!!!!邮箱用户名", "!!!!密码", :login ) do |smtp| smtp.send_message( msg,'!!!!邮箱用户名','!!!!收件人邮箱' )
      end

    end
  end
end

Http.new.httpgetwithassert('!!!!URL','!!!!关键字')

自学 ruby 感觉会有很多 low 的语句,所以拿出来请大家给收拾收拾

你的 httpget 方法是打酱油的吗

  1. 个人更偏好 curl (curb) 胜过 openuri
  2. 示例中的 httpget 多余。
  3. html_response = open(uri) { |http| http.read }, 无需预先声明 html_response, 单行 do end 改用 {}
  4. !html_response[keywords].nil? 改为 html_response[keywords].present?, 如果是非 rails 环境。那改用 unless, 并且改为 guard 形式。
  5. 偏好 guard 形式提早返回。如果要用 if else 先处理焦点分支。
  6. httpget 和 httpgetwithassert 不够 dry, 有重复内容。可以重构下。
  7. 你的方法名起的不好。http.httpget 很别扭。http.download, http.fetch, http.receive, http.send 等等会否好些?
  8. 你可以把 参数 放到构造方法而不是接口方法里。

楼上说的外加 httpgetwithassert 函数里require 'net/smtp'是多余的

5 楼 已删除
需要 登录 后方可回复, 如果你还没有账号请 注册新账号