【问题标题】:params is not visible in some sinatra helper functionsparams 在某些 sinatra 辅助函数中不可见
【发布时间】:2017-10-08 09:43:50
【问题描述】:

我对函数find_agency的参数可见性有疑问:

代码:

需要'sinatra/base'

module Sinatra
  module AgencyRightsHelper
    def self.find_agency
      @agency = nil
      if !params[:agency_id].nil? then
        @agency = Agency.find(params[:agency_id]) and return
      end
    end

def before_get_agency rights_params
  AgencyRightsHelper::find_agency
end
  end
  helpers AgencyRightsHelper
end

错误:

2017-05-10 00:01:26 - NoMethodError - undefined method `params' for Sinatra::AgencyRightsHelper:Module:
    /Users/dali/perso/spacieux-be/app/helpers/agency_rights_helper.rb:18:in `before_get_agency'
    /Users/dali/perso/spacieux-be/app/helpers/rights_helper.rb:61:in `before_action'

params 在其他没有使用 self 的辅助函数中可见,但我觉得有必要使用它来重用辅助函数本身的函数。

【问题讨论】:

    标签: ruby sinatra


    【解决方案1】:

    find_agency 是一个类方法,这意味着它无法访问特定实例的属性和方法,因此您将无法访问 Sinatra 应用程序类的给定实例的params(请参阅@ 987654321@)。相反,您可以创建这样的模块:

    module AgencyRightsHelper
      def find_agency
        @agency = Agency.find(params[:agency_id]) if params[:agency_id].present?
      end
    end
    

    然后您可以使用此方法,例如在您的 Sinatra 应用程序类中的 before 块中。

    【讨论】:

    • 那是我的原始代码,但我不能在同一个助手本身中使用助手函数。找不到函数。
    • 我不确定我是否理解正确,但您可以轻松地向AgencyRightsHelper 添加另一个函数并从find_agency 调用它。你能告诉我你完整的 Sinatra App 课程代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    相关资源
    最近更新 更多