Class: Pushr::Message

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/pushr/message.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Message

Returns a new instance of Message.



8
9
10
11
12
# File 'lib/pushr/message.rb', line 8

def initialize(attributes = {})
  attributes.each do |name, value|
    send("#{name}=", value) if respond_to?("#{name}=")
  end
end

Instance Attribute Details

#appObject

Returns the value of attribute app.



5
6
7
# File 'lib/pushr/message.rb', line 5

def app
  @app
end

#external_idObject

Returns the value of attribute external_id.



5
6
7
# File 'lib/pushr/message.rb', line 5

def external_id
  @external_id
end

#typeObject

Returns the value of attribute type.



5
6
7
# File 'lib/pushr/message.rb', line 5

def type
  @type
end

Class Method Details

.create(attributes = {}) ⇒ Object



23
24
25
26
27
# File 'lib/pushr/message.rb', line 23

def self.create(attributes = {})
  m = new(attributes)
  m.save
  m
end

.create!(attributes = {}) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/pushr/message.rb', line 29

def self.create!(attributes = {})
  m = new(attributes)
  unless m.save
    raise Pushr::Error::RecordInvalid
  end
  m
end

.instantiate(message) ⇒ Object



48
49
50
51
52
53
# File 'lib/pushr/message.rb', line 48

def self.instantiate(message)
  return nil unless message
  hsh = ::MultiJson.load(message)
  klass = hsh['type'].split('::').reduce(Object) { |a, e| a.const_get e }
  klass.new(hsh)
end

.next(queue_name, timeout = 3) ⇒ Object



41
42
43
44
45
46
# File 'lib/pushr/message.rb', line 41

def self.next(queue_name, timeout = 3)
  Pushr::Core.redis do |conn|
    message = conn.blpop(queue_name, timeout: timeout)
    return instantiate(message[1]) if message
  end
end

Instance Method Details

#saveObject



14
15
16
17
18
19
20
21
# File 'lib/pushr/message.rb', line 14

def save
  if valid?
    Pushr::Core.redis { |conn| conn.rpush("pushr:#{app}:#{self.class::POSTFIX}", to_json) }
    return true
  else
    return false
  end
end

#to_jsonObject



37
38
39
# File 'lib/pushr/message.rb', line 37

def to_json
  MultiJson.dump(to_hash)
end