Mandrill API Templating - ruby-on-rails

I'm using Mandrill's Ruby API Gem and have the follow simple template for testing:
<html>
<body>
<h1 mc:edit="header">testastic</h1>
<hr/>
<br/><br/>
<div mc:edit="main_section"></div>
<hr/>
<div mc:edit="footer"></div>
</body>
</html>
Following the example on Heroku's guide I have the follow Ruby code:
require 'mandrill'
m = Mandrill::API.new
rendered = m.templates.render 'test-template', [{:header => 'some header text', :main_section => 'The main content block', :footer => '<h3>asdf</h3>'}]
mail(:to => "Jayson Lane <jayson#domain.com>", :subject => "Test Email") do |format|
format.html { rendered['html'] }
#format.text { render "test" }
end
This works great and the email sends my template just fine, however, it doesn't replace the template mc:edit variables. Am I missing something?

You need to construct a hash for each element you're trying to replace. For instance, I have this inside of a template:
<h3 mc:edit="plan_info_name"> </h3>
<span mc:edit="plan_info_description"> </span>
<span mc:edit="plan_info_benefits"> </span>
And this on the mailer:
mandrill.messages.send_template(template,[
{
:name => 'plan_info_name',
:content => extra[:membership_info].name
},
{
:name => 'plan_info_description',
:content => extra[:membership_info].long_description
},
{
:name => 'plan_info_benefits',
:content => benefits_list
}
....

Related

Stripe standalone :source => params[:stripeToken] error

I'm new to Stripe connect, building a marketplace app using stripe connect standalone, and require the user to enter a custom amount to pay the other user. The old form I was using worked fine, but once I changed to the new form, my :source => params[:stripeToken] no longer generates, as well as :stripeEmail. What is causing this?
Invalid source object: must be a dictionary or a non-empty string
my original charges_controller.rb
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
#amount = 500
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount,
:description => 'Wage Payment',
:currency => 'cad'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
then I added the methods from the stripe recipe for custom amounts:
def create
#amount = params[:amount]
#amount = #amount.gsub('$', '').gsub(',', '')
begin
#amount = Float(#amount).round(2)
rescue
flash[:error] = 'Charge not completed. Please enter a valid amount in CAD ($).'
redirect_to new_charge_path
return
end
#amount = (#amount * 100).to_i # Must be an integer!
if #amount < 500
flash[:error] = 'Charge not completed. Payment amount must be at least $5.'
redirect_to new_charge_path
return
end
charge = Stripe::Charge.create(
:amount => #amount,
:customer => customer.id,
:currency => 'cad',
:source => params[:stripeToken],
:description => ‘Payment'
)
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
I also modified the form, and added the javascript in charges/new.html.erb:
old form:
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_my_key');
</script>
<%= form_tag charges_path do %>
<article>
<% if flash[:error].present? %>
<div id="error_explanation">
<p><%= flash[:error] %></p>
</div>
<% end %>
<label class="amount">
<span>Amount: $5.00</span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="A month's subscription"
data-amount="500"
data-locale="auto"></script>
<% end %>
new form:
<%= form_tag charges_path, id: 'form' do %>
<div id="error_explanation">
<% if flash[:error].present? %>
<p><%= flash[:error] %></p>
<% end %>
</div>
<article>
<%= label_tag(:amount, 'Payment Amount:') %>
<%= text_field_tag(:amount) %>
</article>
<article>
<%= hidden_field_tag(:stripeToken) %>
<%= hidden_field_tag(:stripeEmail) %>
</article>
<button id='donateButton'>Pay Now</button>
<% end %>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_CcUZ1IJxEqLR5RvVE3p5tx3U');
</script>
<script>
var handler = StripeCheckout.configure({
key: '<%= Rails.configuration.stripe[:publishable_key] %>',
locale: 'auto',
name: 'Payments',
description: 'Wage',
token: function(token) {
$('input#stripeToken').val(token.id);
$('input#stripeEmail').val(token.id);
$('form').submit();
}
});
$('#donateButton').on('click', function(e) {
e.preventDefault();
$('#error_explanation').html('');
var amount = $('input#amount').val();
amount = amount.replace(/\$/g, '').replace(/\,/g, '')
amount = parseFloat(amount);
if (isNaN(amount)) {
$('#error_explanation').html('<p>Please enter a valid amount in CAD ($).</p>');
}
else if (amount < 5.00) {
$('#error_explanation').html('<p>Wage amount must be at least $5.</p>');
}
else {
amount = amount * 100; // Needs to be an integer!
handler.open({
amount: Math.round(amount)
})
}
});
// Close Checkout on page navigation
$(window).on('popstate', function() {
handler.close();
});
</script>
Now when I submit the custom amount, I am given the following error:
You have passed a blank string for 'source'. You should remove the
'source' parameter from your request or supply a non-blank value
Extracted source (around line #27): Stripe::Charge.create(
Not sure how to proceed. This error seems to be associated to creating charges, as the error is in the charges controller. Or it is in the javascript of the new custom form.
What am I missing?
I had exactly the similar problem. But after few hours of struggle I figured it out. The reason is following. If you are using Rails 4.+ and using Turbolinks along with it, then it loads entire javascript for that page and when you are loading modal the javascript on that modal page wont work. You have to switch off the turbolink.
For me I switched off at the link level which is the link responsible for loading the charge/new page. Example:
<%= link_to "Buy", new_charge_path(product_id: #product.id),'data-no-turbolink' => true %>

How to send email based on date time in Rails?

I am having a "send email" functionality in my application which sends email to the email addresses.
Later a new functionality is added where when the user checks on "Send email later" radio button, selects date and time and clicks on send email button so that the email is sent at particular time.
For this I added a field into database with column "send_reports_at", added to controller and required actions.
The date time is stored as : "2016-11-01 16:15".
How to add the condition of sending email based on the date time in my application(I am new to delayed job and all)?
Please help.
This is my view:
<%= f.input :additional_emails, :label => false, :input_html => {:id => 'sponge_contacts', :placeholder => 'Separate emails by comma', :class => 'deliver_page_email', :type => 'text', :rows => 2, :style=> 'width:300px; border-color:#ccc; font-size:13px; padding:10px 0 0 10px; width: 295px; height: 110px; resize: none;'} %>
<input type="radio" id="send_email_0" name="send_email" value="now" checked> Send email now<br>
<input type="radio" id="send_email_1" name="send_email" value="later"> Send email later<br>
<%= f.input :send_reports_at,:label => false, :input_html => {:placeholder => 'Click here to select date and times', :class => 'deliver_page_email', :type => 'text', :rows => 2} %>
<% content_for :javascript do %>
<script type="text/javascript">
$( function() {
$( "#report_send_reports_at" ).datepicker();
} );
$(document).ready(function() {
$("#report_send_reports_at").hide();
$("#send_email_0, #send_email_1").bind('change click',function(){
toggleResult();
});
});
function toggleResult(){
result = $("[name='send_email']:checked").val();
if(result == "later"){
$("#report_send_reports_at").show();
}else{
$("#report_send_reports_at").hide();
}
}
</script>
<% end %>
<% end %>
<%= link_to "Send Now", '#', :class => "pink_button _round_5", :id => 'send_now_button' %>
This is my controller method:
def send_report_email
send_to_agents = params.has_key?("send_to_agents") && params["send_to_agents"] == "true"
if #report.photos.empty?
Screenshot.delay.new(#user.id, #report.id, Rails.application.config.custom.indicator_screenshot_bucket)
else
Screenshot.delay.new(#user.id, #report.id, "photo_screenshots")
end
Screenshot.delay.new(#user.id, #report.id, Rails.application.config.custom.report_screenshot_bucket)
if #report.update_attributes(params[:report])
set_photo_position(false)
#report.save
if send_to_agents
#report.update_attribute(:duplicable, true)
#good_emails, #bad_emails, #unsubscribed_emails = #user.account.users.map(&:email), [], []
else
#good_emails, #bad_emails, #unsubscribed_emails = filter_emails(#report.additional_emails)
#user.delay.add_new_contacts(#good_emails)
end
#good_emails.each do |email|
send_to_agents == true ? ReportMailer.delay.additional_emails(email, #user, #report, "A new report is available: #{#report.title}") : ReportMailer.delay.additional_emails(email, #user, #report)
end
ReportMailer.delay.report_sent(#user, #report, #good_emails, #bad_emails, #unsubscribed_emails)
end
respond_to do |format|
format.json { render :json => { :success => true, :report_id => #report.id, :redirect => user_reports_url(current_user), :notice => 'Report was successfully sent!' } }
end
end
You could write a function (for instance a class method for ReportMailer) that sends all of the email whose scheduled time matches or is less than the current time, then set a cron job to use rails runner to run that function as often as necessary.

pdfkit not rendering images and css to the pdf

I have generated a pdf using pdfkit but it is neither rendering images nor the css file. I don't know why this is happening. Any help will be appreciable.
Layout : (report.html.erb)
<!DOCTYPE html>
<html lang='en'>
<head>
<%= stylesheet_link_tag 'merchant_report', rel: 'stylesheet'%>
<%= csrf_meta_tags %>
<%= favicon_link_tag 'favicon.ico' %>
</head>
<body>
<%= yield %>
</body>
</html>
Action : (report.pdf.erb)
<div class="checkin_data">
<h4 style="text-align: center;">No. of Customers Vs. Date</h4>
<div>No. of Checkins during this period on a day wise basis</div>
<% image_name = Time.now.strftime("%d-%m-%Y").to_s + '_' + $merchant.id.to_s + '_check_in_visit_history_image.png' %>
<!-- <img src="http://127.0.0.1:3000/system/report/#{image_name}"/> -->
<%= image_tag("/assets/images/report/#{image_name}")%>
<br>
<h4 style="text-align: center;">No. of Customers Vs. No. of Visits</h4>
<div>No. of Visits per Customer during this period</div>
<canvas height="400" width="600" id="customer_visit"></canvas>
<br>
</div>
Controller : (merchant_report_controller)
respond_to do |format|
format.html
format.pdf do
html = render_to_string(:layout => "report.html.erb" , :action => "report.pdf.erb")
kit = PDFKit.new(html)
kit.stylesheets << "#{Rails.root}/public/system/stylesheets/merchant_report.css"
send_data(kit.to_pdf, :filename => "some_name.pdf", :type => 'application/pdf', :disposition => 'inline')
return
end
end
pdfkit.rb
PDFKit.configure do |config|
config.wkhtmltopdf = '/usr/bin/wkhtmltopdf'
config.default_options = {
:page_size => 'Legal',
:print_media_type => true,
:disable_javascript => true
}
# Use only if your external hostname is unavailable on the server.
config.root_url = "http://localhost:3000"
config.verbose = false
end

Extra characters rendered in view that cannot be found! A possible bug in rendering engine?

I am developing an application using rails 3.2.0 and ruby 1.9 on a Mac
I have a very strange error when rendering an index view
Rails is rendering the characters us at the bottom of the screen, below an index table, and I cannot find these characters in the view.
This part of the view looks like
<section id="main">
<section id="group"></section>
<section id="content">
<section id="data_table_section">
<script>
us
</section>
</section>
The part from id=content is yield in a layout file
<section id='content'>
<%= yield %>
</section>
When I delete the content of the view template, i.e the the us is still there
When I delete <%= yield %> in the layout, the us disappears
When I search for the us in the view code it is not found
When I add my own extra characters in the bottom of the view template code, after tags the us is displayed after these characters
When I delete the layout template the us is still there
The only thing I can come up with is that us is generated by the yield function in some mysterious way, but that seems as a very strange explanation!
Anyone that has had this problem before?
Anyone that know how to find extra characters as us in the code ?
Could it be a bug in the rendering engine ?
Any advices would be great appreciated
Here follows my view code. I use tableastic gem and some other gems
<% if !#unit.nil?
header_text="Deltagarlista för #{#unit.class.model_name.human} #{#unit.name}"
else header_text='Deltagarlista för ST-Forum'
end %>
<section id='data_table_section'>
<article id='remote_clinic_article'></article>
<article id="users_article">
<%= table_for(#users) do |t| %>
<thead ><tr ><th id='table_header' colspan=17><%=header_text%></th></tr></thead>
<thead><tr style='text-align:center;' ><th colspan=15><%= render :partial=>'users/filter'%></th></tr></thead>
<% index=(params[:page].to_i-1)*#per_page%>
<%= t.data do
t.cell(:id, :heading => "Id") {|p| index+=1}
t.cell(:portrait, :heading => "Foto") {|p| image_tag(p.portrait_image,:height=>'24px')}
t.cell(:name,:heading => sort_to("Namn",users_url(:sort_field=>'surname', :sort=>#sort),#sort_field)) {|p| link_to(mark_search_hits(p.name,#search),user_path(p.id))}
t.cell(:clinic, :heading => sort_to("Arbetsplats",users_url(:sort_field=>'clinics.name', :sort=>#sort),#sort_field)) {|p| link_to(mark_search_hits(p.clinic.name,#search),clinic_path(p.clinic.id)) unless p.clinic.nil?}
t.cell(:email,:cell_html => {:class => "address"},
:heading => sort_to("Email",users_url(:sort_field=>'email', :sort=>#sort),#sort_field)) {|p| mail_to(mark_search_hits(truncate(p.email,:length =>20),#search))}
t.cell(:user_roles,:cell_html => {:style => "width:50px"},
:heading => sort_to("Roller",users_url(:sort_field=>'user_roles.role_index', :sort=>#sort),#sort_field)) {|p| mark_search_hits(p.roles(true).to_sentence,#search)}
t.cell(:groups, :heading => sort_to("Grupper",users_url(:sort_field=>'groups.name', :sort=>#sort),#sort_field)) {|p| mark_search_hits(to_sentence(p.groups),#search)}
t.cell(:forum, :heading => sort_to("ST-forum",users_url(:sort_field=>'forums.name', :sort=>#sort),#sort_field)) {|p| mark_search_hits(link_to(p.forum.name,clinic_path(p.forum.id)),#search) unless p.forum.nil?}
t.cell(:st_starts_on, :heading => sort_to("ST-start -- slut",users_url(:sort_field=>'employments.st_starts_on', :sort=>#sort),#sort_field)){|p| mark_search_hits(between_user_dates(p.employment.st_starts_on,p.employment.st_end_on),#search) unless p.employment.nil?}
t.cell(:legitimation_on,:heading => sort_to("Legitimation",users_url(:sort_field=>'employments.legitimation_on', :sort=>#sort),#sort_field)){|p| mark_search_hits(to_user_date(p.employment.legitimation_on),#search) unless p.employment.nil?}
t.cell(:employed_on,
:heading => sort_to("ST-kontrakt",users_url(:sort_field=>'employments.employed_on', :sort=>#sort),#sort_field)){|p| mark_search_hits(to_user_date(p.employment.employed_on),#search) unless p.employment.nil?}
t.cell(:last_visit,
:heading => sort_to("Inloggad senast",users_url(:sort_field=>'last_visit_at', :sort=>#sort),#sort_field)){|p| mark_search_hits(to_user_date(p.last_visit_at),#search) }
t.cell(:mail,
:heading => "Handledare / Handledd") {|p| if !p.supervisors.blank? then mail_supervisors(p) elsif !p.supervised.blank? then mail_supervised(p) end}
t.cell(:id, :cell_html => {:style => "width:30px"},:heading=>image_to('new.png',new_user_path,:class=>'no_class')) {|p| (image_to('destroy.png',user_path(p),:class=>'none',:method=>'delete', :id=>'destroy_button', :confirm => "Vill du verkligen radera vald kurs ",:title=>'Radera kurs')+' '+image_to('map.png', map_address_path(p.address.id),:method=>:get,:class=>'none', :remote=>true, :title=>'Visa en karta över bostadsområdet')).html_safe}
end%>
<tfoot>
<tr >
<td colspan="16" class='flickr_pagination'><%= will_paginate #users, :container => true %><span class="table_filter_text">
<% if #count_users==0 %>
<span class="table_filter_alert_text">
<%=" Inga användare tillgänglig för #{put_filter(#filterparams)}".html_safe%>
</span>
<%else%>
<span class="table_footer_text">
<%="Visar användare "+((params[:page].to_i-1)*#per_page+1).to_s+" till "+([(params[:page].to_i-1)*#per_page+#per_page,#count_users].min).to_s+" av #{#count_users.to_s} användare" .html_safe%>
<br/><%= "Med #{ put_filter(#filterparams)}".html_safe %>
</span>
<%end%>
</td>
</tr>
</tfoot>
<% end %>
</article>
</section>
<script>
$(document).ready(function() {
/* $('.pagination a').attr('data-remote', 'true');*/
jQuery(".best_in_place").best_in_place();
});
// Observe forum_field and filter group_options
$(document).ready(function(){
$("#forum_id").live('change',function () {
var forum = "";
forum=$("select#forum_id :selected").val()
if (forum=='') {forum=0}
jQuery.get('/users/'+forum+'/update_group_options', function(data){
$("#group_div").html(data);
})
return false;
})
.change();
$("#county_council_id").live('change',function () {
var county_council = "";
county_council=$("select#county_council_id :selected").val()
if (county_council=='') {county_council=0}
jQuery.get('/users/'+county_council+'/update_forum_options', function(data){
$("#forum_div").html(data);
})
return false;
})
.change();
});
</script>
I think the "us" is written by js.
May be you can double check the js.

Parameter in AJAX request

I have a view which contain multiple links:
<% a.each do |q| %>
<%= link_to "stock it",
{ :action => "stock",
:qid => q.question_id,
:qur => q.question_answers_url,
:qti => q.title } ,
:remote => true %>
<div id="<%= "stock" + q.question_id.to_s %>"></div>
<% end %>
Each link generate AJAX-request. Here is a controller:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
respond_to do |format|
format.js { render :layout=>false }
end
end
Now return to the view. Each link has a 'div' with unique id='stock'. When user press the link I need to add text to specific div with corresponding id.
I have a stock.js.erb file:
$("#stock<number>").html("some text");
How can I pass div-id to stock.js.erb and how can I use it ?
Common use is to add object.id to your DOM id. That what you exactly did:
<div id="<%= "stock_#{q.question_id}" %>"></div>
Then in your controller you shoud define your question_id or your exact question:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
#question_id = params[:qid]
end
Now it will be shared with your stock.js.erb file:
$("#stock_<%= #question_id %>").html("some text");

Resources