开发者

strange nil object result

I have a module:

module Voteable
  def has_up_vot开发者_运维知识库e_of user
    return ! self.votes.select{|v| v.user.id == user.id && v.value == 1}.empty?
  end
  def has_down_vote_of user
    return ! self.votes.select{|v| v.user.id == user.id && v.value == -1}.empty?
  end
end

Which is mixed into a model:

class Comment < ActiveRecord::Base
  include Voteable
end

In a controller code, there is a check:

has_up_vote = @voteable.has_up_vote_of @user
has_down_vote = @voteable.has_down_vote_of @user

@voteable and @user are existing model items, found in a DB.

Suppose, voteable item has up-vote of user. After executing the code, has_up_vote will be equal to true, and has_down_vote will be nil.

Why nil, instead of false ?

I have used several variations of methods, but the problem is the same. Even this gives me the same effect:

def has_up_vote_of user
  has = self.votes.select{|v| v.user.id == user.id && v.value == 1}.empty?
  return !has.nil? && has
end

Posssible, i'm misunderstanding something, but this behavior is strange

Update

I've noticed very strange behaviour.

When i change methods to trivial:

def has_up_vote_of user
  return false
end
def has_down_vote_of user
  return false
end

They both returns nil, when i debug the app. But, from console, they returns false.

It's more stange, because i cannot do anything with these results. These code is not working:

has_up_vote = false if has_up_vote.nil?
has_down_vote = false if has_down_vote.nil?


I think that the debugging environment you're running in is interfering with the actual value of has_down_votes. The select method should never return nil as defined.


Instead of !{}.empty? you could use {}.present?

Its more readable and the output will always be true/false only


I know this doesn't get to the root cause of your strange problem, but it should give you the results you want. Instead of

return ! self.votes.select{|v| v.user.id == user.id && v.value == -1}.empty?

try

return !!self.votes.select{|v| v.user.id == user.id && v.value == -1}.any?

The double exclamation point is intentional -- it will cause nil to become false. (!arr.empty? is equivalent to arr.any? which is equivalent to !!arr.any? -- except the last one converts the nil to false)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜