开发者

Is there a way to have a persistent variable available to all methods in a /lib job?

开发者 https://www.devze.com 2023-03-03 05:42 出处:网络
I开发者_如何转开发\'m writing the following job: /lib/contact_import_job.rb In this job I have:

I开发者_如何转开发'm writing the following job:

/lib/contact_import_job.rb

In this job I have:

def perform
  current_user = XXX.user
  my_method(21)
end
private
my_method(i)
  is there a way to get current_user here w/o having to pass it???
end

Is there a way to use current_user in my_method, without having to pass it? I have several of these private methods and it seems annoying to have to pass current_user to each one?

Ideas? Thanks


You could define the job as a class, so you could have

class ContactImporterJob 

  def initialize(user)
    @user = user
  end

  def perform
    # Do all the stuff here, accessing @user for the user
  end

  private
  # Private methods still have access to @user
end

That way your script can send the current user in once and not have to keep passing it around. Like :

job = ContactImporterJob.new(current_user)
job.perform


You should always pass "states" to your external methods, even if they can get it without passing. So pass your current_user and other session based data. So it will be easier to use and to test it.

Good luck

0

精彩评论

暂无评论...
验证码 换一张
取 消