Devise Invitable optional custom message - devise

I would like to add an optional text_field to add an optional message to the invitation email. So if nothing put into the message then the standard message from invitation_instructions.html.erb should be send otherwise the message of the text_field.
How to do this in devise?

To accomplish this you can use your own mailer instead of having devise email things for you.
Here is how to do it:
class User < ActiveRecord::Base
attr_reader :raw_invitation_token
end
class InvitationsController < Devise::InvitationsController
def create
#from = params[:from]
#subject = params[:invite_subject]
#content = params[:invite_content]
#user = User.invite!(params[:user], current_user) do |u|
u.skip_invitation = true
end
#user.deliver_invitation
email = NotificationMailer.invite_message(#user, #from, #subject, #content)
end
end
class NotificationMailer < ActionMailer::Base
def invite_message(user, venue, from, subject, content)
#user = user
#token = user.raw_invitation_token
invitation_link = accept_user_invitation_url(:invitation_token => #token)
mail(:from => from, :bcc => from, :to => #user.email, :subject => subject) do |format|
content = content.gsub '{{first_name}}', user.first_name
content = content.gsub '{{last_name}}', user.first_name
content = content.gsub '{{full_name}}', user.full_name
content = content.gsub('{{invitation_link}}', invitation_link)
format.text do
render :text => content
end
end
end
end
The raw_invitation_token only exists in newer versions of devise_invitable (compatible with devise >= 3.1).
We are essentially skipping the devise invitation process all together and using our own mailer. We take the content as a parameter and send it as the body of the email. We even substitute placeholders with their actual values.
This solution will give you a lot of flexibility to whatever you want with emails. You can even add a tracking pixel to it if you would like.

Related

Using Twilio in Rails 4 - Uninitialized Constant Error

I am trying to integrate Twilio with my Rails 4 app. I followed a tutorial, but I keep getting an error. Right now I am getting an Uninitialized Constant Error. I provided the code below. Thanks in advance.
Routes.rb
get '/share_over_sms' => 'listing_collections#share_over_sms'
Listing Collection Model
require "messenger"
def clean_number
client_number = self.client_number.scan(/\d+/).join
client_number[0] == "1" ? client_number[0] = '' : client_number
client_number unless client_number.length != 10
end
Messenger Module
module Messenger
def send_sms(number)
twilio_sid = "ENV['TWILIO_ACCOUNT_SID']"
twilio_token = "ENV['TWILIO_AUTH_TOKEN']"
#twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token
from = '+1xxxxxxxxxx'
message = #twilio_client.account.sms.messages.create(
:from => from,
:to => "+1"+number,
:body => "This is a test message."
)
end
end
Listing Collections Controller
def share_over_sms
#client_phone = ClientPhone.new(listing_collection_params)
#client_phone.send_sms(#client_phone.clean_number)
redirect_to :back
end

Process form data before creating table entry

Backstory: I'm building a site that takes in a Soundcloud URL as part of a post. Currently, I store the link they provide and, when a user loads their feed view, I retrieve the associated image / title / favorite count etc. via my post_helper. I have quickly come to realize that this is not scalable and is hurting load times.
So, what I think I should do (feel free to tell me that there is a better way), is to retrieve the SC/YT metadata on form submit and store it along with the other post data (id, user, content etc.) in the posts' table entry. How would I go about calling the helper methods to retrieve such on form submit and include the metadata in the submitted params?
post_helper.rb excerpt:
def soundcloud_info(soundcloud_url, type)
begin
resolve = scClient.get('/resolve', :url => soundcloud_url)
track_info = scClient.get("/tracks/#{resolve.id}")
rescue Soundcloud::ResponseError => e
%Q{ Error: #{e.message}, Status Code: #{e.response.code} }
end
if type == "title"
%Q{#{track_info['title']}}
elsif type == "image"
%Q{#{track_info['artwork_url']}}
elsif type == "favCount"
%Q{Favorite count: #{track_info['favoritings_count']}}
end
end
post_controler.rb excerpt:
def create
#post = current_user.posts.build(params[:post])
if #post.save
flash[:success] = "Your post was successful!"
redirect_to root_url
else
#feed_items = current_user.feed.paginate(page: params[:page])
render 'static_pages/home'
end
end
So apparently it's pretty straight forward... all I need to do is modify the parameters in the controller before I call #post = current_user.posts.build(params[:post]). My issue was that I was trying to do so in the helper.
I haven't quite adapted the whole thing to get all my required fields, but here's an example of how I have adapted the create method to pull the api URL out if someone submits SoundCloud's embed iframe.
micropost_controller.rb excerpt:
def create
#url = params[:post][:link_html]
if #url[/^.*src="(https|http):\/\/w.soundcloud.com\/player\/\?url=(.*)">/]
params[:post][:link_html] = CGI::unescape($2)
end
#post = current_user.posts.build(params[:post])
if #post.save
flash[:success] = "Your post was successful!"
redirect_to root_url
else
#feed_items = current_user.feed.paginate(page: params[:page])
render 'static_pages/home'
end
end

How to make tests with find and date conditions?

I'm trying to develop some tests for a method which is responsible for retrieve some users created after some date. I don't know how to mock tests for it. The method is the following:
def user_list
render :nothing => true, :status => 422 if params[:time_param].blank?
time = Time.parse(params[:time_param])
#users = User.find(:all, :select => 'id, login, email',
:conditions => ["created_at > ?", time])
render :json => { :users => #users }
end
end
This is my spec:
describe UsersController do
context "when receiving time parameter" do
before (:each) do
#time_param = "2013-01-25 00:01:00"
user1 = mock_model(User, :created_at => Time.parse('2013-01-25 00:00:00'))
user2 = mock_model(User, :created_at => Time.parse('2013-01-25 00:01:00'))
user3 = mock_model(User, :created_at => Time.parse('2013-01-25 00:02:00'))
#users = []
#users << user1 << user2 << user3
end
it "should retrieve crimes after 00:01:00 time" do
User.stub(:find).with(:all, :select => 'id, login, email').and_return(#users)
get :user_list, { :time_param => #time_param }
JSON.parse(response.body)["users"].size.should eq 1
end
end
end
The problem is that it always returns all users despite of returning just one. (the last one). Where am I mistaking?
Help me =)
You are not testing what you have to test there, on a controller spec you only need to test that the method that you want is called with the parameters that you want, in your case, you have to test that the User model receives :find with parameters :all, :select => 'id, login, email', :conditions => ["created_at > ?", time] (with time the value that should be there.
Also, that logic does not belong to the controller, you should have a class method on User, something like select_for_json(date) to wrap around that find method (you can find a better name for it)
Then your controller becomes:
def user_list
render :nothing => true, :status => 422 if params[:time_param].blank?
time = Time.parse(params[:time_param])
#users = User.select_for_json(time)
render :json => { :users => #users }
end
your spec would be
before(:each) do
#users = mock(:users)
#time_param = "2013-01-25 00:01:00"
end
it "retrieve users for json" do
User.should_receive(:select_for_json).once.with(#time).and_return(#users)
get :user_list, { :time_param => #time }
assigns(:users).should == #users
end
that way you are sure that your action does what it does and the spec is A LOT faster since you are not creating users
then you can test that method on the model specs, there you have to create some users, invoke that method and check the users returned (don't stub/mock anything on your model spec)
Your stub call is telling find to ignore what it thought it was supposed to do and return #users instead. It will not attempt to match the conditions.
Unfortunately, to do your test I think you're going to have to allow the find to execute through your database which means you can't use mock_models. You probably will want to do either User.create(...) or FactoryGirl.create(:user) (or some other factory / fixture).
Of course doing it this way, you may hit MassAssignment issues if you use attr_accessible or attr_protected, but those are easy enough to stub out.
I hope that helps.

How to convert postgresql column into a float for a scoped search in rails

I am trying to search my postgresql db in rails. I followed the Railscasts #111 Advanced Search tutorial and it is working for the name and category of my items column in plain text. However, I want to set a min/max price on my search as well which is where I come into my problem. In my db my price is stored as a string in the format "AU $49.95". Can I convert this into a float on the fly in my scoped search? If so how? If not, what should I do?
Here is the code:
search.rb
class Search < ActiveRecord::Base
attr_accessible :keywords, :catagory, :minimum_price, :maximum_price
def items
#items ||= find_items
end
private
def find_items
scope = Item.scoped({})
scope = scope.scoped :conditions => ["to_tsvector('english', items.name) ## plainto_tsquery(?)", "%#{keywords}%"] unless keywords.blank?
scope = scope.scoped :conditions => ["items.price >= ?", "AU \$#{minimum_price.to_s}"] unless minimum_price.blank?
# scope = scope.scoped :conditions => ["items.price <= ?", "AU \$#{maximum_price.to_s}"] unless maximum_price.blank?
scope = scope.scoped :conditions => ["to_tsvector('english', items.catagory) ## ?", catagory] unless catagory.blank?
scope
end
end
searches_controller.rb
class SearchesController < ApplicationController
def new
#search = Search.new
end
def create
#search = Search.new(params[:search])
if #search.save
redirect_to #search, :notice => "Successfully created search."
else
render :action => 'new'
end
end
def show
#search = Search.find(params[:id])
end
end
Thanks for reading this far!
Use the data type numeric or money for exact numerical calculation without rounding errors - and sorting as a number (not as text).
Converting string literal to numeric should not be a performance problem at all.

Bad routing, rails

I didn't figure out the mechanics of the routing yet..
I have a User, Msg and comment model.
A User creates a Msg and inside the msg i'd like to put simple text box for comments. similar to twitter.
However, When the the form is submitted (using the form below) instead of returning to localhost/msgs/:id it returns to localhost/comments.
I have no view for /comments and I don't want to have. I want all comments to be displayed in msg/:id page.
comments controller:
class CommentsController < ApplicationController
before_filter :authenticate
def create
msgid = flash[:msg]
#current_msg = Msg.find(discid)
#comm = #current_msg.comments.build(params[:comment])
#comm.user_id = current_user.id
#comm.msg_id = msgid
puts discid
if #comm.save
flash[:success] = "Comment posted"
redirect_to msg_path(discid)
else
flash[:error] = "Comment was not posted."
redirect_to msg_path(discid)
end
end
route.rb
match '/comments' , :to => 'msgs#show'
resources :users
resources :msgs
since the comments are displayed in the show view of the msgs here is the show action in the msgs controller
def show
#msg= Msg.find(params[:id])
#title = #msg.title
#comment = Comment.new
#comments = #msg.comments.all
flash[:msg] = #msg.id
end
The error I get is
ActiveRecord::RecordNotFound in MsgsController#show
Couldn't find Msgwithout an ID
and it points to line 46 which at the moment is #msg = Msg.find(params[:id])
If I remove the route line and put a regular resources :comments I get a missing template for comments/create..
Help is appreciated.
Issue solved.. I add a :id => discid in the redirecא_to..
Also used Template is missing to understand the issue