aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/user.rb
blob: 58597cc9b146296635a2dab45f9c0ed30d21ac72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class User < ActiveRecord::Base
  has_many :tweets, :dependent => :delete_all
  has_many :favorites, :dependent => :delete_all
  has_many :retweets, :dependent => :delete_all

  def self.cached(identity)
    if identity.is_a?(Fixnum) || identity.is_a?(Bignum)
      Rails.cache.fetch("user/#{identity}", :expires_in => 3.hour) do
        where(:id => identity).first
      end
    elsif identity.is_a?(String)
      if /^[A-Za-z0-9_]{1,15}$/ =~ identity
        uid = Rails.cache.fetch("screen_name/#{identity}", :expires_in => 3.hour) do
          if user = where(:screen_name => identity).first
            user.id
          end
        end

        cached(uid)
      end
    elsif identity.is_a?(NilClass)
      nil
    else
      raise Exception, "Invalid identity: #{identity}"
    end
  end

  def protected?
    protected
  end

  def registered?
    account
  end

  def account
    Account.where(:user_id => id).first
  end

  def profile_image_url_original
    profile_image_url.sub(/_normal((\.(png|jpeg|gif))?)/, "\\1")
  end

  def twitter_user
    if registered?
      account.twitter_user
    else
      raise Exception, "why??"
    end
  end

  def stats
    @stats_cache ||= ->{
      raise Aclog::Exceptions::UserNotRegistered unless account

      tweets.inject(
        {favorites_count: favorites.count,
         retweets_count: retweets.count,
         tweets_count: tweets.length, # cache: tweets.inject calls "SELECT `tweets`.*"
         favorited_count: 0,
         retweeted_count: 0,
         stats_api: account.stats_api}
      ) do |hash, m|
        hash[:favorited_count] += m.favorites_count
        hash[:retweeted_count] += m.retweets_count
        hash
      end
    }.call
  end
end