How to add new variable for flash message with Devise? - ruby-on-rails-3

In my RoR app, I'm passing flash messages using "notice" and "alert".
But, when I'm trying to pass like flash["warning"], for example, I receive: undefined local variable or method warning'
What can I do to be able to create a flash message passing 'warning' value?
Code:
#app/controllers/users/passwords_controller.rb
class Users::PasswordsController < Devise::PasswordsController
def create
user = params["user"]
if User.find_by_email(user["email"]).nil?
set_flash_message(:testing, :email_not_found) if is_navigational_format?
redirect_to root_path
else
self.resource = resource_class.send_reset_password_instructions(user)
if successfully_sent?(resource)
respond_with({}, :location => after_sending_reset_password_instructions_path_for(resource_name))
else
respond_with(resource)
end
end
end
protected
def after_sending_reset_password_instructions_path_for(resource_name)
root_path
end
end
#app/views/landing/index.html.erb
.
.
<h5><%= testing %></h5>
Any help? Thanks!

Try to use a symbol. flash[:warning] = "XYZ" for example.

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

check instance variable value in before filter rspec

In my controller I have a method which checks for next item. But before executing this method I need to set an instance variable which is written in the before_filter method. So how do I test it in rspec.
before_filter method check_items, :only[:next]
def check_items
if params[:item] == "Sherlock"
#item = $book1
elsif params[:item] == "Harry"
#queue = $book2
else
render :json=>{"Error" => "Book name does not exist"}
end
end
=======================
def next
#book = #item.pull
unless #book.nil?
respond_with(#book)
else
render :json =>{"msg"=>"Nothing to pull"}
end
end
If you are writing controller specs, you can test this behavior with assigns constraint. You may end up with something like this:
it "assigns #item" do
item = Item.create
get :next
expect(assigns(:item)).to eq(item)
end
If you write unit tests, you can use instance_variable_get method. But I would avoid it - I would go with controller specs.
Hope that helps

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

Rails render mail_form gem from a different controller

From travels, which belongs to offer, I'm trying to render a form generated with the mail_form gem.
But I get an error with this message:
*undefined method `model_name' for NilClass:Class*
travels/show
= render :partial => '/question_forms/form', :question_form => #question_form
Any hint how to get this? I've tried including the question_form model as an association to travel, but it doesn't work.
This is the question_forms_controller default code:
class QuestionFormsController < ApplicationController
def new
#question_form = QuestionForm.new
end
def create
begin
#question_form = QuestionForm.new(params[:question_form])
#question_form.request = request
if #question_form.deliver
flash.now[:notice] = 'Thank you for your message!'
else
render :new
end
rescue ScriptError
flash[:error] = 'Sorry, this message appears to be spam and was not delivered.'
end
end
end
In my travels_controller I tried to load #question_form using the same method, but this doesn't seem the way:
def new
#offer_season = OfferSeason.find(params[:offer_season_id])
#travel = #offer_season.travels.find(params[:id])
#question_form = #travel.questionforms.new
end
def create
#offer_season = OfferSeason.find(params[:offer_season_id])
#travel = #offer_season.travels.find(params[:id])
begin
#question_form = #travel.questionforms.new(params[:question_form])
#question_form.request = request
if #question_form.deliver
flash.now[:notice] = 'Thank you for your message!'
else
render :new
end
rescue ScriptError
flash[:error] = 'Sorry, this message appears to be spam and was not delivered.'
end
end

Where to set session default value?

guys!
Prior to asking i should mention, that i`m working without ActiveRecord or any self-hosted-database. So thats why i have to store some values in the session.
From the very begining i desided to set session value of the users city in the layout. - i supposed it would be loaded before anything else. So i`ve done something like this:
<% session[:city] ||= {:name => 'City-Name', :lat => '40', :lng => '40'}%>
But when i`m loading directly to inner page it occurs that session[:city is nil *(
How should i set the session properely, so that it wouldn`t be nil???
I had similar needs in one of the applications I worked on. It needed the users data to be loaded on sign-in and stored in the session. So, wrote a module called session_helpers.rb with the following:
module SessionHelpers
def get_value(key)
session[key.to_sym]
end
protected
def store_data(*objects)
objects.each do |object|
if object.is_a?(Hash)
object.each do |key, value|
session[key.to_sym] = value
end
end
end
end
def remove_data(*objects)
objects.each do |object|
if object.is_a?(String)
key = to_id(object)
else
key = to_id(object.class.name)
end
session[key] = nil
end
end
def update_data(key, value)
session[key.to_sym] = value
end
private
def to_id(name)
"#{name.parameterize('_').foreign_key}".to_sym
end
end
You can make any or all the methods available to views as well:
# application_controller.rb
helper_method :get_value
From the model I would retrieve a hash of the data that needs to be put up in the session about the user:
def common_data
#data = Hash.new
#data.merge!( { 'news' => self.news.count } )
...
#data
end
As I wanted to do this after sign-in I overrode the devise method to do this:
def after_sign_in_path_for(resource_or_scope)
store_data( '_count', current_user.common_data )
dashboard_path
end
This way I was able to load important data about the user on sign-in and store it in the session and retrieve whenever I wanted. Hope this helps.