<mycontroller>中的NoMethodError#<mymethod> <mymodule> <mymodule> </mymodule> </mymeoduod> </mymethod> </mycontroller>的未定义方法`<mymodulemethod>'

时间:2013-04-01 05:01:49

标签: ruby-on-rails module nomethoderror

对于基础知识来说,但是我有一段时间可以获得一个非常基本的工作流程:

1)使用方法定义模块以将URL保存到var(或返回它)

2)在控制器中调用该方法以初始化方法

3)让视图显示该网址

AuthController中的NoMethodError#oauth undefined方法getAccessToken的“oauthurl”:模块

模块:\ lib \ get_access_token.rb

module GetAccessToken
    CONSUMER_TOKEN = { :token=>"mytokenstringwhichisreallylong", :secret=> "mysecretstringwhichisreallylong" }
    def self.oauthurl    
      @oauthurl="https://us.etrade.com/e/t/etws/authorize?key=#{(CONSUMER_TOKEN[:token])}&token="
    end
end

控制器:app \ controllers \ auth_controllers.rb

require 'get_access_token'
class AuthController < ApplicationController
include GetAccessToken
before_filter :oauthurl1
    def oauthurl1
        GetAccessToken.oauthurl
    end
end

查看:app \ views \ auth \ oauth.html.erb

<% provide(:title, 'oAuth') %>
<h1>oAuth</h1>
<%= link_to "oAuth", @oauthurl %>

我的更高级别的目标是让eTrade oAuth流程正常工作,但我想确保我理解每一行代码而不是接受别人的代码,而我无法让这个非常基本的构建块工作。

3 个答案:

答案 0 :(得分:0)

将以下内容添加到config / application.rb:

config.autoload_paths += Dir["#{config.root}/lib/**"]

将您的AuthController更改为:

class AuthController < ApplicationController
  include GetAccessToken

  def oauthurl1
    GetAccessToken.oauthurl
  end
end

答案 1 :(得分:0)

您的模块代码将是

module GetAccessToken
  CONSUMER_TOKEN = { :token=>"mytokenstringwhichisreallylong", :secret=> "mysecretstringwhichisreallylong" }
  def self.oauthurl    
    "https://us.etrade.com/e/t/etws/authorize?key=#{(CONSUMER_TOKEN[:token])}&token="
  end
end

,您的控制器代码应为

require 'get_access_token'

class AuthController < ApplicationController
  include GetAccessToken

  def oauthurl1
    @oauthurl = GetAccessToken.oauthurl
  end
end

我们需要在控制器中初始化@oauthurl以在视图中使用此变量,否则它将为nil

答案 2 :(得分:0)

在上述贡献的慷慨帮助下,这就是我最终解决错误的方法。我在控制器而不是模型中定义了实例变量,并使用before_filer:

初始化了控制器方法

型号:\ lib中\ test_module.rb

module TestModule
    CONSUMER_TOKEN = { :token=>"myReallyLongToken", :secret=> "myReallyLongSecret" }

    def self.testUrl
        "https://us.etrade.com/e/t/etws/authorize?key=#{(CONSUMER_TOKEN[:token])}&token="
    end
end

控制器:app \ controllers \ test_controller.rb

require 'test_module'

class TestController < ApplicationController
  include TestModule

  before_filter :testUrl1Init

  def testUrl1Init
    @testurl=TestModule.testUrl
  end
end

查看:\ app \ views \ test \ test.html.erb

<% provide(:title, 'test') %>
<h1>test</h1>
<%= link_to "test link", @testurl %>