Sha256: d5217e3bdba85e70ee9e5467affbf71cb69442a18012c24aa73c66f9eb4a1327

Contents?: true

Size: 1.8 KB

Versions: 13

Compression:

Stored size: 1.8 KB

Contents

class ExvoAuth::Models::Message
  include ActiveModel::Validations
  include ActiveModel::Serialization
  
  class RecordInvalid < StandardError; end
  class RecordNotFound < StandardError; end
  
  validates :label,    :presence => true, :format => /^[_a-z0-9]+$/ix
  validates :text,     :presence => true
  validates :user_uid, :presence => true, :numericality => true

  attr_accessor :id, :label, :text, :user_uid, :created_at, :read
  
  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end
  
  def self.create(attributes = {})
    message = new(attributes)
    if message.valid?
      message.deliver
      message
    else
      raise RecordInvalid, message.errors.full_messages.join(", ")
    end
  end
  
  def self.all
    auth = ExvoAuth::Autonomous::Auth.instance
    response = auth.get("/api/private/app_messages.json")
    response.map{ |m| new(m) }
  end
  
  def self.find(id)
    auth = ExvoAuth::Autonomous::Auth.instance
    response = auth.get("/api/private/app_messages/#{id}.json")
    if response.code == 200
      new(response)
    else
      raise RecordNotFound, "Couldn't find #{model_name} with ID=#{id}"
    end
  end
  
  def deliver
    auth = ExvoAuth::Autonomous::Auth.instance
    attributes = {
      :label    => label,
      :text     => text,
      :user_uid => user_uid
    }
    response = auth.post("/api/private/app_messages.json", :body => attributes)
    case response.code
      when 201 then
        response.parsed_response.each do |k, v|
          send("#{k}=", v)
        end
      when 422 then
        response.parsed_response.each{ |attr, error| errors.add(attr, error) }
        raise RecordInvalid, errors.full_messages.join(", ")
      else
        raise "Unknown error"  
    end

  end
  
  def persisted?
    !!id
  end

end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
exvo-auth-0.14.0 lib/exvo_auth/models/message.rb
exvo-auth-0.13.0 lib/exvo_auth/models/message.rb
exvo-auth-0.12.2 lib/exvo_auth/models/message.rb
exvo-auth-0.12.1 lib/exvo_auth/models/message.rb
exvo-auth-0.12.0 lib/exvo_auth/models/message.rb
exvo-auth-0.11.2 lib/exvo_auth/models/message.rb
exvo-auth-0.11.1 lib/exvo_auth/models/message.rb
exvo-auth-0.11.0 lib/exvo_auth/models/message.rb
exvo-auth-0.10.4 lib/exvo_auth/models/message.rb
exvo-auth-0.10.3 lib/exvo_auth/models/message.rb
exvo-auth-0.10.2 lib/exvo_auth/models/message.rb
exvo-auth-0.10.1 lib/exvo_auth/models/message.rb
exvo-auth-0.10.0 lib/exvo_auth/models/message.rb