Reset a counter in Ruby - ruby

I have the following code to compile jobs from github jobs API. How do I reset a counter back to 0 every time I call on a new city? I've tried putting it in several different places with no luck.
def ft_count_and_percentage
##url += #city
uri = URI(##url)
response = Net::HTTP.get(uri)
result = JSON.parse(response)
result.each do |job|
if job["type"] == "Full Time"
##fulltime_count += 1
end
end
puts "Total number of jobs in #{#city}: #{result.length}"
if ##fulltime_count > 0
puts ("full time percent ") + "#{(##fulltime_count/result.length) * 100}"
else
puts "No FT Positions"
end
end
##fulltime_count is defined outside this method to start at 0. Currently, as expected the counter just keeps adding jobs every time I add a new city.
boston = Job.new("Boston")
boston.ft_count_and_percentage
sf = Job.new("San Francisco")
sf.ft_count_and_percentage
la = Job.new("Los Angeles")
la.ft_count_and_percentage
denver = Job.new("Denver")
denver.ft_count_and_percentage
boulder = Job.new("Boulder")
boulder.ft_count_and_percentage
chicago = Job.new("Chicago")
chicago.ft_count_and_percentage
ny = Job.new("New York City")
ny.ft_count_and_percentage

You may need to reset it inside Job init
class Job
def initialize
##count = 0
end
def ft_count_and_percentage
#the blah you already have
end
end

Related

How to update an attribute after create or update

I’m new to rails and I’m trying to figure out the following.
I’ve got a class Order which has attributes name, status and radius. The possible status are [draft, posted, taken]. The radius can change from 500 to 5k incrementing 500 each time a loop runs. I would like to know how can I make the radius to change depending on the status and the time that has pass.
If #order.status = draft, then status = 500.
If #order.status = posted, then the radius’ value will start with 500 but increment by 500 every 10 seconds until it gets to 40.
If #order.status = taken, then the radius’ value will be equal to whatever the radius is when the status changed to taken.
if order.status != taken after the 40 seconds, the #order.status = draft and #order.radius = 500
The following code runs well in ruby for visualization only, if you copied an run it on the teminal you will see it running well.
count = 1
initial_radius = 500
puts "Enter the status: "
status = gets
status = status.chomp
while status == 'posted' && count < 4 # this will be the one deciding (n) #times for 10k max radius of search otherwise get back to draft
puts ""
puts "Run #{count}"
radius = 500
puts "Radius = #{radius}"
n = 1
while status == 'posted' && n <10
status = 'posted'
puts " Status is now = #{status.capitalize}! "
sleep(1)
puts "n = #{n}"
puts "Enter the status: "
status = gets
status = status.chomp
n += 1
start = Time.now
puts "Radius = #{radius}"
end
if status == 'posted'
count += 1
radius *= count
puts "New Radius = #{radius}"
elsif status == 'taken'
radius *= count
puts ""
puts "Order has been Taken with radius #{radius}!!"
puts ""
end
#radius = 500 This was removed as it didn't affect
end
if status == 'taken'
puts ""
else
puts ""
puts "No company took the order"
puts "Order has gone back to status Draft and its radius is #{initial_radius} "
puts ""
end
But when I try the following to see how the server behaves and I create a new Order it hangs until it finishes processing any order that has been placed before. I know that it hangs because of the sleep method. The code below is done only to see how it will behave. It does update the radius after 15 seconds but no one would like to use an application that needs to wait until someone else finish their bit.
Order model
after_save :change_radius, on: [:create, :update]
def change_radius
if self.status == 'posted'
sleep 15
update_column(:radius, 1000)
elsif self.status == 'draft'
update_column(:radius, 500)
end
end
My question is. How can I make it to work so it will be possible for any other user to use the application (create an order) without any hanging until it finish dealing with another user’s order. I think it may need use of Active jobs or something similar but unsure how to set it up if this is the case. I would appreciate any guidance on this matter.
For a process that takes a long time to complete, consider putting it in a background process. I would check out using sidekiq with redis. It's a good option for background processing.

Two version of the same code not giving the same result

I am trying to implement a simple timeout class that handles timeouts of different requests.
Here is the first version:
class MyTimer
def handleTimeout mHash, k
while mHash[k] > 0 do
mHash[k] -=1
sleep 1
puts "#{k} : #{mHash[k]}"
end
end
end
MAX = 3
timeout = Hash.new
timeout[1] = 41
timeout[2] = 5
timeout[3] = 14
t1 = MyTimer.new
t2 = MyTimer.new
t3 = MyTimer.new
first = Thread.new do
t1.handleTimeout(timeout,1)
end
second = Thread.new do
t2.handleTimeout(timeout,2)
end
third = Thread.new do
t3.handleTimeout(timeout,3)
end
first.join
second.join
third.join
This seems to work fine. All the timeouts work independently of each other.
Screenshot attached
The second version of the code however produces different results:
class MyTimer
def handleTimeout mHash, k
while mHash[k] > 0 do
mHash[k] -=1
sleep 1
puts "#{k} : #{mHash[k]}"
end
end
end
MAX = 3
timeout = Hash.new
timers = Array.new(MAX+1)
threads = Array.new(MAX+1)
for i in 0..MAX do
timeout[i] = rand(40)
# To see timeout value
puts "#{i} : #{timeout[i]}"
end
sleep 1
for i in 0..MAX do
timers[i] = MyTimer.new
threads[i] = Thread.new do
timers[i].handleTimeout( timeout, i)
end
end
for i in 0..MAX do
threads[i].join
end
Screenshot attached
Why is this happening?
How can I implement this functionality using arrays?
Is there a better way to implement the same functionality?
In the loop in which you are creating threads by using Thread.new, the variable i is shared between main thread (where threads are getting created) and in the threads created. So, the value of i seen by handleTimeout is not consistent and you get different results.
You can validate this by adding a debug statement in your method:
#...
def handleTimeout mHash, k
puts "Handle timeout called for #{mHash} and #{k}"
#...
end
#...
To fix the issue, you need to use code like below. Here parameters are passed to Thread.new and subsequently accessed using block variables.
for i in 0..MAX do
timers[i] = MyTimer.new
threads[i] = Thread.new(timeout, i) do |a, b|
timers[i].handleTimeout(a, b)
end
end
More on this issue is described in When do you need to pass arguments to Thread.new? and this article.

Refactor the Ruby CLI program

I'm new to programming in Ruby.
How do I make the output show Revenue and Profit or Loss?
How can I refactor the following code to look neater? I know it's wrong but I have no idea how to take my if profit out of the initialize method.
class Theater
attr_accessor :ticket_price, :number_of_attendees, :revenue, :cost
def initialize
puts "What is your selling price of the ticket?"
#ticket_price = gets.chomp.to_i
puts "How many audience are there?"
#number_of_attendees = gets.chomp.to_i
#revenue = (#number_of_attendees * #ticket_price)
#cost = (#number_of_attendees * 3) + 180
#profit = (#revenue - #cost)
if #profit > 0
puts "Profit made: $#{#profit}"
else
puts "Loss incurred: $#{#profit.abs}"
end
end
end
theater = Theater.new
# theater.profit
# puts "Revenue for the theater is RM#{theater.revenue}."
# I hope to put my Profit/Loss here
#
# puts theater.revenue
Thanks guys.
Do not initialize the object with input from the user, make your object accept the needed values. Make a method to read the needed input and return you new Theater. Last of all put the if in separate method like #report_profit.
Remember constructors are for setting up the initial state of the object, making sure it is in a valid state. The constructor should not have side effects(in your case system input/output). This is something to be aware for all programming languages, not just ruby.
Try this:
class Theatre
COST = { running: 3, fixed: 180 }
attr_accessor :number_of_audience, :ticket_price
def revenue
#number_of_audience * #ticket_price
end
def total_cost
COST[:fixed] + (#number_of_audience * COST[:running])
end
def net
revenue - total_cost
end
def profit?
net > 0
end
end
class TheatreCLI
def initialize
#theatre = Theatre.new
end
def seek_number_of_attendes
print 'Number of audience: '
#theatre.number_of_audience = gets.chomp.to_i
end
def seek_ticket_price
print 'Ticket price: '
#theatre.ticket_price = gets.chomp.to_i
end
def print_revenue
puts "Revenue for the theatre is RM #{#theatre.revenue}."
end
def print_profit
message_prefix = #theatre.profit? ? 'Profit made' : 'Loss incurred'
puts "#{message_prefix} #{#theatre.net.abs}."
end
def self.run
TheatreCLI.new.instance_eval do
seek_ticket_price
seek_number_of_attendes
print_revenue
print_profit
end
end
end
TheatreCLI.run
Notes:
Never use your constructor (initialize method) for anything other than initial setup.
Try to keep all methods under 5 lines.
Always try to keep each class handle a single responsibility; for instance, printing and formatting output is not something the Theatre class needs to care.
Try extracting all hard coded values; eg see the COST hash.
Use apt variables consistent to the domain. Eg: net instead of profit makes the intent clear.

error when creating hash in simple Credit Card class for ruby

I am creating a simple CC class that can create and update a credit card. To do this, I have created cc_bal{} as an instance object so it can update respect credit cards. The hash is to save and update a person and the amount on their cc. I end up getting an output of just the original amount that was created and not the updated amount
Heres the code:
class CC
def initialize(cc_name, cc_bal = {}, open_cc = false)
#cc_name = cc_name
#cc_bal = cc_bal
#open_cc = open_cc
end
def create(initAmount, person)
if initAmount > 0
#open_cc = true
#cc_bal[:person]=initAmount
puts "congrats #{person} on opening your new #{#cc_name} CC! with $#{#cc_bal[:person]}"
else
puts "sorry not enough funds"
end
end
def update(amount, person)
if #open_cc == true
#cc_bal[:person] + amount
else
puts "sorry no account created, #{person}"
end
puts "#{person} has CC balance of #{#cc_bal[:person]}"
end
end
#chase = Bank.new("JP Morgan Chase")
#wells_fargo = Bank.new("Wells Fargo")
me = Person.new("Shehzan", 500)
friend1 = Person.new("John", 1000)
#chase.open_account(me)
#chase.open_account(friend1)
#wells_fargo.open_account(me)
#wells_fargo.open_account(friend1)
#chase.deposit(me, 200)
#chase.deposit(friend1, 300)
#chase.withdraw(me, 50)
#chase.transfer(me, wells_fargo, 100)
#chase.deposit(me, 5000)
#chase.withdraw(me, 5000)
#puts chase.total_cash_in_bank
#puts wells_fargo.total_cash_in_bank
credit_card = CC.new("Visa")
credit_card.create(10,me)
credit_card.update(50,me)
credit_card.create(20,friend1)
credit_card.update(40,friend1)
Please disregard the function calls that are commented out.
Any idea why the CC's are not updatiing?
if #open_cc == true
#cc_bal[:person] + amount
else
You increase the amount, but you don't set the new value anywhere. It should be
if #open_cc == true
#cc_bal[:person] += amount
else
Note. The code needs some serious refactoring and cleanup.

Calling multiple methods on a CSV object

I have constructed an Event Manager class that performs parsing actions on a CSV file, and produces html letters using erb. It is part of a jumpstart labs tutorial
The program works fine, but I am unable to call multiple methods on an object without the earlier methods interfering with the later methods. As a result, I have opted to create multiple objects to call instance methods on, which seems like a clunky inelegant solution. Is there a better way to do this, where I can create a single new object and call methods on it?
Like so:
eventmg = EventManager.new("event_attendees.csv")
eventmg.print_valid_phone_numbers
eventmg_2 = EventManager.new("event_attendees.csv")
eventmg_2.print_zipcodes
eventmg_3 = EventManager.new("event_attendees.csv")
eventmg_3.time_targeter
eventmg_4 = EventManager.new("event_attendees.csv")
eventmg_4.day_of_week
eventmg_5 = EventManager.new("event_attendees.csv")
eventmg_5.create_thank_you_letters
The complete code is as follows
require 'csv'
require 'sunlight/congress'
require 'erb'
class EventManager
INVALID_PHONE_NUMBER = "0000000000"
Sunlight::Congress.api_key = "e179a6973728c4dd3fb1204283aaccb5"
def initialize(file_name, list_selections = [])
puts "EventManager Initialized."
#file = CSV.open(file_name, {:headers => true,
:header_converters => :symbol} )
#list_selections = list_selections
end
def clean_zipcode(zipcode)
zipcode.to_s.rjust(5,"0")[0..4]
end
def print_zipcodes
puts "Valid Participant Zipcodes"
#file.each do |line|
zipcode = clean_zipcode(line[:zipcode])
puts zipcode
end
end
def clean_phone(phone_number)
converted = phone_number.scan(/\d/).join('').split('')
if converted.count == 10
phone_number
elsif phone_number.to_s.length < 10
INVALID_PHONE_NUMBER
elsif phone_number.to_s.length == 11 && converted[0] == 1
phone_number.shift
phone_number.join('')
elsif phone_number.to_s.length == 11 && converted[0] != 1
INVALID_PHONE_NUMBER
else
phone_number.to_s.length > 11
INVALID_PHONE_NUMBER
end
end
def print_valid_phone_numbers
puts "Valid Participant Phone Numbers"
#file.each do |line|
clean_number = clean_phone(line[:homephone])
puts clean_number
end
end
def time_targeter
busy_times = Array.new(24) {0}
#file.each do |line|
registration = line[:regdate]
prepped_time = DateTime.strptime(registration, "%m/%d/%Y %H:%M")
prepped_time = prepped_time.hour.to_i
# inserts filtered hour into the array 'list_selections'
#list_selections << prepped_time
end
# tallies number of registrations for each hour
i = 0
while i < #list_selections.count
busy_times[#list_selections[i]] += 1
i+=1
end
# delivers a result showing the hour and the number of registrations
puts "Number of Registered Participants by Hour:"
busy_times.each_with_index {|counter, hours| puts "#{hours}\t#{counter}"}
end
def day_of_week
busy_day = Array.new(7) {0}
d_of_w = ["Monday:", "Tuesday:", "Wednesday:", "Thursday:", "Friday:", "Saturday:", "Sunday:"]
#file.each do |line|
registration = line[:regdate]
# you have to reformat date because of parser format
prepped_date = Date.strptime(registration, "%m/%d/%y")
prepped_date = prepped_date.wday
# adds filtered day of week into array 'list selections'
#list_selections << prepped_date
end
i = 0
while i < #list_selections.count
# i is minus one since days of week begin at '1' and arrays begin at '0'
busy_day[#list_selections[i-1]] += 1
i+=1
end
#busy_day.each_with_index {|counter, day| puts "#{day}\t#{counter}"}
prepared = d_of_w.zip(busy_day)
puts "Number of Registered Participants by Day of Week"
prepared.each{|date| puts date.join(" ")}
end
def legislators_by_zipcode(zipcode)
Sunlight::Congress::Legislator.by_zipcode(zipcode)
end
def save_thank_you_letters(id,form_letter)
Dir.mkdir("output") unless Dir.exists?("output")
filename = "output/thanks_#{id}.html"
File.open(filename,'w') do |file|
file.puts form_letter
end
end
def create_thank_you_letters
puts "Thank You Letters Available in Output Folder"
template_letter = File.read "form_letter.erb"
erb_template = ERB.new template_letter
#file.each do |line|
id = line[0]
name = line[:first_name]
zipcode = clean_zipcode(line[:zipcode])
legislators = legislators_by_zipcode(zipcode)
form_letter = erb_template.result(binding)
save_thank_you_letters(id,form_letter)
end
end
end
The reason you're experiencing this problem is because when you apply each to the result of CSV.open you're moving the file pointer each time. When you get to the end of the file with one of your methods, there is nothing for anyone else to read.
An alternative is to read the contents of the file into an instance variable at initialization with readlines. You'll get an array of arrays which you can operate on with each just as easily.
"Is there a better way to do this, where I can create a single new object and call methods on it?"
Probably. If your methods are interfering with one another, it means you're changing state within the manager, instead of working on local variables.
Sometimes, it's the right thing to do (e.g. Array#<<); sometimes not (e.g. Fixnum#+)... Seeing your method names, it probably isn't.
Nail the offenders down and adjust the code accordingly. (I only scanned your code, but those Array#<< calls on an instance variable, in particular, look fishy.)

Resources