Add more specs for questions controller
[shapado:piglops-shapado.git] / lib / jobs / base.rb
1 require 'open-uri'
2 module Jobs
3   module Base
4     include Magent::Async
5
6     def create_badge(user, group, opts, check_opts = {})
7       return if user.admin?
8
9       unique = opts.delete(:unique) || check_opts.delete(:unique)
10
11       ok = true
12       if unique
13         ok = user.find_badge_on(group, opts[:token], check_opts).nil?
14       end
15
16       return unless ok
17
18       badge = user.badges.create(opts.merge({:group_id => group.id}))
19       if !badge.valid?
20         Rails.logger.info "Cannot create the #{badge.token} badge: #{badge.errors.full_messages}"
21       else
22         user.increment(:"membership_list.#{group.id}.#{badge.type}_badges_count" => 1)
23         if badge.token == "editor"
24           user.override(:"membership_list.#{group.id}.is_editor" => true)
25         end
26       end
27
28       if !badge.new_record?
29         Rails.logger.info ">> Created badge: #{badge.inspect}"
30         if !user.email.blank? && user.notification_opts.activities
31           Notifier.earned_badge(user, group, badge).deliver
32         end
33
34         if user.notification_opts.badges_to_twitter
35           token = badge.name(user.language)
36           group_name = group.name
37           link = "http://" + group.domain # TODO: ssl
38
39           txt = I18n.t('jobs.base.create_badge.send_twitter', :link => link, :token => "##{token}", :group_name => "##{group_name}") # TODO: link the twitter account
40           user.twitter_client.update(txt)
41         end
42         if group.notification_opts.badges_to_twitter
43           token = badge.name(user.language)
44           group_name = group.name
45           link ||= "http://" + group.domain # TODO: ssl
46
47           txt = I18n.t('jobs.base.create_badge.group_send_twitter', :link => link,
48                        :token => "##{token}", :user => user.login,
49                        :group_name => "##{group_name}") # TODO: link the twitter account
50           group.twitter_client.update(txt)
51         end
52       end
53     end
54
55     def shorten_url(url, entry)
56       if entry.short_url.blank?
57         begin
58           link = open("http://bit.ly/api?url=#{CGI.escape(url)}").read
59           entry.override(:short_url => link)
60         rescue
61           link = url
62         end
63       else
64         link = entry.short_url
65       end
66       link
67     end
68
69     def make_status(text, link, limit)
70       "#{text[0..limit-link.size]} #{link}"
71     end
72   end
73 end
74