Rails 4,Mechanize,Figaro:环境变量无效

时间:2015-11-28 00:52:17

标签: ruby-on-rails-4 environment-variables mechanize figaro-ruby

我试图登录网站,但我的env变量没有以必要的形式正确插入。我正在使用Figaro,我的环境变量安全地存储在config/application.yml中。我可以确认两件事......

  1. 在对我的实际电子邮件和密码进行硬编码时,我能够成功登录
  2. 在Rails控制台中进行测试时,我的环境变量正常返回(例如ENV [" WHATEVER"]返回正确的值)

    # app/helpers/scrape_wf.rb
    
    require 'mechanize'
    
    agent = Mechanize.new
    page = agent.get('https://www.wealthfront.com/login')
    login_form = page.forms.first
    
    # LOG IN UNSUCCESSFUL
    
    login_form.email    = ENV["WF_EMAIL"] 
    login_form.password = ENV["WF_PASSWORD"]
    
    home_page = login_form.submit
    
    puts page.title          # => Log In to Wealthfront
    puts home_page.title     # => Log In to Wealthfront
    
    # LOG IN SUCCESSFUL
    
    login_form.email    = "my_harcoded_email"
    login_form.password = "my_harcoded_password"
    
    home_page = login_form.submit
    
    puts page.title          # => Log In to Wealthfront
    puts home_page.title     # => Wealthfront
    
  3. 并在控制台中......

        rails c
        Loading development environment (Rails 4.2.4)
        [1] pry(main)> ENV["WF_EMAIL"]
        => "my_harcoded_email"
        [2] pry(main)> ENV["WF_PASSWORD"]
        => "my_harcoded_password"
    

    我做错了什么......?

1 个答案:

答案 0 :(得分:0)

根据this excellent post ...

  

当您在Rails应用程序中安装Figaro gem时,您在config / application.yml中输入的任何值都将在启动时加载到ruby ENV哈希中。

...因为我正在开发脚本并从命令行运行它(即ruby such_and_such.rb),我的环境变量没有被设置/初始化,因此当脚本执行时它们是空白的。

解决方案:将结果打印到视图(确认,确实有效),而不是控制台。