user mailer showing special character - ruby-on-rails

as we all know that html_safe work in controller and view
i am sending some data from user_mailer.rb file and its having some special character like if i wrote &"samarth" so its show &amd&quotsamarth&quot
the code is
def alert_publication_notification(user, cust_alert, home_url)
load_mailer_settings
#content_type = "text/html"
#subject = ("[abc]- #{cust_alert.alert.name.html_safe} : mail ") due to this line i am getting special character any solution
#from = "sam"
#recipients = user.login
#bcc = Settings.emailid_alerts
#sent_on = Time.now
#customer_alert = cust_alert
#user = user
#home_url = home_url
end

use raw(some_variable) function for RAILS 3 this will not show encoded characters.

Related

Get Input from form for API url Request in rails?

I'm new to Rails and I'm trying to make a simple weather API to get weather by zipcode
is there a way to get the zipcode from user input from a simple form, this will be just for learning so I'm not trying to make users devise, or users model
require 'net/http'
require 'json'
#url = 'http://api.openweathermap.org/data/2.5/weather?zip=#{zipcode}&appid=APIKEY'
#uri = URI(#url)
#response = Net::HTTP.get(#uri)
#output = JSON.parse(#response)
actually I figured it out, i needed to add
def zipcode
#zip_query = params[:zipcode]
if params[:zipcode] == ""
#zip_query = "Hey you forgot to enter a zipcode!"
elsif params[:zipcode]
# Do Api stuff
require 'net/http'
require 'json'
#url = 'http://api.openweathermap.org/data/2.5/weather?zip='+ #zip_query +'&appid=APIKEY'
#uri = URI(#url)
#response = Net::HTTP.get(#uri)
#output = JSON.parse(#response)
#name = #output['name']
# Check for empty return result
if #output.empty?
#final_output = "Error"
elsif !#output
#final_output = "Error"
else
#final_output = ((#output['main']['temp'] - 273.15) * 9/5 +32).round(2)
end
end
end
in the controller.rb file
and add
post "zipcode" => 'home#zipcode'
get "home/zipcode"
in the routes file
but I'm sure this is not the best practice

How to make one default receiver be able to see the other receivers mail ids in ActionMailer rails

I am sending mails to multiple receivers at a time. I needed one default receiver to be able to see the ids of other receivers on his mail. And the other receivers are in BCC. I tried by setting the default mail to to: field and other receivers to bcc:. It didn't work. Following is my code.
def newequip_matches_wanted
#default_mail = "mail#mymail.com"
#system_email = SystemEmail.find_by(title: 'Equipment matches WantedEquipment')
#subject = #system_email.try(:subject).to_s
#subject = "Equipment matches WantedEquipment" if #subject.blank?
#equipment = Equipment.last
x = Equipment.last.try(:category_id)
y = WantedEquipment.pluck(:category_id)
a = Equipment.last.try(:sub_category_id)
b = WantedEquipment.pluck(:sub_category_id)
y.include?(x) && b.include?(a)
if true
#receiver = WantedEquipment.where(sub_category_id: "#{a}", status: 2).pluck(:email)
mail(bcc: #receiver, to: #default_mail, subject: #subject)
end
end
What am I missing here?
Question is updated.
You missed storing the subject into #subject and also you have syntax error in second code for mail
def mail
#subject = "This is Demo subject"
#default_mail = "mail#mymail.com"
#receiver = Model.where(status: 2).pluck(:email)
mail(bcc: #receiver, to: #default_mail, subject: #subject)
end
Here is a reference

Add a random string while updating attribute

I am looking for a method that can generate a random string in the starting of the email field while updating the record.
def update
#user = User.find_by_id(4)
#user.email = #method to update email with random string
end
So if I have the email record abc#gmail.com and I want to update it like this:
dssaakj123_abc#gmail.com
How it can be done in rails?
You can use the SecureRandom library:
#user.email = "#{SecureRandom.hex(10)}_#{user.email}"
Why not use SecureRandom?
require 'securerandom'
random_string = SecureRandom.hex # provide argument to limit the no. of characters
# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)
For appending before email, you can do something like
#user.email = "#{SecureRandom.hex(5))_#{#user.email}" # 5 is no. of characters
Hope it helps!
(1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join
8 is the number of characters you want to generate randomly.
create an action in your application controller like this :
private
def generate_random_string
SecureRandom.urlsafe_base64(nil, false)
end
And use it like this in any controller you want:
def update
#user = User.find_by_id(4)
#user.email = generate_random_string + #user.email
end
I hope this will help you.
def update
#user = User.find_by_id(4)
#user.email = "#{generate_random_string(8)}_#{#user.email}"
## You can pass any length to generate_random_string method, in this I have passed 8.
end
private
def generate_random_string(length)
options = { :length => length.to_i, :chars => ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a }
Array.new(options[:length]) { options[:chars].to_a[rand(options[:chars].to_a.size)] }.join
end

Gem Resque Error - Undefined "method perform" after Overriding it form the super class

First of all Thanks for you all for helping programmers like me with your valuable inputs in solving day to day issues.
This is my first question in stack overflow as I am experiencing this problems from almost one week.
WE are building a crawler which crawls the specific websites and extract the contents from it, we are using mechanize to acheive this , as it was taking loads of time we decided to run the crawling process as a background task using resque with redis gem , but while sending the process to background I am experiencing the error as the title saying,
my code in lib/parsers/home.rb
require 'resque'
require File.dirname(__FILE__)+"/../index"
class Home < Index
Resque.enqueue(Index , :page )
def self.perform(page)
super (page)
search_form = page.form_with :name=>"frmAgent"
resuts_page = search_form.submit
total_entries = resuts_page.parser.xpath('//*[#id="PagingTable"]/tr[2]/td[2]').text
if total_entries =~ /(\d+)\s*$/
total_entries = $1
else
total_entries = "unknown"
end
start_res_idx = 1
while true
puts "Found #{total_entries} entries"
detail_links = resuts_page.parser.xpath('//*[#id="MainTable"]/tr/td/a')
detail_links.each do |d_link|
if d_link.attribute("class")
next
else
data_page = #agent.get d_link.attribute("href")
fields = get_fields_from_page data_page
save_result_page page.uri.to_s, fields
#break
end
end
site_done
rescue Exception => e
puts "error: #{e}"
end
end
and the superclass in lib/index.rb is
require 'resque'
require 'mechanize'
require 'mechanize/form'
class Index
#queue = :Index_queue
def initialize(site)
#site = site
#agent = Mechanize.new
#agent.user_agent = Mechanize::AGENT_ALIASES['Windows Mozilla']
#agent.follow_meta_refresh = true
#rows_parsed = 0
#rows_total = 0
rescue Exception => e
log "Unable to login: #{e.message}"
end
def run
log "Parsing..."
url = "unknown"
if #site.url
url = #site.url
log "Opening #{url} as a data page"
#page = #agent.get(url)
#perform method should be override in subclasses
#data = self.perform(#page)
else
#some sites do not have "datapage" URL
#for example after login you're already on your very own datapage
#this is to be addressed in 'perform' method of subclass
#data = self.perform(nil)
end
rescue Exception=>e
puts "Failed to parse URL '#{url}', exception=>"+e.message
set_site_status("error "+e.message)
end
#overriding method
def self.perform(page)
end
def save_result_page(url, result_params)
result = Result.find_by_sql(["select * from results where site_id = ? AND ref_code = ?", #site.id, utf8(result_params[:ref_code])]).first
if result.nil?
result_params[:site_id] = #site.id
result_params[:time_crawled] = DateTime.now().strftime "%Y-%m-%d %H:%M:%S"
result_params[:link] = url
result = Result.create result_params
else
result.result_fields.each do |f|
f.delete
end
result.link = url
result.time_crawled = DateTime.now().strftime "%Y-%m-%d %H:%M:%S"
result.html = result_params[:html]
fields = []
result_params[:result_fields_attributes].each do |f|
fields.push ResultField.new(f)
end
result.result_fields = fields
result.save
end
#rows_parsed +=1
msg = "Saved #{#rows_parsed}"
msg +=" of #{#rows_total}" if #rows_total.to_i > 0
log msg
return result
end
end
What's Wrong with this code?
Thanks

does a after_created Rails callback method on a model have an instance of the newly created model?

I have a after_create method for my Contact model.
However, when I put the value, it comes out nil. How can I have a callback for a newly created model ( I do a fair amount of transformation in the create model) referenced within the callback method?
after_save :update_company
def update_company
puts self.inspect
puts self.company
if company.phone.empty?
company.phone = self.phone
company.save
end
end
When I look at the logs for self.inspect, it doesn't show any of the transformations used in the create method...yet, this should run only after it has created (and saved), the object, right?
Here is the create method:
def create
#contact = Contact.create(params[:contact])
unless #contact.vcard.path.blank?
paperclip_vcard = File.new(#contact.vcard.path)
#vcard = Vpim::Vcard.decode(paperclip_vcard).first
#contact.title = #vcard.title
#contact.email = #vcard.email
#contact.first_name = #vcard.name.given
#contact.last_name = #vcard.name.family
#contact.phone = #vcard.telephone
#contact.address.street1 = #vcard.address.street
#contact.address.city = #vcard.address.locality
#contact.address.state = #vcard.address.region
#contact.address.zip = #vcard.address.postalcode
#contact.company_name = #vcard.org.fetch(0)
end
#contact.user_id = current_user.id # makes sure every new user is assigned an ID
if #contact.save
flash[:notice] = "Successfully created contact."
redirect_to #contact
else
render :action => 'new'
end
end
Yes, this happens because you didn't use self when assigning the value to company object.
In ruby, generally you don't require the use have "self" to retrieve attributes of an instance
for example in your code. you can puts company and it would work fine.
but when assigning (on the left hand side ) you always have to use self.
so change this in your code.
self.company.phone = self.phone
company.save
or
self.company.phone = phone
company.save

Resources