I am building a simple web app that sends SMS messages to cell phones using Twilio. I want to ensure that the user has entered a full 10 digit phone number before it will allow a message to attempt to be sent.
When I test it with a less-than or greater-than 10 digit number, in heroku logs, I see Twilio::REST::RequestError (The 'To' number 1234567890 is not a valid phone number.).
I have tried to use a begin/rescue wrapper and am telling it to render text: "Try again with a valid number." and tried a variety of if statements to try to avoid the error.
I am pretty new to Ruby and Rails and Twilio, but I promise i have been through every guide I have found. Any help is greatly appreciated. Full code of my UserController below:
require 'twilio-ruby'
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user])
account_sid = '...'
auth_token = '...'
if #user.save
render text: "Wasn't that fun? Hit the back button in your browser to give it another go!"
begin
client = Twilio::REST::Client.new account_sid, auth_token
client.account.sms.messages.create(
from: '+16035093259',
to: #user.phone,
body: #user.message
)
rescue Twilio::REST::RequestError
render text: "Try again with a valid number."
end
else
render :new
end
end
end
I'd extract the SMS sending logic into a separate model/controller and use a background job to process the submitting. The UserController should only handle, well, user creation/modification.
Scaffolding:
$ rails g model sms_job user:references message:text phone submitted_at:datetime
$ rake db:migrate
Model:
class SmsJob < AR::Base
attr_accessible :user_id, :message, :phone
belongs_to :user
validates_presence_of :message, :phone, :user_id
validates :phone,
length: { min: 10 },
format: { with: /\+?\d+/ }
scope :unsubmitted, where(submitted_at: nil)
TWILIO = {
from_no: '...',
account_sid: '...',
auth_token: '...'
}
# find a way to call this method separately from user request
def self.process!
unsubmitted.find_each do |job|
begin
client = Twilio::REST::Client.new TWILIO[:account_sid], TWILIO[:auth_token]
client.account.sms.messages.create(
from: TWILIO[:from_no],
to: job.phone,
body: job.message
)
job.submitted_at = Time.zone.now
job.save
rescue Twilio::REST::RequestError
# maybe set update a tries counter
# or delete job record
# or just ignore this error
end
end
end
end
The controller then should just provide the information that the SMS is going to be send:
# don't forget the 'resources :sms_jobs' in your routes.rb
class SmsJobsController < ApplicationController
# index, update, destroy only for only admin?
def new
#sms_job = SmsJobs.new
end
def create
#sms_job = current_user.sms_jobs.build params[:sms_job]
if #sms_job.save
redirect_to root_url, notice: "Your message is being send!"
else
render :new
end
end
end
For the background processing, have a look at these excellent Railscasts :-) You probably need to workaround some concurrency problems if you have to process many messages and/or Twilio has a long response time (didn't use that service yet).
Related
I am using Mailchimp (via the Gibbon gem) to add email addresses to my Mailchimp mailing list, and I want to handle any errors that are returned by Mailchimp and display them in my view.
Here is my Pages controller:
class PagesController < ApplicationController
def subscribe
email = subscriber_params[:email]
if email.empty?
flash[:error] = 'Please provide an email.'
redirect_to root_path
else
subscriber = Mailchimp.new.upsert(email)
if subscriber
flash[:success] = 'You\'re in!'
redirect_to root_path(subscribed: :true)
else
# Return error coming from Mailchimp (i.e. Gibbon::MailChimpError)
end
end
end
end
And here is the app > services > mailchimp.rb file I set up to separate out the Mailchimp logic:
class Mailchimp
def initialize
#gibbon = Gibbon::Request.new(api_key: Rails.application.credentials.mailchimp[:api_key])
#list_id = Rails.application.credentials.mailchimp[:list_id]
end
def upsert(email)
begin
#gibbon.lists(#list_id).members.create(
body: {
email_address: email,
status: "subscribed"
}
)
rescue Gibbon::MailChimpError => e #This is at the bottom of the Gibbon README
raise e.detail
end
end
end
What I'm trying to figure out is how to return/send Gibbon::MailChimpError back to my Pages#subscribe action. I see it being outputted as a RuntimeError in my console, but I'm not sure the right way to access/pass it along.
And please let me know if there's a better practice for this kind of implementation.
You could move the begin/rescue block to the subscribe action inside your controller to handle the error from there, or even better, you can use rescue_from in your controller like this:
class PagesController < ApplicationController
rescue_from Gibbon::MailChimpError do |e|
# Handle the exception however you want
end
def subscribe
# ....
end
end
before I ask the question I want to give a little background on the models. I have a user_conversation model(through table) which accepts attributes from conversations and messages models. The create action and before action are given below.
before_action :logged_in_user
before_action :validate_conversation, only: :create
def create
redirect_to home_path unless current_user
#conversation = UserConversation.new conversation_params
#conversation.user = current_user
#conversation.conversation.messages.first.user = current_user
#conversation.save!
activate_unread
redirect_to user_conversation_path(current_user,#conversation)
end
Private
def validate_conversation
#user = User.find params[:user_id]
if params[:user_conversation][:conversation_attributes]["subject"].blank?
redirect_to new_user_conversation_path(#user)
flash[:danger] = "Subject cannot be blank"
else params[:user_conversation][:conversation_attributes][:messages_attributes]["0"]["body"].blank?
redirect_to new_user_conversation_path(#user)
flash[:danger] = "Message cannot be blank"
end
end
def conversation_params
params.require(:user_conversation).permit(:recipient_id, conversation_attributes: [:subject, messages_attributes: [:body]])
end
I was trying to write an integration tests for the post request of user_conversation. The test is given below.
require 'test_helper'
class ConversationCreateTest < ActionDispatch::IntegrationTest
def setup
#user = users(:user_a)
#conversation = conversations(:convo_one)
end
test "invalid creation of a user conversation no subject" do
log_in_as(#user)
get new_user_conversation_path(#user)
post user_conversations_path(#user), user_conversation: {:recipient_id => #user.id, :conversation_attributes => {:subject => "this is a subject",
:message_attributes => {"0" => {:body => "sending a message"}}}}
end
I get the following error message when I run the command.
1) Error:
ConversationCreateTest#test_invalid_creation_of_a_user_conversation_no_subject:
NoMethodError: undefined method `[]' for nil:NilClass
app/controllers/user_conversations_controller.rb:63:in `validate_conversation'
test/integration/conversation_create_test.rb:13:in `block in <class:ConversationCreateTest>'
191 runs, 398 assertions, 0 failures, 1 errors, 0 skips
I have been trying to debug the problem for about 2 hours. I have checked the test log files and it says internal server error 500. I have tried commenting certain lines of codes to narrow down the problem but not really sure what the problem is. Any help would be appreciated.
In rails, validations are made with the ActiveModel::Validators.
So you can simply validate your model like this:
User:
class User
has_many :conversations, through: "user_conversations"
end
Conversation:
class Conversation
has_many :users, through: "user_conversations"
validates_presence_of :subject, :messages
end
See more here about validations
So if you then need to validate your model you can call:
conversation = Conversation.create(subject: nil)
conversation.errors.full_messages # => ["Subject can't be blank"]
I think you'll need to rewrite a bunch of things in your app, and if you took the code above you can simply test this thing within a model (unit) test.
Which, by the way, is no longer needed because you don't want to test the rails provided validators. You probably just want to test your own validators.
I like to send mails such that my JobNotifier/Mailer iterates through the Subscriber's Email List and call deliver "n" times, if that could be the solution to my problem.
Unfortunately, all I have done sends Emails Messages and expose the email addresses of every user to the recipients, which is not suppose to be.
Here are my codes
create method right inside my jobs_controller.rb
def create
#job = Job.new(job_params)
if #job.save
# Deliver the Posted Job
JobNotifier.send_post_email(#job).deliver
redirect_to preview_job_path(#job)
else
render :new
end
end
app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default to: Proc.new { User.pluck(:email).uniq },
from: 'FarFlungJobs <no-reply#farflungjobs.com>'
layout 'mailer'
end
app/mailers/job_notifier.rb
class JobNotifier < ApplicationMailer
def send_post_email(job)
#jobs = job
mail( :subject => 'New job posted on FarFlungJobs'
)
end
end
test/mailers/preview/job_notifier_preview.rb
# Preview all emails at http://localhost:3000/rails/mailers/job_notifier
class JobNotifierPreview < ActionMailer::Preview
def send_post_email
user = User.all
JobNotifier.send_post_email(user)
end
end
Tried to hop on my browser to test my Mailer using the URL shown below to preview/test my mailer:
http://localhost:3000/rails/mailers/job_notifier/send_post_email
Outcome of my test is this image below (at least if needed to help me with my problem):
Am using Rails
4.2.1
You have to send the email to each user separately. It will take much longer but it won't show other user's emails.
So in your controller, you will have something like this:
def create
#job = Job.new(job_params)
if #job.save
User.pluck(:email).uniq.each do |email|
# Deliver the Posted Job
JobNotifier.send_post_email(#job, email).deliver
end
redirect_to preview_job_path(#job)
else
render :new
end
end
Or you could put the loop inside the mailer
Edit:
You'll need to change your mailer to be able to handle extra argument:
class JobNotifier < ApplicationMailer
def send_post_email(job, email)
#jobs = job
mail(:to => email :subject => 'New job posted on FarFlungJobs')
end
end
I am trying to setup a system where if User A is reading a status from User B and clicks 'I'm interested' it will send a pre default message to User B's inbox (create new record in the Message table). This is sort of like on social networks where users sends a 'wink' to another user. I was able to do a similar setup for another section on the app that works, but I can't get this 'wink' feature to work. After the user clicks 'I'm interested', that link should no longer be available to the user for that status. I get a undefined method 'interested= error.
Intrigued Controller:
def create
#intrigue = current_user.intrigues.build(intrigue_params)
end
def destroy
#intrigue.destroy
end
def repost
#intrigue = Intrigue.find(params[:id]).repost(current_user)
end
#Need help with below code
def interested
#intrigue = User.find(params[:id])
#message = Message.create(:subject => "#{user_id} is Interested in you",
:sender_id => #user_id,
:recipient_id => #intrigue.user_id,
:body => "I saw your date and I'm interested")
#intrigue.message = #message
render :new, alert: 'Your message was sent.'
end
Routes:
resources :intrigues do
member do
post :repost
post :interested
end
end
I added has_one :intrigue to the Message model.
I added belongs_to :message to the Intrigue model.
The intrigues table has the following columns: id, content, user_id
The messages table has the following columns: id, sender_id, recipient_id, subject, body
Remove the line #intrigue.message = #message
Your sender id and recipient id are incorrect also.
def interested
#intrigue = User.find(params[:id])
#intrigue = current_user
#recipient = Intrigue.find(params[:id])
#message = Message.create(:subject => "Someone is Interested in you",
:sender_id => #intrigue.id,
:recipient_id => #recipient.user_id,
:body => "I saw your date and I'm interested")
render :new, alert: 'Your message was sent.'
end
That will have it working with no errors. I would also add a redirect.
I have created a Ruby on Rails application where users can track workouts. The can do so either privately or publicly. On workouts which are public ( workout.share == 1 ) I allow users to comment. When a comment is created on a workout, the workout owner is notified via email. That all works great.
I am now looking for some advice on the best way to allow users who have commented on a workout, to also be notified via email. Here is an example.
User A creates Workout 1. User B comments on Workout 1 and User A receives an email notification. User C also comments on Workout 1 and both User A and User B receive email notifications.
What is the best way to tell my application to loop through all the users who have commented on Workout 1 and send an email to them?
Currently I am sending an email to the workout owner with the following code in the comments_controller (I realize this could be cleaner code):
class CommentsController < ApplicationController
...
def create
#workout = Workout.find(params[:workout_id])
#comment = #workout.comments.build(params[:comment])
#comment.user = current_user
respond_to do |format|
if #comment.save
if #comment.workout.email_notification == 1
#comment.deliver_comment_notification_mail!
format.html { redirect_to( projects_path) }
format.js
else
format.html { redirect_to( projects_path) }
format.js
end
else
end
end
end
...
and in comment_mailer.rb
def comment_notification_mail(comment)
subject "Someone commented on your Workout"
recipients("#{comment.workout.user.username} <#{comment.workout.user.email}>")
from("foobar")
body :comment => comment,
:commenter => comment.user,
:workout => comment.workout,
:commentee => comment.workout.user,
:workout_url => workout_url(comment.workout),
:commenter_url => user_url(comment.user)
end
To find out a workout owner and commenter is not a hard job. My suggestions are:
move the code of sending email in your controller to your model, using #after_create, eg:
class Comment < ActiveRecord::Base
#...
after_create :notify_subscribers
def subscribers
(self.workout.commenters << self.workout.owner).uniq
end
def notify_subscribers
#... implemented below
end
end
using delayed_job or other tools to put the email sending job to background, or the request would be blocked until all the emails has been sent. eg, in the #notify_owner_and_commenter method
def notify_subscribers
self.subscribers.each do |user|
CommentMailer.send_later :deliver_comment_notification_mail!(self, user)
end
end
Then you need to refactor you #deliver_comment_notification_mail! method with two arguments.
Delayed job ref: https://github.com/tobi/delayed_job
From my POV, it's all the work of the mailer. I'd just rewrite the comment_notification_mail to something more neutral (which could speak to workout owner and commenters).
Then something like:
def comment_notification_mail(comment)
recs = [comment.workout.user]
recs << comment.workout.comments(&:user)
recs -= comment.user
subject "Someone commented on your Workout"
recipients(recs.inject('') { |acc, r| "#{r.username} <#{r.email}>" })
from("foobar")
body :comment => comment,
:commenter => comment.user,
:workout => comment.workout,
:commentee => comment.workout.user,
:workout_url => workout_url(comment.workout),
:commenter_url => user_url(comment.user)
end
Of course, if mails are not supposed to be public, send by bcc ;)