Guest User

Untitled

a guest
Apr 26th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 2.28 KB | None | 0 0
  1.  
  2. class BroadcastService
  3.  
  4.   # The content in the broadcast object will be broadcast to each feed in
  5.   # the feeds hash. Any communication failures will be flagged with an
  6.   # error message in the value of the corresponding feed in the feeds hash
  7.   # and false will be returned, otherwise true is returned
  8.   # Really this should be more OO and the case statement replaced by
  9.   # polymorphic calls. This is left to the reader as an exercise, but ideally
  10.   # you would want to make this a singleton rather than use class scope methods. The
  11.   # error handling mechanism is also a bit clunky and non-user friendly.
  12.   def self.broadcast(broadcast, feeds)
  13.     puts "feeds: #{feeds.inspect}"
  14.     result = []
  15.     feeds.each do |feed, value|
  16.       case feed
  17.       when "twitter"
  18.         result.concat(via_twitter(broadcast))
  19.       when "email"
  20.         result.concat(via_email(broadcast, feeds[:alumni_email]))
  21.       when "facebook"
  22.       when "RSS"
  23.       when "atom"
  24.       end
  25.     end
  26.     result
  27.   end
  28.  
  29.   private
  30.  
  31.   def self.via_email(broadcast, email_list)
  32.     # Iterate across all users sending an email to each.
  33.    
  34.     users = User.find(:all)
  35.    
  36.     users.each do |user|
  37.       NewsBroadcast.send_news(user, broadcast, email_list).deliver
  38.     end
  39.     add_feed broadcast, 'email'
  40.     return []
  41.   rescue => e
  42.     return [:feed => email_list, :code => 500, :message => e.message]
  43.   end
  44.  
  45.   def self.via_twitter(broadcast)
  46.     result = []
  47.     begin
  48.       # SINCE AUG 2010 TWITTER REQUIRES OAUTH, SO BASIC AUTH NO LONGER SUPPORTED.
  49.       # Now using two-legged OAuth authentication (see initializers/twitter.rb) to
  50.       # obtain an access token object
  51.       response = TWITTER_ACCESS_TOKEN.post('/statuses/update.json', { :status => broadcast.content })
  52.    
  53.       case response
  54.       when Net::HTTPSuccess
  55.         # Now wire up with the correct feed
  56.         add_feed broadcast, 'twitter'
  57.       else # Something went wrong
  58.         result = [:feed => 'twitter', :code => response.code, :message => response.message]
  59.       end
  60.     rescue => e
  61.       result = [:feed => 'twitter', :code => 500, :message => e.message]
  62.     end
  63.     result
  64.   end
  65.  
  66.   def self.add_feed(broadcast, feed_name)
  67.     feed = Feed.find_by_name(feed_name)
  68.     broadcast.feeds << feed if feed
  69.   end
  70. end
Add Comment
Please, Sign In to add comment