exception_notification for delayed_job - ruby-on-rails

Is there a exception_notification-like gem for delayed_job?
Preferably that works with REE-1.8.7 and Rails 2.3.10.

I've done something like this in the past for delayed job rake tasks:
require 'action_mailer'
class ExceptionMailer < ActionMailer::Base
def setup_mail
#from = ExceptionNotifier.sender_address
#sent_on = Time.now
#content_type = "text/plain"
end
def exception_message(subject, message)
setup_mail
#subject = subject
#recipients = ExceptionNotifier.exception_recipients
#body = message
end
end
namespace :jobs do
desc "sync the local database with the remote CMS"
task(:sync_cms => :environment) do
Resort.sync_all!
result = Delayed::Job.work_off
unless result[1].zero?
ExceptionMailer.deliver_exception_message("[SYNC CMS] Error syncing CMS id: #{Delayed::Job.last.id}", Delayed::Job.last.last_error)
end
end
end

Include this module in classes which are to be delayed:
require 'exception_notifier'
module Delayed
module ExceptionNotifier
# Send error via exception notifier
def error(job, e)
env = {}
env['exception_notifier.options'] = {
:sections => %w(backtrace delayed_job),
:email_prefix => '[Delayed Job ERROR] ',
:exception_recipients => %w(some#email.com),
:sender_address => %(other#email.com)
}
env['exception_notifier.exception_data'] = {:job => job}
::ExceptionNotifier::Notifier.exception_notification(env, e).deliver
end
end
end
and create a template for the notification in app/views/exception_notifier/_delayed_job.text.erb:
Job name: <%= #job.name %>
Job: <%= raw #job.inspect %>
* Process: <%= raw $$ %>
* Server : <%= raw `hostname -s`.chomp %>

Related

Issue with rails mailer and rake task

If an agent hasn't been verified, I want one email to be generated and sent to me with all of their names. Not sure where I went wrong.
agent_card_mailer.rb
class AgentCardMailer < ActionMailer::Base
default from: "Help <help#email.com>"
def not_verified_message(agent_card)
#agent_card = agent_card
mail(:to => "me#email.com", :subject => "Agent License Issues")
end
end
not_verified_message.html.erb
Hi there,<br><br>
These agents have not been verified.<br><br>
<% #agent_cards.each do |agent_card| %>
<%= agent_card.agent.name %><br>
<% end %>
issue_with_license.rake
namespace :agent_cards do
desc 'Send out weekly email for agents with issues'
task remind_license_issues: :environment do
AgentCard.all.each do |agent_card|
if agent_card.verified == false
AgentCardMailer.not_verified_message(agent_card).deliver_now
end
end
end
end
error:
ActionView::Template::Error: undefined method `each' for nil:NilClass
Your mailer is setting the attribute #agent_card but the template is looking for the plural #agent_cards

Rails scheduled SMS sender

I want send an SMS each 5 minutes to my users. At the moment, my application sends an SMS during the creation of an account.
# users_controller.rb
def create
#user = User.new(user_params)
if #user.save
#user.send_activation_email
#user.send_daily_sms
flash[:info] = "Veuillez contrôler votre boîte mail pour activer votre compte."
redirect_to root_url
else
render 'new'
end
end
# user.rb
def send_daily_sms
# put your own credentials here
account_sid = '**********************'
auth_token = '**********************'
# set up a client to talk to the Twilio REST API
#client = Twilio::REST::Client.new account_sid, auth_token
#client.account.messages.create({
:from => '**********',
:to => '***********',
:body => 'Salut',
})
end
I already have scheduled mails working in my project by doing this :
# schedule.rb
every :day, :at => '12pm' do
rake "email_sender_daily"
end
# My task
task :email_sender_daily => :environment do |_, args|
User.find_each do |user|
UserMailer.daily_mail(user).deliver_now if user.daily == true
end
end
# My UserMailer
def daily_mail(user)
#user = user
mail to: user.email, subject: "Mail journalier"
end
I'm showing you this because, with the UserMailer, I know how to access it from an other file. Here, I'd like to do the exactly the same for SMS, but how can I access the method that is in my Model ? If not, where can I put this method to be able to access it from my rake task ?
Twilio developer evangelist here.
It looks to me like you have all the parts you need. If send_daily_sms is a method in your User class then all you require is a rake task like so:
task :sms_sender_daily => :environment do |_, args|
User.find_each do |user|
user.send_daily_sms if user.daily == true
end
end
And then your schedule.rb would look like:
every :day, :at => '12pm' do
rake "email_sender_daily"
rake "sms_sender_daily"
end
I would warn that sending sms messages to all your users via one method that calls the API over and over again is somewhat fragile. If one message fails to send because of a timeout or some other error then the task will throw an error and not be able to complete sending all the messages.
I'd suggest sending both emails and sms messages by workers using a background queue, like Rails's ActiveJob. If you are on the latest Rails 4.2 then you can use a gem called Textris that works much like ActionMailer and then you could define a UserTexter class like this:
class UserTexter < Textris::Base
default :from => YOUR_NUMBER
def daily_sms(user)
#user = user
text :to => #user.phone_number
end
end
Then your tasks could look like this:
task :email_sender_daily => :environment do |_, args|
User.find_each do |user|
UserMailer.daily_mail(user).deliver_later if user.daily == true
end
end
task :sms_sender_daily => :environment do |_, args|
User.find_each do |user|
UserTexter.daily_sms(user).deliver_later if user.daily == true
end
end
Check out the Textris documentation for more on how to use the gem.
Let me know if this helps at all!

Ruby websocket client for websocket-rails gem

I am developing a rails webpage which need to use websocket functionality to communicate with an external ruby client. In order to do this, I am using the websocket-rails gem in the rails server, definning the client_connected client_disconnected event and a specific action to received the messages from the client (new_message).
On the client side I have tried to use different ruby gems like faye-websocket-ruby and websocket-client-simple but I always obtain errors when I try to send a message. On the server I can't find the way to process these messages. Both gems has a send method with only accepts a string (not being able to specify the name of the event)
The code that I have been using is the following:
Server side
app/controllers/chat_controller.rb
class ChatController < WebsocketRails::BaseController
def new_message
puts ')'*40
end
def client_connected
puts '-'*40
end
def client_disconnected
puts '&'*40
end
end
config/events.rb
WebsocketRails::EventMap.describe do
subscribe :client_connected, :to => ChatController, :with_method => :client_connected
subscribe :message, :to => ChatController, :with_method => :new_message
subscribe :client_disconnected, :to => ChatController, :with_method => :client_disconnected
end
config/initializers/websocket_rails.rb
WebsocketRails.setup do |config|
config.log_path = "#{Rails.root}/log/websocket_rails.log"
config.log_internal_events = true
config.synchronize = false
end
Client side
websocket-client-simple
require 'rubygems'
require 'websocket-client-simple'
ws = WebSocket::Client::Simple.connect 'ws://localhost:3000/websocket'
ws.on :message do |msg|
puts msg.data
end
ws.on :new_message do
hash = { channel: 'example' }
ws.send hash
end
ws.on :close do |e|
p e
exit 1
end
ws.on :error do |e|
p e
end
hash = { channel: 'Example', message: 'Example' }
ws.send 'new_message', hash
loop do
ws.send STDIN.gets.strip
end
faye-websocket
require 'faye/websocket'
require 'eventmachine'
EM.run {
ws = Faye::WebSocket::Client.new('ws://localhost:3000/websocket')
ws.on :open do |event|
p [:open]
end
ws.on :message do |event|
p [:message, event.data]
end
ws.on :close do |event|
p [:close, event.code, event.reason]
ws = nil
end
ws.send( 'Example Text' )
}
Thanks in advance. Regards.
PD: Let me know if you need more code.
Finally I have found the solution. The problem was that the message needs to be constructed with a certain format in order to be understood by websocket-rails.
Example: ws.send( '["new_message",{"data":"Example message"}]' )
where new_message is the event which websocket-rails is listening to.

Custom Helper with alias_method_chain on Ruby on Rails in development mode [REDMINE]

I would like to custom the method link_to_issue of the application_helper of Redmine with the principle of the alias_method_chain in order to keep the Redmine code clean in a plugin but I encounter a problem.
First of all, here is the patch file, application_helper_patch.rb :
require_dependency 'application_helper'
module ApplicationtHelperPatch
def self.included(base) # :nodoc:
base.send(:include, InstanceMethods)
base.class_eval do
unloadable
alias_method_chain :link_to_issue, :custom_show
end
end
module InstanceMethods
def link_to_issue_with_custom_show(issue, options={})
title = nil
subject = nil
if options[:subject] == false
title = truncate(issue.subject, :length => 60)
else
subject = issue.subject
if options[:truncate]
subject = truncate(subject, :length => options[:truncate])
end
end
s = link_to "#{h subject}", {:controller => "issues", :action => "show", :id => issue},
:class => issue.css_classes,
:title => title
s = "#{h issue.project} - " + s if options[:project]
end
end
end
And the init.rb of the plugin :
require 'redmine'
require 'application_helper_patch'
Dispatcher.to_prepare do
ApplicationHelper.send(:include, ApplicationtHelperPatch) unless ApplicationHelper.included_modules.include? ApplicationtHelperPatch
end
Redmine::Plugin.register :redmine_dt_capture do
name 'my plugin'
author 'Remi'
description 'This is a plugin for Redmine'
version '0.0.1'
permission :dt, :public => true
menu :top_menu,
:dt,
{ :controller => 'my_controller', :action => 'index' },
:caption => ' my_plugin '
if RAILS_ENV == 'development'
ActiveSupport::Dependencies.load_once_paths.reject!{|x| x =~ /^#{Regexp.escape(File.dirname(__FILE__))}/}
end
This solution runs perfectly in production mode, but no in development mode. When I launch the application I encounter this problem :
NoMethodError in Issues#show
Showing app/views/issues/show.html.erb where line #47 raised:
undefined method `call_hook' for #<ActionView::Base:0x6b8b750>
Extracted source (around line #47):
Why does the method call_hook is undefined in development mode ?
Thanks
Try more conventional way to add patch, may be this will resolve your issue.
put your patch in your_plugin/lib/plugin_name/patches/
and application_helper_patch.rb will become like this
require_dependency 'application_helper'
module PluginName
module Patches
module ApplicationtHelperPatch
def self.included(base) # :nodoc:
base.send(:include, InstanceMethods)
base.class_eval do
unloadable
alias_method_chain :link_to_issue, :custom_show
end
end
module InstanceMethods
def link_to_issue_with_custom_show(issue, options={})
title = nil
subject = nil
if options[:subject] == false
title = truncate(issue.subject, :length => 60)
else
subject = issue.subject
if options[:truncate]
subject = truncate(subject, :length => options[:truncate])
end
end
s = link_to "#{h subject}", {:controller => "issues", :action => "show", :id => issue},
:class => issue.css_classes,
:title => title
s = "#{h issue.project} - " + s if options[:project]
end
end
end
end
end
And the init.rb of the plugin :
require 'redmine'
require 'application_helper_patch'
Dispatcher.to_prepare do
ApplicationHelper.send(:include, PluginName::Patches::ApplicationtHelperPatch) unless ApplicationHelper.included_modules.include? PluginName::Patches::ApplicationtHelperPatch
end
Redmine::Plugin.register :redmine_dt_capture do
name 'my plugin'
author 'Remi'
description 'This is a plugin for Redmine'
version '0.0.1'
permission :dt, :public => true
menu :top_menu,
:dt,
{ :controller => 'my_controller', :action => 'index' },
:caption => ' my_plugin '
if RAILS_ENV == 'development'
ActiveSupport::Dependencies.load_once_paths.reject!{|x| x =~ /^#{Regexp.escape(File.dirname(__FILE__))}/}
end

Ruby script not running when Process.daemon is added

I have the following simple script, which checks an email account and if there is new mail it forwards the email and sends an SMS. This happens as expected when the script is run without Process.daemon. When it is added, and email is received at the email account, nothing happens (nothing is forwarded and no SMS is sent) and there are no error messages in the console. Any suggestions?
#!/usr/bin/env ruby
require "bundler/setup"
require "mailman"
require "twilio-ruby"
Mailman.config.pop3 = {
:username => 'address#gmail.com',
:password => 'password',
:server => 'pop.gmail.com',
:port => 995,
:ssl => true
}
Mailman.config.poll_interval = 60
Mailman::Application.run do
default do
begin
Ticket.receive_mail(message)
MailForwarder.forwarded_email(message).deliver
#account_sid = 'xxxxxxxxxxx'
#auth_token = 'xxxxxxxxxx'
#client = Twilio::REST::Client.new(#account_sid, #auth_token)
#account = #client.account
#sms = #account.sms.messages.create(
:from => '+1111111111',
:to => '+122222222',
:body => message.subject
)
puts #sms
puts "#{message.subject}"
rescue Exception => e
Mailman.logger.error "Exception occurred whle receiving message:\n#{message}"
Mailman.logger.error [e, *e.backtrace].join("\n")
end
end
Process.daemon
end
I believe you need to set up your script as a daemon before you start up the mailman application. I did a bit of testing, and it worked fine if I called Process.daemon before calling the Mailman::Application.run but it didn't work if I put it where you had it.
So I had it as:
....
Mailman.config.poll_interval = 15
Process.daemon
Mailman::Application.run do
default do
end
end

Resources