How to subscribe a Pubnub channel asynchronous? - ruby-on-rails

I want my rails app to subscribe a global channel, so everything happens on client, then client will publish into that channel. I want it to be asynchronous because there will be a lot of messages via that channels, and I want it to run along with Rails process. Currently, I can't get it to work, I put it initializers/pubnub.rb:
$pubnub.subscribe(channel: 'global', callback: ->(envelop) { do_something })
I don't get any incoming messages.

Just an usage example in my test app:
$pubnub = Pubnub.new(
:subscribe_key => "demo",
:publish_key => "demo",
:heartbeat => 10,
:logger => Rails.logger
)
ActiveRecord::Base.establish_connection
$pubnub.subscribe(:channel => :demo){|e| Message.create(:content => e.msg)}
It works just fine. What code You are trying to run in the callback?

Related

Redis error on websocket-rails when sending an event to a specific client

I am using 'threadsocket-rails'branch of websocket-rails gem and RedisCloud service of heroku with memory size 30MB.(link: https://elements.heroku.com/addons/rediscloud)
In my config, I have enable channel synchronization and set redis_options as:
config.redis_options = { :host => APP_CONFIG['REDIS_CLOUD_HOST'],
:port => APP_CONFIG['REDIS_CLOUD_PORT'],
:password => APP_CONFIG['REDIS_CLOUD_PASSWORD']}
When android or ios devices trigger the event, they get this empty hash (when I use redis):
["add_to_channel",{},{"id":null,"channel":null,"user_id":null,"success":false,"result":null,"token":null,"server_token":null}]
I also get this error:
NameError Exception: undefined local variable or method `sync' for #<WebsocketRails::UserManager::LocalConnection:0x007fe271873c18>
Otherwise they get correct response("message":"user join new channel"):
["add_to_channel",{"message":"user join new channel"},{"id":null,"channel":null,"user_id":null,"success":false,"result":null,"token":null,"server_token":null}]
I use this code to send an event to a specific client:
WebsocketRails.users[recipient_id].send_message('add_to_channel', {:message => message[:body]})

How to track API calls on my ruby on rails app using google analytics?

I created an API for external applications to log in or make specific web calls using OAuth. What I'm looking for is a way to track the number of times these API calls are being used.
Is there an option for me?
You could send the events with the measurement protocol.
require "net/http"
require "uri"
uri = URI.parse("http://www.google-analytics.com/collect")
Net::HTTP.post_form(uri, {"v" => "1",
"tid" => "UA-XXXX-1",
"cid" => "555",
"t" => "event",
"ec" => "API",
"ea" => "request",
"el" => "data/get",
"ev" => "5"})
I believe you can do this with Google Events:
https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
There are various Ruby libraries for interacting with GA.

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)

Analytics API integration rails failing on heroku production

I am currently developing a ruby on rails application which includes the gattica gem to fetch Google Analytics data. When I fetch my data:
https://github.com/activenetwork/gattica
gs = Gattica.new({:email => 'johndoe#google.com', :password => 'password', :profile_id => 123456})
results = gs.get({ :start_date => '2008-01-01',
:end_date => '2008-02-01',
:dimensions => 'browser',
:metrics => 'pageviews',
:sort => '-pageviews'})
on development I will simply receive a response which I can parse to my application.
However on production the page returns a 500 error and in my Gmail inbox I receive a message about a suspicious login being caught.
Is there any way I can fix this issue?
PS: my application is hosted on Heroku.
With kind regards,
Dennis
You're getting the 500 error because Google is blocking your heroku ip from accessing your account. They aren't sure it's you.
You need to change your activity settings to authorize that ip/domain.
Read this: https://support.google.com/accounts/answer/1144110?hl=en&ref_topic=2401957
Also, its a good idea to read your logs when debugging these kinds of errors. Rails.logger.debug results could shed some light.

Persisting thread in delayed_job

So I have a rails app where I want my delayed job process to communicate with an SMPP server. But the problem occurs when I try to send the messages. My thread that I created in an initializer (delayed_job.rb):
if $0.ends_with?('/delayed_job')
require_relative '../../lib/gateway'
config = {
:host => 'SERVER.COM',
:port => 2345,
:system_id => 'USERNAME',
:password => 'PASSWORD',
:system_type => '', # default given according to SMPP 3.4 Spec
:interface_version => 52,
:source_ton => 0,
:source_npi => 1,
:destination_ton => 1,
:destination_npi => 1,
:source_address_range => '',
:destination_address_range => '',
:enquire_link_delay_secs => 60
}
Thread.new{
gw = Gateway.new
gw.start(config)
}
end
But checking my log file for the smpp server, it seems that the thread dies right after it starts. So I guess my question is how to persist the thread while the delayed_job daemon is running?
If I start my rails app in production and I try to send messages individually, it works without a problem, but because delayed_job is a separate process, I can't communicate with the the smpp thread in the rails app from my workers in the delayed_job queues.
Any ideas?
Sorted, decided to separate everything into their own daemons and each would communicate with the database independently as opposed to trying to work with pipes and signals.

Resources