Module: Communicator::ActiveRecordIntegration::InstanceMethods

Defined in:
lib/communicator/active_record_integration.rb

Overview

Instance methods that are to be mixed in to receiver classes

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#updated_from_messageObject

Instance variable to store whether this instance has been updated from remote message



29
30
31
# File 'lib/communicator/active_record_integration.rb', line 29

def updated_from_message
  @updated_from_message
end

Instance Method Details

#process_message(input) ⇒ Object

Processes the given message body by applying all contained attributes and their values and saving. When the setter instance method is missing on the local record, skip that attribute.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/communicator/active_record_integration.rb', line 40

def process_message(input)
  Communicator.logger.info "Processing json message content on #{self.class} ##{id}"
  # When the input is still json, parse it. Otherwise we're assuming it's already a demarshalled hash
  input = JSON.parse(input) if input.kind_of?(String)
  input.each do |attr_name, value|
    # Exclude skipped attributes
    next if self.class.skipped_remote_attributes.include?(attr_name.to_sym) or !attributes.has_key?(attr_name)
    self.send("#{attr_name}=", value)
  end
  self.updated_from_message = true
  save!
  
rescue => err
  Communicator.logger.warn "Failed to process message on #{self.class} ##{id}! Errors: #{self.errors.map{|k,v| "#{k}: #{v}"}.join(", ")}"
  if err.respond_to?(:context)
    err.context["Validation Errors"] = "Errors: #{self.errors.map{|k,v| "#{k}: #{v}"}.join(", ")}"
    err.context["JSON Input"] = input.inspect
  end
  raise err
end

#publishObject

Publishes this instance as an OutboundMessage with json representation as body



32
33
34
35
36
# File 'lib/communicator/active_record_integration.rb', line 32

def publish
  msg = Communicator::OutboundMessage.create!(:body => {self.class.to_s.underscore => attributes}.to_json)
  Communicator.logger.info "Publishing updates for #{self.class} ##{id}"
  msg
end