0

I have a problem with params visibility the function find_agency:

Code:

require '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

Error:

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 is visible in other helpers function where no self is used but I feel obliged to use it the re-use a function in the helper itself.

Charmi
  • 594
  • 1
  • 5
  • 20

1 Answers1

0

find_agency is a class method meaning it doesn't have access to attributes and methods of a specific instance, so you won't be able to access params of a given instance of a Sinatra Application class (see (Ruby,Rails) Context of SELF in modules and libraries...?). Instead you could create a module like this:

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

You can then use this method e.g. in a before block in your Sinatra Application class.

Community
  • 1
  • 1
xlts
  • 136
  • 5
  • That was my original code but I cannot use the helper function in the same helper itself. It cannot find the function. – Charmi May 10 '17 at 07:30
  • I'm not sure if I understood correctly, but you can easily add another function to `AgencyRightsHelper` and call it from `find_agency`. Can you show me your full Sinatra App class code? – xlts May 10 '17 at 07:53