Class: Promiscuous::Publisher::Mock

Inherits:
Object
  • Object
show all
Includes:
Common::ClassHelpers
Defined in:
lib/promiscuous/publisher/mock.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMock

Returns a new instance of Mock.



35
36
37
38
# File 'lib/promiscuous/publisher/mock.rb', line 35

def initialize
  self.id = BSON::ObjectId.new
  self.new_record = true
end

Class Method Details

.class_nameObject



31
32
33
# File 'lib/promiscuous/publisher/mock.rb', line 31

def self.class_name
  self.klass ? self.klass : guess_class_name('Publishers')
end

.publish(options) ⇒ Object



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
# File 'lib/promiscuous/publisher/mock.rb', line 4

def self.publish(options)
  if defined?(attributes)
    if options[:attributes]
      raise "Do not specify the 'to' field in childrens" if options[:to]
      self.attributes = self.attributes + options[:attributes]
    end
  else
    class_attribute :to, :attributes, :klass

    self.to = options[:to]
    self.klass = options[:class]
    self.attributes = options[:attributes].to_a

    attr_accessor :id, :new_record
  end
  attr_accessor *attributes

  associations = attributes.map { |attr| $1 if attr =~ /^(.*)_id$/ }.compact
  associations.each do |attr|
    attr_accessor attr
    define_method("#{attr}=") do |value|
      instance_variable_set("@#{attr}", value)
      instance_variable_set("@#{attr}_id", value.nil? ? value : value.id)
    end
  end
end

Instance Method Details

#destroyObject



71
72
73
74
75
76
77
78
# File 'lib/promiscuous/publisher/mock.rb', line 71

def destroy
  Promiscuous::Subscriber.process(
    '__amqp__'  => self.class.to,
    'id'        => self.id,
    'type'      => self.class.class_name,
    'operation' => 'destroy'
  )
end

#payloadObject



55
56
57
58
59
60
61
62
63
# File 'lib/promiscuous/publisher/mock.rb', line 55

def payload
  {
    '__amqp__'  => self.class.to,
    'id'        => self.id,
    'type'      => self.class.class_name,
    'operation' => self.new_record ? 'create' : 'update',
    'payload'   => Hash[self.class.attributes.map { |attr| [attr.to_s, payload_for(attr)] }]
  }
end

#payload_for(attr) ⇒ Object



65
66
67
68
69
# File 'lib/promiscuous/publisher/mock.rb', line 65

def payload_for(attr)
  value = __send__(attr)
  value = value.payload if value.is_a?(Promiscuous::Publisher::Mock)
  value
end

#saveObject Also known as: save!



40
41
42
43
44
45
46
# File 'lib/promiscuous/publisher/mock.rb', line 40

def save
  if payload['__amqp__'].in? Promiscuous::Subscriber::AMQP.subscribers.keys
    Promiscuous::Subscriber.process(JSON.parse(payload.to_json))
  end
  self.new_record = false
  true
end

#update_attributes(attrs) ⇒ Object Also known as: update_attributes!



49
50
51
52
# File 'lib/promiscuous/publisher/mock.rb', line 49

def update_attributes(attrs)
  attrs.each { |attr, value| __send__("#{attr}=", value) }
  save
end