2

I got a quite annoying problem tonight, and maybe someone here will be able to help me.

I'm building a static blog with nanoc, and currently making some helpers for next/previous articles (I included some tests I made and the return):

# lib/helpers.rb
include Nanoc3::Helpers::Blogging
include Nanoc3::Helpers::LinkTo

# Returns a link to the next article
# If the article in param is the most recent, returns nothing
def next_article article
  articles = sorted_articles # returns an array of article ordered by date
  pos = articles.index(article) # returns the expected integer
  pos.class # returns Fixnum
  pos.nil? # returns false
  pos + 1 # NoMethodError: undefined method `+' for nil:NilClass
  return if pos.zero? # NoMethodError: undefined method `zero?' for nil:NilClass
  link_to(articles[pos+1][:title], articles[pos+1]) # Fails too, obviously
end

I have absolutely no idea of why I can't use the "pos" variable, but can still perform some read on it. If anyone has an insight, I'll take it. Thanks in advance !

(I use ruby-1.9.3p194, with rvm, on OSX Lion, if it may have any relation)

Update : I should have precised that the returned value for pos is the expected value when just read. Strangely enough, setting

pos = articles.index(article).to_s.to_i

seems to work though. I just don't understand how & why it happens.

#layout/post_navigation.haml
.post_navigation
  .next
    =next_article @item
FabPelletier
  • 313
  • 1
  • 3
  • 5
  • I don't think there's enough info to help, it looks like it should work. There are only two explanations I can think of. either you made a mistake and think that `pos.class` returns `Fixnum` (maybe it returns Fixnum for one article, but nil for another -- perhaps the last one), or there's some devious trickery going on here (e.g. overriding the #class method). Without being able to see articles and pos, I can't really provide any more relevant info. An example that reproduces the problem would be helpful. – Joshua Cheek Aug 16 '12 at 03:09
  • I've edited the question to provide a bit more info. As the code really is vanilla, I don't really know how to provide more of an example however. – FabPelletier Aug 16 '12 at 03:53
  • 1
    I’m following Joshua Cheek here… I also think that perhaps pos has a different value on different runs. The `.to_s.to_i` “works” because `nil.to_s.to_i == 0`, but that is probably not what you intended to happen. – Denis Defreyne Aug 16 '12 at 05:26
  • Thanks to both of you for your time, you were right. The values returned were totally legal for my posts, but my about page got caught by the same rule and was indeed not part of the sorted_articles result. Woke up today with that in mind in felt bad to have posted it on SO. Sorry ! – FabPelletier Aug 16 '12 at 13:55

0 Answers0