Created
November 30, 2012 20:35
-
-
Save cheald/4178415 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class PushService < AbstractController::Base | |
| include AbstractController::Rendering | |
| self.view_paths = "app/views" | |
| def self.publish(recipient_ids, json) | |
| recipients = RecipentClass.where(:id.in recipient_ids).all | |
| FayePublisher.new(recipients, json).publish | |
| GcmPublisher.new(recipients, json).publish | |
| end | |
| # Create a new event to push to connected browsers and Android devices | |
| # | |
| # @param [Symbol] type of change :create, :destroy ... | |
| # @param [ActiveRecord] record which has been created or updated | |
| def initialize(type, record) | |
| Rails.logger.info "[PushService] #{type} #{record.inspect}" | |
| @type = type | |
| @record = record | |
| end | |
| def publish | |
| PushService.delay.publish @record.recipients.map(&:id), json | |
| end | |
| private | |
| def json | |
| @_json ||= {klass: @record.class.to_s, type: type_as_json, id: @record.id, record: record_as_json } | |
| end | |
| def record_as_json | |
| case @type | |
| when :destroy | |
| nil | |
| when :update | |
| @record.changes.each_with_object({}) { |(k, v), h| h[k] = v.last } | |
| when :touch | |
| {updated_at: @record.updated_at} | |
| else | |
| ActiveSupport::JSON.decode(render_template) | |
| end | |
| end | |
| def type_as_json | |
| @type == :touch ? :update : @type | |
| end | |
| def render_template | |
| render_to_string(:partial => @record, :locals => { :message => @record }) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment