Help in ruby code
I am beginner in Ruby and having trouble understanding this code
require_relative 'custom_page'
module Jekyll
class Tag < CustomPage
def initialize(site, base, dir, tag)
super site, base, dir, 'tag'
self.data['tag'] = tag
self.data['title'] = "#{site.config['tag_title_prefix'] || 'Tag: '}#{tag}"
self.data['description'] = "#{site.config['tag_meta_description_prefix'] || 'Tag: '}#{tag}"
end
end
class Tags < CustomPage
def initialize(site, base, dir)
super site, base, dir, 'tags'
self.data['tags'] = site.categories.keys.sort
#1# puts self.data['tags']
end
end
class Site
# generate_tags_categories is called by the custom process function in site_process.rb
def generate_tags_categories
dir = self.config['tag_dir'] || 'tags'
write_page Tags.new(self, self.source, dir) if self.layouts.key? 'tags'
self.categories.keys.each do |tag|
puts "dd"
#2# puts tag
write_page Tag.new(self, self.source, File.join(dir, tag.slugize), tag)
end
end
开发者_如何学Python end
end
In the above code, the statement puts self.data['tags']
(marked 1) outputs more than 10 values as expected. However, the line puts tag
(marked 2) outputs only one value implying that array contains only one value. Isn't self.categories.keys.each
expected to loop through all the values which itself is assigned to self.data['tags']
You may start with ensuring that the 'categories' still contain many values before entering the loop:
puts "categories.keys: #{self.categories.keys.inspect}" # <<- here
self.categories.keys.each do |tag|
puts "dd"
#2# puts tag
If the first puts
shows you more than one value, and the loop is called only once, then you may want to investigate what possibly makes the loop break. Maybe write_page
throws an exception, catch somewhere up the calling stack?
When you debug some values, it's better to use inspect
method instead of (automagically called by puts
) method to_s
. The output of inspect
is more debug-friendly.
It is possible, (however unlikely) that the 'tag' contains some control characters which clear the previous output, or something like that. The inspect
is always safe. (ok, not always but in most of cases ;)
精彩评论