How to customize cron job in ruby application? - ruby

I have been developing a backend with padrino ruby framework and I would like to build a cron job.
This is what I have done.
gem 'whenever', :require => false
wheneverize .
inside schedule.rb
every 1.minute do
rake "cronjob"
end
/tasks/cronjob.rake
Here I added my custom tasks. and this will be to long to add here.
So I wrote only error happening parts
performances = Performance.left_join(:slots, id: :slot_id).where(Sequel.~(status: ModelA::Api.settings.pending),Sequel[:slots][:from]>oneweekbefore,Sequel[:slots][:to]<onemonthafter+1.day)
....
begin
data = {}
data[:from] = "** <postmaster#**.mailgun.org>"
data[:to] = email
data[:subject] = subject
data[:html] = render 'mails/sendemailbasedontime',:locals => { :data => localdata }
RestClient.post GigabitArtist::Api.settings.mailgun_domain, data
rescue => exception
puts exception.inspect
end
end
I got these errors:
SEQUEL DEPRECATION WARNING: Passing multiple arguments as filter
arguments when not using a conditions specifier
([#:!=, #args=>[:status,
"pending"]>, #:>,
#args=>[#"slots",
#column=>:from>, Sat, 02 Dec 2017]>, #:<, #args=>[#"slots",
#column=>:to>, Wed, 10 Jan 2018]>]) is deprecated and will be removed
in Sequel 5. Pass the arguments to separate filter methods or use
Sequel.& to combine them.
/Users/whitesnow/.rvm/gems/ruby-2.4.1/gems/sequel-4.46.0/lib/sequel/dataset/query.rb:1296:in
filter_expr'
/Users/whitesnow/.rvm/gems/ruby-2.4.1/gems/sequel-4.46.0/lib/sequel/dataset/query.rb:1249:in
add_filter'
/Users/whitesnow/.rvm/gems/ruby-2.4.1/gems/sequel-4.46.0/lib/sequel/dataset/query.rb:1034:in
where'
/Volumes/Data/Work/RBP/GAB/tasks/cronjob.rake:12:inblock in '
/Users/whitesnow/.rvm/gems/ruby-2.4.1#global/gems/rake-12.0.0/lib/rake/task.rb:250:in
block in execute'
/Users/whitesnow/.rvm/gems/ruby-2.4.1#global/gems/rake-12.0.0/lib/rake/task.rb:250:in
each'
/Users/whitesnow/.rvm/gems/ruby-2.4.1#global/gems/rake-12.0.0/lib/rake/task.rb:250:in
execute'
/Users/whitesnow/.rvm/gems/ruby-2.4.1#global/gems/rake-12.0.0/lib/rake/task.rb:194:in
block in invoke_with_call_chain'
/Users/whitesnow/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/monitor.rb:214:in
mon_synchronize'
/Users/whitesnow/.rvm/gems/ruby-2.4.1#global/gems/rake-12.0.0/lib/rake/task.rb:187:in
invoke_with_call_chain'
I think errors are from sequel querying and
data[:html] = render 'mails/sendemailbasedontime',:locals => { :data => localdata }
ofcourse, this query was tested in other .rb file and I tested with raw sql. for example, I tested this tasks inside get request hander of test.rb controller. and it does work well
I would like to know if I can use render function inside task.
I searched all day for this problem with no success.
Any advice will be big help for me.
Thank you very much.

As the deprecation warning states, you are passing multiple arguments to a filter method. The simplest fix would be to call a filter method separately for each argument:
performances = Performance.
left_join(:slots, id: :slot_id).
exclude(status: ModelA::Api.settings.pending).
where(Sequel[:slots][:from]>oneweekbefore).
where(Sequel[:slots][:to]<onemonthafter+1.day)

Related

Sinatra: params hash cannot be merged

I want to merge a hash with default parameters and the actual parameters given in a request. When I call this seemingly innocent script:
#!/usr/bin/env ruby
require 'sinatra'
get '/' do
defaults = { 'p1' => 'default1', 'p2' => 'default2' }
# params = request.params
params = defaults.merge(params)
params
end
with curl http://localhost:4567?p0=request then it crashes with
Listening on localhost:4567, CTRL+C to stop
2016-06-17 11:10:34 - TypeError - no implicit conversion of nil into Hash:
sinatrabug:8:in `merge'
sinatrabug:8:in `block in <main>'
When I access the Rack request.params directly it works. I looked into the Sinatra sources but I couldn't figure it out.
So I have a solution for my actual problem. But I don't know why it works.
My question is: Why can I assign param to a parameter, why is the class Hash but in defaults.merge params it throws an exception?
Any idea?
This is caused by the way Ruby handles local variables and setter methods (i.e. methods that end in =) with the same name. When Ruby reaches the line
params = defaults.merge(params)
it assumes you want to create a new local variable named params, rather than use the method. The initial value of this variable will be nil, and this is the value that the merge method sees.
If you want to refer to the method, you need to refer to it as self.params=. This is for any object that has such a method, not just Sinatra.
A better solution, to avoid this confusion altogether, might be to use a different name. Something like:
get '/' do
defaults = { 'p1' => 'default1', 'p2' => 'default2' }
normalized_params = defaults.merge(params)
normalized_params.inspect
end
Your code is throwing an error because params is nil when you make this call defaults.merge(params). I assume you are trying to merge defaults with request.params, which should contain the parameters from your GET.
Change this line
params = defaults.merge(params)
to this
params = defaults.merge(request.params)
I found this in rack gem
http://www.rubydoc.info/gems/rack/Rack/Request#params-instance_method
It seems you can retrieve GET and POST data by params method but you can't write in it. You have to use update_param and delete_param instead.

Get Asana Projects using Ruby

I am currently trying to get the list of projects I have on my asana account and post them on a webpage. I have already set up my oauth in Ruby which works. I am having issues figuring out now how to call the asana API for the projects. Here is the code that I am currently using:
get '/workspaces' do
if $client
"<h1>Workspaces</h1>" \
#u1 is an unordered html bulleted list; li defines the list item
$client.workspaces.find_all.each do |workspace|
get "\t* #{workspace.name} - projects:"
$client.projects.find_by_workspace(workspace: workspace.id).each do |projects|
get "\t\t- #{projects.name}"
"<ul>" + $client.projects.find_all.map { |w| "<li>#{w.name}</li>" }.join + "</ul>"
end
end
else
redirect '/sign_in'
end
end
I am getting the error message :
undefined method `get' for #
file: app.rb location: block (2 levels) in <class:SinatraApp> line: 42
What other method should I be using other than get?
It looks like you want to output the values. Use puts if you want output it into your console.
puts "\t* #{workspace.name} - projects:"
However, I noticed you are using redirect "/sign_in". I assume you are using some kind of framework? Then, use your framework's output methods.

Rails 4 & mail-2.5.4 - NoMethodError: undefined method `ascii_only?' for nil:NilClass

This error occurs on production server randomly not for every user. we are using sidekiq for delayed jobs and mandrill for emails. Please find the error backtrace form Airbrake.
My ActionMailer Method is:
def auto_reply(email, subject, message)
mail(to: email, body: message, subject: subject)
end
/gems/mail-2.5.4/lib/mail/fields/common/parameter_hash.rb:44 in block in encoded
/gems/mail-2.5.4/lib/mail/fields/common/parameter_hash.rb:43 in map
/gems/mail-2.5.4/lib/mail/fields/common/parameter_hash.rb:43 in encoded
/gems/mail-2.5.4/lib/mail/fields/content_type_field.rb:113 in encoded
/gems/mail-2.5.4/lib/mail/field.rb:167 in method_missing
/gems/mail-2.5.4/lib/mail/header.rb:206 in block in encoded
/gems/mail-2.5.4/lib/mail/header.rb:205 in each
/gems/mail-2.5.4/lib/mail/header.rb:205 in encoded
/gems/mail-2.5.4/lib/mail/message.rb:1801 in encoded
/gems/mail-2.5.4/lib/mail/body.rb:153 in block in encoded
/gems/mail-2.5.4/lib/mail/parts_list.rb:11 in block in collect
/gems/mail-2.5.4/lib/mail/parts_list.rb:11 in each
/gems/mail-2.5.4/lib/mail/parts_list.rb:11 in collect
/gems/mail-2.5.4/lib/mail/body.rb:153 in encoded
/gems/mail-2.5.4/lib/mail/message.rb:1803 in encoded
/gems/actionmailer-4.0.8/lib/action_mailer/base.rb:475 in set_payload_for_mail
/gems/actionmailer-4.0.8/lib/action_mailer/base.rb:455 in block in deliver_mail
/gems/activesupport-4.0.8/lib/active_support/notifications.rb:159 in block in instrument
/gems/activesupport-4.0.8/lib/active_support/notifications/instrumenter.rb:20 in instrument
/gems/activesupport-4.0.8/lib/active_support/notifications.rb:159 in instrument
/gems/actionmailer-4.0.8/lib/action_mailer/base.rb:454 in deliver_mail
/gems/mail-2.5.4/lib/mail/message.rb:232 in deliver
/gems/sidekiq-3.2.4/lib/sidekiq/extensions/action_mailer.rb:20 in perform
/gems/sidekiq-3.2.4/lib/sidekiq/processor.rb:52 in block (2 levels) in process
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/chain.rb:122 in call
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/chain.rb:122 in block in invoke
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/server/active_record.rb:6 in call
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/chain.rb:124 in block in invoke
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/server/retry_jobs.rb:74 in call
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/chain.rb:124 in block in invoke
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/server/logging.rb:11 in block in call
/gems/sidekiq-3.2.4/lib/sidekiq/logging.rb:22 in with_context
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/server/logging.rb:7 in call
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/chain.rb:124 in block in invoke
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/chain.rb:127 in call
/gems/sidekiq-3.2.4/lib/sidekiq/middleware/chain.rb:127 in invoke
/gems/sidekiq-3.2.4/lib/sidekiq/processor.rb:51 in block in process
/gems/sidekiq-3.2.4/lib/sidekiq/processor.rb:94 in stats
/gems/sidekiq-3.2.4/lib/sidekiq/processor.rb:50 in process
/gems/celluloid-0.16.0/lib/celluloid/calls.rb:26 in public_send
/gems/celluloid-0.16.0/lib/celluloid/calls.rb:26 in dispatch
/gems/celluloid-0.16.0/lib/celluloid/calls.rb:122 in dispatch
/gems/celluloid-0.16.0/lib/celluloid/cell.rb:60 in block in invoke
/gems/celluloid-0.16.0/lib/celluloid/cell.rb:71 in block in task
/gems/celluloid-0.16.0/lib/celluloid/actor.rb:357 in block in task
/gems/celluloid-0.16.0/lib/celluloid/tasks.rb:57 in block in initialize
/gems/celluloid-0.16.0/lib/celluloid/tasks/task_fiber.rb:15 in block in create
Some of your three variables : email, subject, or message are nil.
I also had this problem - using Rails 4.1 no matter what I did when I tried to send out an email I always got the dreaded
NoMethodError (undefined method `ascii_only?' for nil:NilClass):
For me the problem was related to my mailer settings - one of the components, in this case the SMTP Server Name, was not set up correctly.
I use a local file for semi-secret settings, so my configuration looked like this:
config.action_mailer.smtp_settings = {
:authentication => :plain,
:address => SECRET['SMTP_HOST'],
:port => SECRET['SMTP_PORT'],
:domain => SECRET['SMTP_DOMAIN'],
:user_name => SECRET['SMTP_USER'],
:password => SECRET['SMTP_PASS']
}
The SECRET hash is read in application.rb like this
secrets_file = "#{ENV['HOME']}/.secrets/myapp.yml"
SECRET = File.exists?(secrets_file) ? YAML.load_file(secrets_file) : {}
And the myapp.yml file then simply contains key-value pairs in YAML format.
The reason I got the ascii_only? nil error was because I was simply missing on of the SMTP settings (in my case the :address) - and that caused the error.

Updating test case in rally by ruby

I am trying to update test case of a particular scenario. But it saying that undefined method update for :test_case symbol.
Need help on this..
My updating method is....
def dataValidInput(featName,testCase)
fields = {:workspace => #rally["workspace"],
:project => #rally["project"],
:work_product => featName,
:test_case => testCase,
:validation_input => #step_name,
:name => testCase}
test_case = #slm.update(:test_case,fields)
end
Am getting output as...
undefined method `update' for :test_case:Symbol (NoMethodError)
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rally_rest_api-1.1.0/lib /rally_rest_api/rally_rest.rb:105:in `update'
C:/Users/CukesRally/features/CreateTC10.rb:176:in `nilValidInput'
C:/Users/CukesRally/features/CreateTC10.rb:154:in `chek_Steps'
C:/Users/CukesRally/features/CreateTC10.rb:132:in `find_or_create_test_case'
C:/Users/CukesRally/features/CreateTC10.rb:104:in `after_features'
C:/Users/CukesRally/features/CreateTC10.rb:93:in `before_test_case'
My Command :
cucumber C:/Users/CukesRally/features/Plan.feature --format MyTest::CreateStep
Thanks
First of all, I see that you're using an outdated gem. Please switch to using the rally_api gem. The latest version is 1.1.2: https://rubygems.org/gems/rally_api/versions/1.1.2
Then, if you still need help, please point me to a repo where the code is located or provide a gist link. I'd like to know where #slm and :work_product are defined as they seem to be the source of your error.

Confusion with Ruby to save the files with any extensions to the excel columns

I am creating a script to insert the files from folders to the Excel columns, but it seems I am doing wrong. Can any one help me for the same?
updated Ruby Code:
require 'fileutils'
require 'win32ole'
#Excel Application will be started from here.
#--------------------------------------------
excel = WIN32OLE.new('Excel.Application')
excel.visible = true
wb=excel.workbooks.open("E:\\WIPData\\Ruby\\Scripts\\Copy of GSL_File_DownLoad1.xlsx")
wbs= wb.Worksheets(1)
rows=2
column=2
until wbs.cells(rows,1).value == nil do
Dir.entries("E:\\WIPData\\Ruby").each do |f|
if f == wbs.cells(rows,1).value then
files_dir = File.expand_path("..", Dir.pwd)
column=2
Dir.foreach(files_dir.concat("/" + f)) do |x|
full_path=files_dir.concat("/" + x)
wbs.cells(rows,column).Select
wbs.oleobjects.add({
'Filename' => full_path,
'Link' => true,
'DisplayAsIcon' => false,
})
column = column + 1
end
break
end
end
end
wb.Save
wb.Close(0)
excel.Quit()
#Excel Application will be finished here.
#------------
Error:
E:/WIPData/Ruby/Scripts/test.rb:27:in `method_missing': (in OLE method `add': )
(WIN32OLERuntimeError)
OLE error code:800A03EC in Microsoft Excel
Cannot insert object.
HRESULT error code:0x80020009
Exception occurred.
from E:/WIPData/Ruby/Scripts/test.rb:27:in `block (2 levels) in <main>'
from E:/WIPData/Ruby/Scripts/test.rb:23:in `foreach'
from E:/WIPData/Ruby/Scripts/test.rb:23:in `block in <main>'
from E:/WIPData/Ruby/Scripts/test.rb:17:in `each'
from E:/WIPData/Ruby/Scripts/test.rb:17:in `<main>'
Your problem is on line 25 in your code. It is the method wbs.OLEObjects.Add(,full_path,False,True,,,f) that is causing the problem.
In VBA, it is perfectly fine to leave parameters to a method blank if they are not required. However, this is not available in Ruby.
In your original Macro, you passed keyword arguments to the method. One way of doing this in Ruby is with a Hash. An article on the Ruby on Windows blog suggests doing it like so:
wbs.oleobjects.add({
'Filename' => full_path,
'Link' => false,
'DisplayAsIcon' => true,
'IconIndex' => 0,
'IconLabel' => f,
'IconFileName' => icon_path
})
I did not see you provide an icon path in your Ruby code so I'm making an assumption on that final variable.
Also note that true and false are lowercase. Uppercase versions would be read by Ruby as either a constant or a class.
If you are doing work in Microsoft Office with Ruby, I would highly recommend frequenting Ruby on Windows. The author doesn't appear to post anymore but it is still a relevant source.
EDIT:
Your new error is probably due to Dir.entries. This method will grab . and .. when it pulls entries. I'd imagine Excel is tripping up on trying to add those two to the Worksheet.
There are two ways to remove this.
1) Skip them in your each block.
Dir.entries("E:\\WIPData\\Ruby").each do |f|
next if ['.', '..'].include? f
# The rest of your block code
end
2) Use Dir#glob which will not return . and ..
Dir.chdir("E:\\WIPData\\Ruby")
Dir.glob('*').each do |f|
# Your block code
end
EDIT:
For documentation's sake, this topic is also discussed on Ruby Forums.

Resources