Problem with my if then statements executing
Right now I use an 'after_commit :share_all' on my posts model to call the method below which shares info to facebook and twitter. I'm trying to check if the user has the right authentication provider and if so then to issue the share.
def share_all
if user.authentications.where(:provider => 'facebook')
then user.facebook_share(title, content, item_name)
end
if user.authentications.where(:provider => 'twitter')
user.twitter_share(title, content, item_name)
end
end
When a user only has a twitter provider the first part still seems t开发者_StackOverflowo execute the user.facebook_share, I think this because I see an error in the log of undefined method `token' for nil:NilClass and then there's no post to twitter. How do I get the first if statement only to execute if there's a 'facebook' provider, and if not move on and execute the second if statement if there's a 'twitter' provider?
def facebook_share(title, content, item_name)
facebook.feed!(
:message => "#{title} #{item_name} #{content}"
)
end
def facebook
unless @fb_user
provider = self.authentications.find_by_provider('facebook')
@fb_user ||= FbGraph::User.me(provider.token)
end
@fb_user
end
def twitter
unless @twitter_user
provider = self.authentications.find_by_provider('twitter')
@twitter_user = Twitter::Client.new(:oauth_token => provider.token, :oauth_token_secret => provider.secret) rescue nil
end
@twitter_user
end
def twitter_share(title, content, item_name)
twitter.update("#{title} #{item_name} #{content}")
end
I think ActiveRecord is returning an empty array []
1 which is true
as far as Ruby2 is concerned. I imagine you need something like:
def share_all
if user.authentications.where(:provider => 'facebook').any?
user.facebook_share(title, content, item_name)
end
...
1. Well, actually, an ActiveRecord object with Array-like attributes.
2. Everything except false
and nil
is true
.
精彩评论