Pushmeup Gem - Can't send push notifications in Active Admin model - ruby-on-rails

I'm creating a CRM/CMS in Rails using Active Admin.
I've used Pushmeup Gem for the APNS(Apple Push notification service) functionality but I can't seem to make it work.
Here's what I did.
Forked the Pushmeup Gem to create my own repository. I've edited the configurations to match my credentials.
gem 'pushmeup', :git => 'git://github.com/thisisnotme/pushmeup.git'
I've followed the instructions here.
Here's my app/admin/token.rb file.
collection_action :apns, method: :get do
device_token = '7eb2c5fa7f3b0be45cb3613b1d05470c5b76b90929a8ce49d2e511d7b1245d8a'
APNS.send_notification(device_token, 'Hello iPhone!' )
APNS.send_notification(device_token, :alert => 'Hello iPhone!', :badge => 1, :sound => 'default')
end
This came up on my screen:
NoMethodError in Admin::DeviceTokensController#apns
undefined method `close' for nil:NilClass
Extracted source (around line #19):
17
18
19
20
21
22
collection_action :apns, method: :get do
device_token = '7eb2c5fa7f3b0be45cb3613b1d05470c5b76b90929a8ce49d2e511d7b1245d8a'
APNS.send_notification(device_token, 'Hello iPhone!' )
APNS.send_notification(device_token, :alert => 'Hello iPhone!', :badge => 1, :sound => 'default')
end
It seems that the APNS class is missing. I'm kinda lost. Sorry Rails Newbie.

I've found that the host and port are defined as follows:
module APNS
#host = 'gateway.sandbox.push.apple.com'
#port = 2195
class << self
attr_accessor :host, :pem, :port, :pass
end
end
So you just can redefine APNS variables, as it is shown in the README:
APNS.host = 'gateway.push.apple.com'
APNS.port = 2195
APNS.pem = '/path/to/pem/file'
APNS.pass = ''

Maybe this is kinda late but I had the same error. It was thrown because I did not extract the certificate AND the key from the keychain into a single PEM file.

Related

NoMethodError: undefined method `const_defined?' when referring to class methods

I am building an email sending system into an already fairly complex rails app.
From a controller I'm trying to call a method that builds an email and then delivers it.
In controller:
response_for :create, :update do
estimate = current_object.estimate.reload
flash[:success] = "Tier Save Successful. "
flash[:success] += send_estimate_email if estimate.verify && estimate.tiers.select{|t| !t.verified?}.empty?
flash[:notice] = "This service bundle was changed for a previously verified service bundle. Please re-verify after changes are complete" if current_object.auto_unverified
redirect_to [current_object.estimate]
end
def send_estimate_email
return "" if current_object.estimate.requestor_email.blank? || !current_object.estimate.requestor_notified_at.blank?
begin
estimate = current_object.estimate
host = request.host_with_port
binding.pry
success = EstimateEmailer.deliver_verification_complete(estimate, host)
current_object.estimate.notes.create!(:user_id => User.find(:first, :conditions => {:user_type_id => UserType::ROOT.id}).id, :title => "Verification Complete Email Sent", :body => "TO: #{success.to}\nSUBJECT: #{success.subject}\nBODY: #{success.body}")
rescue Exception => e
logger.warn(e)
success = false
end
if success
current_object.estimate.update_attribute(:requestor_notified_at, Time.now)
current_object.estimate.notes.create!(:title => "Auto-email sent to requestor", :body => "TO: #{success.to}\nSUBJECT: #{success.subject}\nBODY: #{success.body}", :user_id => current_user.id)
return "Automatic estimate email was successfully sent to #{current_object.estimate.requestor_email}"
else
return "However, automatic estimate email could not be sent due to an error"
end
end
I don't think there's anything wrong with the email code itself, but for some reason I get this error on the EstimateEmailer.deliver_verification_complete(estimate, host) call:
NoMethodError: undefined method `const_defined?' for "estimate":String
setting a breakpoint in the controller before the EstimateEmailer call I notice that I get the error whenever I try to refer to other classes. Just calling EstimateEmailer or any other class name returns the same error.
I've run into issues with undefined method const_defined? in the past. I'm guessing the issue isn't specific to emailing, but I haven't the slightest idea where to begin debugging.
def verification_complete(estimate, host)
request_id = estimate.integration_transactions.empty? ? "Internal ID #{estimate.id}" : estimate.integration_transactions.last.source_id
#estimate = estimate
#estimate_url = public_estimate_url(estimate.public_id, :host => host, :protocol => 'https')
mail(
subject: "Ref ##{estimate.project_code} Application Hosting Estimate Available for Review: #{request_id}",
to: [estimate.requestor_email, estimate.project_manager_email].reject{|email| email.blank? }.join(','),
from: SUPPORT_ADDRESS
)
end
You're using make_resourceful which has an incompatibility with current versions of ActiveSupport. I've just lodged a PR that addresses it: https://github.com/hcatlin/make_resourceful/pull/16.
Alternatively, you can point to the remote branch in your Gemfile:
gem 'make_resourceful', github: 'carpodaster/make_resourceful', branch: 'fix/incompatibility-with-active-support-dependencies'
I assume this problem only occurs in your development environment, right? In that case, you should be able to avoid it by setting config.eager_load = true in config/environments/development.rb.

Mandrill setup Ruby on Rails

I'm trying to setup the Mandrill API to send transactional emails. To start with I just want to get a welcome email sent to new users that have just successfully signed up. Once I've completed that I should be able to figure out any other additional emails. I've already coded a few bits, but to be honest I'm not entirely sure I'm doing it right! The code doesn't currently work during testing, which is really annoying.
All the code is included below, all input is welcome :)
I have both the following gems installed.
'mandrill-api'
'mandrill_mailer'
I'm unsure where to place the following code, the documentation for the gem says mail.rb in config/initializers https://github.com/renz45/mandrill_mailer (Look under 'Usage')
ActionMailer::Base.smtp_settings = {
:address => "smtp.mandrillapp.com",
:port => 587,
:user_name => ENV['MANDRILL_USERNAME'],
:password => ENV['MANDRILL_API_KEY'],
:domain => 'heroku.com'
}
ActionMailer::Base.delivery_method = :smtp
MandrillMailer.configure do |config|
config.api_key = ENV['MANDRILL_API_KEY']
end
I won't be using Action Mailer so I guess I'll just change
ActionMailer::Base.smtp_settings
to
MandrillMailer::TemplateMailer.smtp_settings
???
I have a transactional_mailer.rb file under app/mailers
class TransactionalMailer < MandrillMailer::TemplateMailer
default from: 'hello#randomemail.com'
def welcome(user)
mandrill_mail template: 'welcome_template',
subject: "hello",
to: {email: user.email, name: user.name},
vars: {
'USER_IDENTIFIER' => user.email,
'LIST_COMPANY' => 'Your Company'
},
important: true,
inline_css: true,
async: true
end
end
The app currently calls the method in the registration controller
MandrillMailer.welcome(resource).deliver
Should it be
TransactionalMailer.welcome(#user).deliver
???
It's not working during testing on the local server (rails s) I'm new to coding and trying to work out why.
All help is appreciated!
Thanks :)

How to integrate SoundCloud in Ruby on Rails?

I am new to RubyOnRails and SoundCloud.
I want to integrate SoundCloud API in my ruby on rails application.
For this I have registered on SoundCloud And I got the ClientID and ClientSecret. Also I have downloaded the SDK.
Now I have copied the files and folders from lib and spec directory to my applications lib and spec directory. Also I have added gem 'soundcloud' in the Gemfile.
After this I made simple code (copied from doc) in My Interactor:
# register a client with YOUR_CLIENT_ID as client_id_
client = SoundCloud.new(:client_id => YOUR_CLIENT_ID)
# get 10 hottest tracks
tracks = client.get('/tracks', :limit => 10, :order => 'hotness')
# print each link
tracks.each do |track|
puts track.permalink_url
end
But here I'm getting the error -
uninitialized constant MyApp::Interactors::MyInteractor::MyAction::SoundCloud
I followed the steps from APIDoc. Is there any step by step example for integrating SoundCloud in Ruby on Rails so that I can follow?
How can I resolve this error?
MyInteracor.rb
module MyApp
module Interactors
module MyInteractor
class MyAction < Struct.new(:user, :params)
def run
# SoundCloud
# register a client with YOUR_CLIENT_ID as client_id_
client = SoundCloud.new(:client_id => 'my-client-id')
# get 10 hottest tracks
tracks = client.get('/tracks', :limit => 10, :order => 'hotness')
# print each link
tracks.each do |track|
puts track.permalink_url
end
end
end
end
end
end
There's a typo in the soundcloud github page change the line:
client = SoundCloud.new(:client_id => 'my-client-id')
to
client = Soundcloud.new(:client_id => 'my-client-id')
[notice the lowercase c in Soundcloud]
Also you are going to need your client secret for SoundCloud's API to verify you.
Perhaps put client method and in it have client = SoundCloud.new(your-client-id,your-secret-key-your-redirect-uri) in a controller or helper with your client_id, client_secret, and redirect uri values protected in a .env file.
I think by leaving out your redirect_uri and client secret you might be getting this error in MyInteractor.rb
Hope this helps

Pubnub and Rails 4

I'm following a twitter tutorial for a class project and I'm stuck at the part where the tutorial is using PUBNUB. I'm getting the following error:
Showing C:/RubyProjects/twitter/app/views/layouts/application.html.erb where line #93 raised:
**wrong number of arguments(1 for 0)**
Extracted source (around line #93):
PUBNUB.subscribe({
channel : "<%= Digest::SHA1.hexdigest(current_user.username, current_user.created_at) %>",
callback : function(message) { updateTimeline(message) }
I found on stackoverflow and found that EventMachine helped some folks and I tried that but still nada :(
I checked the PUBNUB page on Github and saw that it has changed the way channel and callback was written so I tried doing that but it did not help either. Im still getting the same error about wrong number of arguments(1 for 0).
Notify.rb
class Notify
def self.deliver_message_to_user(params)
post = Post.find(params[:post_id])
user = User.find(params[:user_id])
user.channel ||= Channel.new(
:channel_ident =>
Digest::SHA1.hexdigest(user.username, user.created_at.to_s))
Pubnub.publish({
:channel => user.channel.channel_ident,
:message => post.to_json(:include => :user)
})
end
end
application.html.erb
<script>
function updateTimeline(message) {
var html = JST['post'](jQuery.parseJSON(message));
$('#timeline').prepend(html);
}
Pubnub.subscribe({
:channel => "<%= Digest::SHA1.hexdigest(current_user.username, current_user.created_at) %>",
:callback => function(message) { updateTimeline(message) }
})
</script>
I put require 'digest' in my application.rb file and it still din't help. Could it be the syntax? If it is, i'm not sure what the correct syntax would be.
Publishing PubNub Messages in Ruby on Rails 4.0+
I'm pulling the following details from the PubNub Ruby README.md file - https://github.com/pubnub/ruby/blob/master/README.md
First you need to require PubNub lib from the PubNub Gem in Ruby.
## Require PubNub Gem
require 'pubnub'
## Instantiate a new PubNub instance.
pubnub = Pubnub.new(
:publish_key => 'demo', # publish_key only required if publishing.
:subscribe_key => 'demo', # required
:secret_key => nil, # optional, if used, message signing is enabled
:cipher_key => nil, # optional, if used, encryption is enabled
:ssl => nil # true or default is false
)
## Create a callback for checking response of Publish
#my_callback = lambda { |message| puts(message) }
## Execute Publish
pubnub.publish(
:channel => :hello_world,
:message => "hi",
:callback => #my_callback
)
## Sometimes you need a sleep depending on your server type
sleep(1)

ActionMailer::Base::NullMail when trying exception_notification in development

I'd like to add the exception_notification gem to our app, however, this happens when I try to manually trigger a mail:
exception
# => #<ZeroDivisionError: divided by 0>
ExceptionNotifier::Notifier.exception_notification(request.env, exception)
# => #<ActionMailer::Base::NullMail:0x007fa81bc7c610>
ExceptionNotifier::Notifier.background_exception_notification(exception)
# => #<ActionMailer::Base::NullMail:0x007fa81bf58190>
In the above example, the console is at a breakpoint inside rescue_from Exception in the ApplicationController after a deliberate 1/0 in some controller.
I'm using delayed_job as well, but - no surprise - ExceptionNotifier::Notifier.background_exception_notification(exception).deliver does not spool anything.
I've already set config.consider_all_requests_local = false in development, but still exception_notification instantiates NullMail. In other parts of the app, mailers work just fine and use sendmail.
Any ideas what I'm doing wrong here? Thanks for your help!
Likely you are using an old version of the ExceptionNotifier and a newer version of ActiveMailer::Base. Not calling the mail command within the email functionality will result in the ActionMailer::Base::NullMail instance returned rather than a Mail instance.
From documentation:
class Notifier < ActionMailer::Base
default :from => 'no-reply#example.com',
:return_path => 'system#example.com'
def welcome(recipient)
#account = recipient
mail(:to => recipient.email_address_with_name,
:bcc => ["bcc#example.com", "Order Watcher <watcher#example.com>"])
end
end
I had my tests / rspec returning NullMail objects. the solution was simple, my code was:
def my_mail(foo)
mail(
to: to,
from: from,
subject: #sample_item.campaign_market.campaign.translation_for(language_id, 'sample_item_mailer.request_review.subject'),
content_type: "text/html"
)
#sample_item.update_attributes!({feedback_requested: true, review_requested_at: Time.now})
TrackingService::Event.new(#user, #user.market, 'sample_items', "request_review_email #{#sample_item.id}").call()
end
what's not immediately clear from the ruby docs is that you need to return the mail function,not just execute it. If you need to do something after building the mail object make sure you return the mail at the end. like so:
def my_mail(foo)
m = mail(
to: to,
from: from,
subject: #sample_item.campaign_market.campaign.translation_for(language_id, 'sample_item_mailer.request_review.subject'),
content_type: "text/html"
)
#sample_item.update_attributes!({feedback_requested: true, review_requested_at: Time.now})
TrackingService::Event.new(#user, #user.market, 'sample_items', "request_review_email #{#sample_item.id}").call()
return m
end

Resources