add task automatically to rally using rally REST in ruby - ruby

From the below sample code i am able to test the working to list all Tasks in a project.
I want to add New tasks Automatically under a User Story US1234.
I have some 50 User Story in excel to Enter with Task fields (Name ,description, estimate ,To do ,etc... ) ,I want to automate this work.
How to create a task under a user story with the Task fields using REST api in ruby.
There was not much of help with this link http://developer.rallydev.com/help/ruby-toolkit-rally-rest-api
require 'rubygems'
require 'rally_rest_api'
rally= RallyRestAPI.new(:base_url =>"https://rally1.rallydev.com/slm", :username => "harsha.gowda#xyz.com", :password => "xyz123")
projects = rally.find(:project) { equal:name, "XYZ Engineering - Scrum Team 2"}
projects.each do |project|
# puts project.name
tasks = rally.find(:task, :project => project, :fetch => true) {equal :State, "Defined"}
tasks.each do |task|
puts task.name
end
end

You should be able to find most of the answers to your questions here: http://rally-rest-api.rubyforge.org/crud.html.
Here is a basic example, which iterates through each Task on a User Story:
require 'rubygems'
require 'rally_rest_api'
rally= RallyRestAPI.new(:base_url => url, :username => user, :password => pw)
project = (rally.find(:project) { equal :name, name}).first()
rally.find(:hierarchical_requirement, :project => project) {equal :some_field, some_value}.each{ |hr|
hr.tasks.each{ |task|
task.update(:some_field1 => some_value1)
task.update(:some_field2 => some_value2)
task.update(:some_field3 => some_value3)
task.update(:some_field4 => some_value4)
}
}
I don't know how you intend on updating each individually, so you'll have to modify it with your own logic.

Related

rails + heroku: point root in routes.rb file to app.rb file

I have a file called app.rb that runs a server when I run it on my local machine. I would like to deploy app.rb to Heroku so the server will run on Heroku. I think I need to make root in routes.rb point it to. How do I do this?
this is the config.ru:
require_relative 'config/environment'
require '/.app.rb'
run Rails.application
run Sinatra::Application
This is the web server code in app.rb, from codepath guides (https://guides.codepath.com/android/Google-Cloud-Messaging#step-3-setup-web-server):
require 'sinatra'
require 'rest-client'
require 'sequel'
# Create a SQLite3 database
DB = Sequel.connect('sqlite://gcm-test.db')
# Create a Device table if it doesn't exist
DB.create_table? :Device do
primary_key :reg_id
String :user_id
String :reg_token
String :os, :default => 'android'
end
Device = DB[:Device] # create the dataset
# Registration endpoint mapping reg_token to user_id
# POST /register?reg_token=abc&user_id=123
post '/register' do
if Device.filter(:reg_token => params[:reg_token]).count == 0
device = Device.insert(:reg_token => params[:reg_token], :user_id => params[:user_id], :os => 'android')
end
end
# Ennpoint for sending a message to a user
# POST /send?user_id=123&title=hello&body=message
post '/send' do
# Find devices with the corresponding reg_tokens
reg_tokens = Device.filter(:user_id => params[:user_id]).map(:reg_token).to_a
if reg_tokens.count != 0
send_gcm_message(params[:title], params[:body], reg_tokens)
end
end
# Sending logic
# send_gcm_message(["abc", "cdf"])
def send_gcm_message(title, body, reg_tokens)
# Construct JSON payload
post_args = {
# :to field can also be used if there is only 1 reg token to send
:registration_ids => reg_tokens,
:data => {
:title => title,
:body => body,
:anything => "foobar"
}
}
# Send the request with JSON args and headers
RestClient.post 'https://gcm-http.googleapis.com/gcm/send', post_args.to_json,
:Authorization => 'key=' + AUTHORIZE_KEY, :content_type => :json, :accept => :json
end
This is the procfile:
web: bundle exec puma -C config/puma.rb
when I follow the getting started with Ruby on Heroku example, I can see the example webpage. However, if I edit the config.ru file with 'run Sinatra::Application', and deploy to heroku, it is not able to show the example webpage anymore, and just says "Not Found"
require '/.app.rb'
This should be ./app.rb instead.

Define a local variable or method in a script

I'm new to ruby and I'm trying to re-structure my script which adds some servers to zabbix monitor etc.The issue that I'm facing is below:
zbx = ZabbixApi.connect(
:url => 'http://zabbixserver.net/zabbix/api_jsonrpc.php',
:user => 'admin',
:password => 'admin'
)
def createtemplate
zbx.templates.create(
:host => "RealDoc MS Template",
:groups => [:groupid => zbx.hostgroups.get_id(:name => "RealDoc")]
) ..../will create Items, graphs etc...
end
if templateid.empty?
createtemplate
else
puts "Template Exists"
end
When is accessing the createtemplate method it's throwing the following error: undefined local variable or method `zbx' for main:Object (NameError)
well zbx isn't in scope, as it isn't a global. you have a couple options.
either pass it into the method
def createtemplate(zbx)
zbx.templates.create(
:host => "RealDoc MS Template",
:groups => [:groupid => zbx.hostgroups.get_id(:name => "RealDoc")]
) ..../will create Items, graphs etc...
end
if templateid.empty?
createtemplate zbx
else
puts "Template Exists"
en
or you can make it global with a $.
$zbx = ZabbixApi.connect(
:url => 'http://zabbixserver.net/zabbix/api_jsonrpc.php',
:user => 'admin',
:password => 'admin'
)
def createtemplate
$zbx.templates.create(
:host => "RealDoc MS Template",
:groups => [:groupid => zbx.hostgroups.get_id(:name => "RealDoc")]
) ..../will create Items, graphs etc...
end
if templateid.empty?
createtemplate
else
puts "Template Exists"
end
I would do the first option, as global variables should be used sparingly, but in such a short script it probably doesn't matter that much..
It's working with adding the variable to our method def createtemplate(zbx)
, and the same thing when you are calling the methood , you will call it with zbx variable.

Run controller as Ruby script?

In my application I setup a news controller to handle news feeds using Nokogiri:
class NewsController < InheritedResources::Base
def new
require 'nokogiri'
require 'open-uri'
doc = Nokogiri::XML(open("http://www.themusicvoid.com/feed"))
#info = doc.xpath('//item').take(5).map do |i|
News.create(:title => i.xpath('title').inner_text,
:description => i.xpath('description').inner_text,
:link => i.xpath('link').inner_text,
:image => i.xpath('image').inner_text)
end
end
end
This functions by running <%= debug #info %> in the new.html.erb file. It searches the RSS feed and automatically saves to my database.
The problem is that it would do this whenever ANYBODY loaded new.html.erb (although I could add that file to my robots.txt so at least bots wouldn't trigger it.)
What I actually want is some sort of a Ruby script or Rake task that would do the exact same thing without loading a page. If I just run the code above as a script, it works, it would output the data if I wanted to echo it, but it does not save the information to the database. Any ideas on how I might do that?
You can create a rake task under lib/tasks directory:
rss_fetcher.rake
require 'nokogiri'
require 'open-uri'
namespace :rss do
desc "Fetch rss feed"
task :fetch => :environment do
doc = Nokogiri::XML(open("http://www.themusicvoid.com/feed"))
#info = doc.xpath('//item').take(5).map do |i|
News.create(:title => i.xpath('title').inner_text, :description => i.xpath('description').inner_text, :link => i.xpath('link').inner_text, :image => i.xpath('image').inner_text)
end
end
end
then somewhere call rake 'rss:fetch'
I highly recommend the whenever gem to do that kind of job
gem install whenever
config/schedule.rb
every 2.hours do
rake "rss:fetch"
end

Share validations across models with rails 4

There are other questions pertaining to this, but they all seems to be < Rails 4, and what's more, they're not too detailed!
They all talk about creating a module to share these common validations in:
require 'active_record'
module ContactValidations
def self.included(base_class)
base_class.class_eval do
include ContactValidations::InstanceMethods
# model validations
validates_presence_of(:name, :message => 'You must provide a company name.')
validates_presence_of(:street, :message => 'You must provide a company street.')
validates_presence_of(:city, :message => 'You must provide a company city.')
validates_presence_of(:post_code, :message => 'You must provide a company post code.')
validates_numericality_of(:telephone, :on => :create, :message => 'Telephone should be a number with no spaces.', :if => :telephone_given?)
validates_numericality_of(:area_code, :on => :create, :message => 'Telephone area code should be a number with no spaces.', :if => :area_code_given?)
validates_numericality_of(:fax, :on => :create, :message => 'Fax should be a number with no spaces.', :if => :fax_given?)
validates_numericality_of(:fax_area_code, :on => :create, :message => 'Fax area code should be a number with no spaces.', :if => :fax_area_code_given?)
validates_format_of(:web, :with => /^((http)?:\/\/)?(www\.)?([a-zA-Z0-9]+)(.[a-zA-Z0-9]{2,3})(\.[a-zA-Z0-9]{2,3})$/, :on => :create, :message => 'Web address is invalid. Example: http://www.domain or http://domain.', :if => :web_given?)
validates_format_of(:email, :with => /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/, :on => :create, :message => 'Th email address given is invalid.', :if => :email_given?)
validates_uniqueness_of(:email, :message => 'This email is already given.')
end
end
module InstanceMethods
def telephone_given?
!telephone.blank?
end
def fax_given?
!fax.blank?
end
def web_given?
!web.blank?
end
def email_given?
!email.blank?
end
def area_code_given?
!area_code.blank?
end
def fax_area_code_given?
!fax_area_code.blank?
end
end
end
But I for one have no idea where such a file should be saved. In the lib directory? All files in the lib directory are included, seems a bit wasteful for a module I only want to be included in a two or three models...
Does Rails 4 have an inbuilt way to share validations?
If not, where should I save my custom module?
And just to be super clear, how should I require this module in the models that need to include these validations?
Create the module in app/models/concerns, then include them in your classes with:
include ContactValidations
In this way Rails will automatically load the shared modules and make them available for you to include.
you should also have a look at validates_with
https://api.rubyonrails.org/v6.0.3.3/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates_with

Sinatra: DB Authentication with Sessions

I am writing a small sinatra application that I am integrating with Authlogic (following https://github.com/ehsanul/Sinatra-Authlogic-Template)
Everything works except for when I try to login. I get the following error:
NameError at /login
undefined local variable or method `active' for #<User:0x000001040208f0>
I am including the authlogic gem versus including it as a vendor. So my Sinatra app is not exactly the same as the one on Github.
Any and all inquiries will be MUCH appreciated!! Thanks!
Found out my issue.
Here is the model according to the Github page:
class User < ActiveRecord::Base
acts_as_authentic do |c|
# Bcrypt is recommended
#crypto_provider = Authlogic::CryptoProviders::BCrypt
c.perishable_token_valid_for( 24*60*60 )
c.validates_length_of_password_field_options =
{:on => :update, :minimum => 6, :if => :has_no_credentials?}
c.validates_length_of_password_confirmation_field_options =
{:on => :update, :minimum => 6, :if => :has_no_credentials?}
end
def active?
active
end
def has_no_credentials?
crypted_password.blank? #&& self.openid_identifier.blank?
end
def send_activation_email
Pony.mail(
:to => self.email,
:from => "no-reply#domain.tld",
:subject => "Activate your account",
:body => "You can activate your account at this link: " +
"http://domain.tld/activate/#{self.perishable_token}"
)
end
def send_password_reset_email
Pony.mail(
:to => self.email,
:from => "no-reply#domain.tld",
:subject => "Reset your password",
:body => "We have recieved a request to reset your password. " +
"If you did not send this request, then please ignore this email.\n\n" +
"If you did send the request, you may reset your password using the following link: " +
"http://domain.tld/reset-password/#{self.perishable_token}"
)
end
end
I removed all of the mail methods but my script was failing on the active? method because it was looking for an active column in the users table. Since I am unable to append this column to the table (due to data integrity with another system) I simply told my method to return true
My User.rb
class UserSession < Authlogic::Session::Base
end
class User < ActiveRecord::Base
acts_as_authentic do |c|
end
def active?
return true
end
end
Hope this helps someone!

Resources