PushbulletAgent moved device creation to a before_validation callback

This commit is contained in:
Dominik Sander 2015-02-24 20:26:31 +01:00
parent c7b4c4260f
commit 0b979dd1c0
3 changed files with 8 additions and 5 deletions

View file

@ -5,6 +5,8 @@ module Agents
cannot_be_scheduled!
cannot_create_events!
before_validation :create_device, on: :create
API_BASE = 'https://api.pushbullet.com/v2/'
TYPE_TO_ATTRIBUTES = {
'note' => [:title, :body],
@ -54,7 +56,7 @@ module Agents
def validate_options
errors.add(:base, "you need to specify a pushbullet api_key") if options['api_key'].blank?
create_device if options['device_id'].blank?
errors.add(:base, "you need to specify a device_id") if options['device_id'].blank?
errors.add(:base, "you need to specify a valid message type") if options['type'].blank? or not ['note', 'link', 'address'].include?(options['type'])
TYPE_TO_ATTRIBUTES[options['type']].each do |attr|
errors.add(:base, "you need to specify '#{attr.to_s}' for the type '#{options['type']}'") if options[attr].blank?
@ -105,6 +107,7 @@ module Agents
end
def create_device
return if options['device_id'].present?
safely do
response = request(:post, 'devices', basic_auth.merge(body: {nickname: 'Huginn', type: 'stream'}))
self.options[:device_id] = response['iden']

View file

@ -1,6 +1,6 @@
class AddTypeOptionAttributeToPushbulletAgents < ActiveRecord::Migration
def up
Agents::PushbulletAgent.all.each do |agent|
Agents::PushbulletAgent.find_each do |agent|
if agent.options['type'].nil?
agent.options['type'] = 'note'
agent.save!
@ -9,7 +9,7 @@ class AddTypeOptionAttributeToPushbulletAgents < ActiveRecord::Migration
end
def down
Agents::PushbulletAgent.all.each do |agent|
Agents::PushbulletAgent.find_each do |agent|
if agent.options['type'].present?
agent.options.delete 'type'
agent.save(validate: false)

View file

@ -35,8 +35,7 @@ describe Agents::PushbulletAgent do
it "should try do create a device_id" do
@checker.options['device_id'] = nil
mock(@checker).create_device
expect(@checker).to be_valid
expect(@checker).not_to be_valid
end
it "should require fields based on the type" do
@ -142,6 +141,7 @@ describe Agents::PushbulletAgent do
stub_request(:post, "https://token:@api.pushbullet.com/v2/devices").
with(:body => "nickname=Huginn&type=stream").
to_return(:status => 200, :body => '{"iden": "udm0Tdjz5A7bL4NM"}', :headers => {})
@checker.options['device_id'] = nil
@checker.send(:create_device)
expect(@checker.options[:device_id]).to eq('udm0Tdjz5A7bL4NM')
end