我实际上使用的是Rails 3.0,因此它是rails console
vs rails runner try.rb
。以下代码在控制台中运行良好,但不是带有运行程序的脚本。我需要跑步者(而不是使用ruby try.rb
)因为项目有一些ActiveRecord代码。
更新:我无法在myproj\lib\tasks\
内部运行(当前目录为myproj\lib\tasks\
),但可以在myproj
内运行,所以问题就变成了,为什么必须在myproj
运行?
http_header = {'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.53 Safari/534.3'}
url = URI.parse('http://www.google.com/')
response = Net::HTTP.start(url.host, url.port) do |http|
http.get(url.path, http_header)
end
puts response.body
错误代码是:
c:\ror\proj\lib\tasks>rails runner try.rb
c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/runner.rb:50:in `eval': no method name given (ArgumentError)
from c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/runner.rb:50:in `eval'
from c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/runner.rb:50:in `<top (required)>'
from c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:39:in `require'
from c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:39:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
答案 0 :(得分:2)
你从哪里运行命令?
您需要从rails根目录运行该命令,并提供文件名的完整或相对路径,以便rails runner lib/try.rb
原因是命令运行器接受包含ruby代码的文件的名称或包含ruby代码的字符串。当命令运行器找不到argv(0)中命名的文件时,它会尝试eval argv(0),所以它试图评估字符串try.rb