简体   繁体   中英

Rake Task Giving Undefined Method Error When Reading File

I've got a rake task that changes the meta tags on certain pages.

desc 'changes the meta tags'
task mixup_meta_tags: :environment do 
  meta_tags = ['index','noindex','index,nofollow','nofollow,noindex']
  new_tag = meta_tags.sample(1)[0]
  #
  #iterate through html docs
  base = 'app/views/site'
  pages = ['home','about','products','pricing']
  pages.each do |page|
    filename = base + '/' + page + '.html.haml'
    text = File.read(filename)
    current_tag = Nokogiri::HTML(File.open(filename, "r")).xpath("//meta[@name='robots']").first["content"]
    File.open(filename, "w") { |file| file << text.gsub(current_tag,new_tag)}
  end   
end

I'm getting a cryptic error message:

undefined method `[]' for nil:NilClass

concerning this line:

current_tag = Nokogiri::HTML(File.open(filename,"r")).xpath("//meta[@name='robots']").first["content"]

This line is supposed to figure out what the current tags are so that they can be replaced (via the next line of code).

Any advice on what's out of place here?

It's saying that

File.open(filename,"r")).xpath("//meta[@name='robots']").first

is nil or essentially

File.open(filename,"r")).xpath("//meta[@name='robots']").empty?  # true

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