Ruby daemon script only runs once - ruby-on-rails

I've written a ruby NFC reader script and daemonised it with the daemons gem. It all works great except the script only runs once...
Daemon.rb
require 'rubygems'
require 'daemons'
pwd = File.dirname(File.expand_path(__FILE__))
file = pwd + '/touchatag.rb'
Daemons.run_proc(
'touchatag_project_daemon', # name of daemon
:dir_mode => :normal,
:dir => File.join(pwd, 'tmp/pids'), # directory where pid file will be stored
:backtrace => true,
:monitor => true,
:log_output => true
) do
exec "ruby #{file}"
end
touchatag.rb
quire 'rubygems'
require 'nfc'
require 'httparty'
class TagAssociator
include HTTParty
base_uri 'localhost:3000'
end
NFC.instance.find do |tag|
puts "Processing tag..."
TagAssociator.post('/answers/answer', :query => {:uid => tag.uid})
end
This works great and i'm receiving the tag.uid in my app. But when i scan another RFID tag the script wont run again...
Does anyone know how to adjust the script that it runs "forever" and stops when the daemon is stopped?
Thanks
UPDATE
i updated my daemon.rb script:
require 'rubygems'
require 'daemons'
options = {
:app_name => "touchatag_project_daemon",
:ARGV => ['start', '-f', '--', 'param_for_myscript'],
:dir_mode => :script,
:dir => 'tmp/pids',
:multiple => true,
:ontop => true,
# :mode => :exec,
:backtrace => true,
:monitor => true
}
Daemons.run(File.join(File.dirname(__FILE__), '/touchatag.rb'), options)
But it just runs once... i don't get it any other suggestions?

You almost certainly want to be using Daemon.run. run_proc would be useful if you wanted to move the code from touchtag.rb into Daemon.rb.
http://daemons.rubyforge.org/classes/Daemons.html#M000004

Related

“Uninitialized constant” error when trying to create Client

I am working on dashing dashboard and trying to add a Jira widget.In the widget code it is trying to create and initialize a Client object. As shown in code below
require 'Jira'
SCHEDULER.every '5m', :first_in => 0 do |job|
client = Jira::Client.new({
:username => ENV['Talal'],
:password => ENV['Talal123'],
:site => "http://192.168.99.100:32768",
:auth_type => :basic,
:context_path => "/jira"
})
But as I gets to this line client = Jira::Client.new. An exception occurs which states that uninitialized constant Jira::Client.
I believe the gem you should be using is jira-ruby. Once you install it, Bundler should automatically require it for you, meaning if you're in a Rails environment, you shouldn't need to do require 'Jira'.
If you don't want it required application-wide, BTW, you should add this to your Gemfile:
gem 'jira-ruby', require: false
# then in your scheduler, you have to explicitly require it as before:
require 'jira-ruby'
SCHEDULER.every '5m', :first_in => 0 do |job|
client = Jira::Client.new({
:username => ENV['Talal'],
:password => ENV['Talal123'],
:site => "http://192.168.99.100:32768",
:auth_type => :basic,
:context_path => "/jira"
})
Additional information here

How do I tell a Rails 4 app where my SSL certs are?

I'm trying to tell a Rails 4 app where to find the SSL certificates.
Ww got it working by modifying the bin/rails, adding this
if ENV['SSL'] == "true"
module Rails
class Server < ::Rack::Server
def default_options
super.merge({
:Port => 443,
:environment => (ENV['RAILS_ENV'] || "development").dup,
:daemonize => false,
:debugger => false,
:pid => File.expand_path("tmp/pids/server.pid"),
:config => File.expand_path("config.ru"),
:SSLEnable => true,
:SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
:SSLPrivateKey => OpenSSL::PKey::RSA.new(
File.open("/path/to/my/private/.key").read),
:SSLCertificate => OpenSSL::X509::Certificate.new(
File.open("/path/to/my.cert").read),
:SSLCertName => [["CN", WEBrick::Utils::getservername]],
})
end
end
end
end
all good but I want these setting in my config/environments/staging.rb file instead, and I want it to be non-specific to Webbrick.
Is this the right approach, and
if so, how do I move these settings into config/environments/staging.rb?
The consensus from the comments is:
No, and
see 1.
Thanks #tpbowden and #josh-deeden for your quick responses.

How to speed up sitemap_generator with parallel gem

I am trying to speed up sitemap_generator by adding parallelization via the parallel gem. I have the following code but my groups aren't getting written to the public/sitemaps directory. I am thinking it's due to lambdas getting executed in a different space in parallel. Any feedback would be helpful. Thanks!
#!/usr/bin/env ruby
require 'rubygems'
require 'sitemap_generator'
require 'benchmark'
require 'parallel'
require 'random-word'
SitemapGenerator::Sitemap.default_host = "http://localhost"
a = lambda {
SitemapGenerator::Sitemap.group(:filename => :biz, :sitemaps_path => 'sitemaps/biz/') do
(1..1000).each do |index|
url = "/#{RandomWord.adjs.next}/#{RandomWord.nouns.next}"
add url, :priority => 0.8
end
end
}
b = lambda {
SitemapGenerator::Sitemap.group(:filename => :wedding_ugc, :sitemaps_path => 'sitemaps/ugc') do
(1..1000).each do |index|
url = "/#{RandomWord.adjs.next}/#{RandomWord.nouns.next}"
add url, :priority => 0.8
end
end
}
#working example
# SitemapGenerator::Sitemap.default_host = "http://localhost"
# SitemapGenerator::Sitemap.create(:compress => false) do
# group(:filename => :biz, :sitemaps_path => 'sitemaps/biz/') do
# (1..1000).each do |index|
# url = "/#{RandomWord.adjs.next}/#{RandomWord.nouns.next}"
# add url, :priority => 0.8
# end
# end
# end
puts Time.now
Parallel.each([a,b]){|job| job.call()}
puts Time.now
I got this working and posted the solution on github here
Here is the code incase the url gets broken.
SitemapGenerator::Sitemap.create(:compress => false, :create_index => false) do
group1 = lambda {
group = sitemap.group(:filename => :group1, :sitemaps_path => 'sitemaps/group1') do
Record.find_each do |record|
add '/record/path'
end
end
group.sitemap.write unless group.sitemap.written? #write if not full
}
# group2 like above...
Parallel.each([group1, group2], :in_processes => 8) do |group|
group.call
end
end
#regenerate the index sitemap xml file because I couldn't figure out how to track it with multiple processes
SitemapGenerator::Sitemap.create(:compress => false) do
Dir.chdir(sitemap.public_path.to_s)
xml_files = File.join("**", "sitemaps", "**", "*.xml")
xml_file_paths = Dir.glob(xml_files)
xml_file_paths.each do |file|
add file
end
end

Redis-Objects in rails saves as String, not array

I am using the redis-objects gem to store simple info
class Purchase < ActiveRecord::Base
include Redis::Objects
hash_key :user_purchases, :marshal => true, :global => true # "hash" is taken by Ruby
def self.add_user_end(fb_id,item_id)
if self.user_purchases[fb_id]
a = Array.new
a << candidate_id
self.user_purchases[fb_id] = a
else
new_a = self.user_purchases[fb_id]
new_a << item_id
self.user_purchases[fb_id] = new_a
end
end
end
I'm creating a method to collect user_purchases as a hasy_key, keyed by a users fb id. I would imply like to see a collection of ids when I use Purchase.user_purchases["2"] => [1,23,563,2]
I am running into a problem with Redis::Object where I can only save this as a string: Why?
1.9.3-p125 :050 > Purchase.user_purchases["6"].class
=> String
1.9.3-p125 :051 > Purchase.user_purchases["6"]
=> "\u0004\b[\u0006I\"\v543555\u0006:\u0006ET"
Answer:
My Initialization file was missing require 'redis/list'
require 'redis'
require 'redis/objects'
require 'redis/hash_key'
require 'redis/list'
Redis.current = Redis.new(:host => '127.0.0.1', :port => 6379)
My Initialization file was missing require 'redis/list'
require 'redis'
require 'redis/objects'
require 'redis/hash_key'
require 'redis/list'
Redis.current = Redis.new(:host => '127.0.0.1', :port => 6379)

What is the best Rails Logging Gem

what is the best way of configuring Logging features on a rails project? I'm looking for something like Log4J which is available to Rails. I have found log4r and it's conflicting built in Logger class and also tried 'Logging' gem and It has some issues configuring as a audit logger. Please let me know your suggestions on this topic since I'm a beginner on the subject.
I have used below code block in logging.rb and included in environment.rb
But I'm receiving a error on 'returning' keyword as it's deprecated on rails 2.8
config/environment.rb
# Logging
require File.join(File.dirname(__FILE__), 'logging')
Rails::Initializer.run do |config|
config/logging.rb
require 'logging'
# Logging.init is required to avoid
# unknown level was given 'info' (ArgumentError)
# or
# uninitialized constant Logging::MAX_LEVEL_LENGTH (NameError)
# when an Appender or Layout is created BEFORE any Logger is instantiated:
Logging.init :debug, :info, :warn, :error, :fatal
layout = Logging::Layouts::Pattern.new :pattern => "[%d] [%-5l] %m\n"
# Default logfile, history kept for 10 days
default_appender = Logging::Appenders::RollingFile.new 'default', \
:filename => 'log/default.log', :age => 'daily', :keep => 10, :safe => true, :layout => layout
# Audit logfile, history kept forever
audit_appender = Logging::Appenders::RollingFile.new 'audit', \
:filename => 'log/audit.log', :age => 'daily', :safe => true, :layout => layout
# Production logfile, history kept forever
prod_appender = Logging::Appenders::RollingFile.new 'prod', \
:filename => 'log/production.log', :age => 'daily', :safe => true, :layout => layout
DEFAULT_LOGGER = returning Logging::Logger['server'] do |l|
l.add_appenders default_appender
end
Have a look at the following threads:
Rails Logging API
logging in rails app
What's a good logging replacement for rails?
It should be like this:
config/logging.rb
require 'logging'
# Logging.init is required to avoid
# unknown level was given 'info' (ArgumentError)
# or
# uninitialized constant Logging::MAX_LEVEL_LENGTH (NameError)
# when an Appender or Layout is created BEFORE any Logger is instantiated:
Logging.init :debug, :info, :warn, :error, :fatal
layout = Logging::Layouts::Pattern.new :pattern => "[%d] [%-5l] %m\n"
# Default logfile, history kept for 30 days
default_appender = Logging::Appenders::RollingFile.new 'default', \
:filename => "log/#{Rails.env}.log", :age => 'daily', :keep => 30, :safe => true, :layout => layout
log = Logging::Logger[:root]
log.add_appenders default_appender
log.level = :info
Rails.logger = log

Resources