简体   繁体   中英

Ruby: how to make variables visible inside methods within a block?

The following code gives me NameError: undefined local variable or method `dir' in extract_snapshots method.

The code is intended to extract snapshots from a video, store them in a created temporary directory, send the snapshots to a service and remove the directory after.

  def perform
    using_temporary_directory do |dir|
      extract_snapshots
      send_snapshots
    end
  end

  def using_temporary_directory(&b)
    Dir.mktmpdir { |dir| b.call(dir) }
  end

  def extract_snapshots
    system "ffmpeg -i #{video_file_path} -vf fps=1/#{INTERVAL} #{dir}/%04d.jpg"
  end

I thought, that dir variable should be visible in extract_snapshots and send_snapshots , because it is on the same level. But it isn't in the scope of those methods. Is it possible to make dir variable visible without doing the following:

  def perform
    using_temporary_directory do |dir|
      extract_snapshots(dir)
      send_snapshots(dir)
    end
  end

?

You could do something like this, using attr_accessor :

  attr_accessor :dir

  def perform
    using_temporary_directory do
      extract_snapshots
      send_snapshots
    end
  end

  def using_temporary_directory(&b)
    Dir.mktmpdir do |dir| 
      self.dir = dir
      b.call
    end
  ensure # clear the variable when you're finished
    self.dir = nil
  end

  def extract_snapshots
    system "ffmpeg -i #{video_file_path} -vf fps=1/#{INTERVAL} #{dir}/%04d.jpg"
  end

For an explanation, attr_accessor creates reader and writer methods for you, the equivalent of the following:

def dir
  @dir
end

def dir=(val)
  @dir=(val)
end

NB in my opinion there's nothing wrong with doing it the way you've specified towards the end of your question, so pick and choose as suits your circumstances :)

Hope this helps - let me know how you get on or if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM