rails model action check - ruby-on-rails

I have Coupon model and in this model file I have a suitable_for_use method.I want to list Coupons if coupon.suitable_for_use == true.Is there any short way to do this ? I wrote this code but it doesn't work.
#coupons = []
coupons = Coupon.all.each do |coupon|
if coupon.suitable_for_use
#coupons << coupon
end
end
#coupons = coupons
suitable_for_use method
def suitable_for_use
result = true
if is_used?
result = false
elsif self.start > Time.now.in_time_zone
result = false
elsif self.end < Time.now.in_time_zone
result = false
end
return result
end

The problem is your assigning twice to #coupons. The return value from each is the collection it was given. So your last line reassigns the original set of coupons returned by Coupon.all.
#coupons = Coupon.all.select(&:suitable_for_use)
If your not sure what that does, here's the expanded version.
#coupons = Coupon.all.select {|coupon| coupon.suitable_for_select}
Basically, select takes a block that it will iterate over and if the block returns true then it will add that element to the returned collection. So any coupon that returns false will not be returned by select.
The &:suitable_for_use is called a symbol to proc. It literally expands to the block in the second line and is pretty common in ruby one-liners.

Related

array.select not iterating through every element

I have a rails controller and this code only loop through the first element in the metrics array? Why is that?
# /metrics/:id
def values
#metric = metrics.select do |metric|
id = metric['href'].split('/').last
p "id == params[:id] = #{id == params[:id]}" # false on the first iteration (but never gets to the next iteration
return id == params[:id]
end
p "HERE?" # We never get here!
end
You need to remove the return statement from your method, Ruby uses implicit return (see https://jtrudell.github.io/blog/ruby_return_values/), so the result of a block is the last line that is evaluated in that block, the return statement in your code is treated as a return from the values method. Your method needs to look something like:
def values
#metric = metrics.select do |metric|
metric['href'].split('/').last == params[:id]
end
end

Wrong return value when calling a method

I need to Add a tractor_beam instance method that takes a string description of an item as a parameter (e.g., "cow"). When called, the method should disable the shield, add the item to the inventory along with the ship's current location if it isn't too heavy to pick up (see algorithm below), enable the shield again, and return true. If the item is too heavy to pick up, the method should skip the inventory update and return false.
Algorithm:
An item is too heavy to pick up if its letters add up to more than 500. using .ord (Not very scientific, i know.) For example, the letters of cow add up to 329, so our tractor beam can abduct a cow, no problem.
My problem is that it returns nil and an empty hash, how do i break down the item to add each together?
Code:
class Spaceship
attr_accessor :name, :location, :item, :inventory
attr_reader :max_speed
def initialize (name, max_speed, location)
puts "Initializing new Spaceship"
#name = name
#max_speed = max_speed
#location = location
#item = item
#inventory = {}
end
def disable_shield
puts "Shield is off!"
end
def enable_shield
puts "Shield is on!"
end
def warp_to(location)
puts "Traveling at #{max_speed} to #{location}!"
#location = location
end
def tractor_beam(item)
disable_shield
item = item.split('')
item.each do |let|
let.ord
let + let.next
end
return item
if item > 500
enable_shield
#inventory[#location] = item
return true
else
return false
end
end
end
Driver Code:
uss_enterprise = Spaceship.new("USS Enterprise","200,000 mph", "China")
hms_anfromeda = Spaceship.new("HMS Andromeda", "108,277 mph", "China")
uss_enterprise.disable_shield
hms_anfromeda.enable_shield
p hms_anfromeda.location
hms_anfromeda.warp_to("Namibia")
p hms_anfromeda.location
hms_anfromeda.tractor_beam("cow")
p hms_anfromeda.item
Terminal:
Initializing new Spaceship
Initializing new Spaceship
Shield is off!
Shield is on!
"China"
Traveling at 108,277 mph to Namibia!
"Namibia"
Shield is off!
nil
Firstly, you have a return statement before your if conditional, so the conditional will never be ran. Remove that.
Secondly, you get the weight of the item by using ord, but you aren't assigning the value to anything:
item.each do |let|
let.ord
let + let.next
end
return item
if item > 500
This should do the trick:
item = item.split('')
weight = 0
item.each do |let|
weight += let.ord # add the ord of this letter to the weight
end
if weight > 500 # weight is now the ord of each letter of item 'cow'
enable_shield
#inventory[#location] = item
return true
else
return false
end
This line return item in your tractor_beam method will get run every time before getting to your if statement I think that is causing the problem.
Also you are not using the instance variable #item that you are created in the initialize method I think you might actually want something like this:
def tractor_beam(item)
disable_shield
#item = item.split('')
weight = 0
#item.each do |let|
weight += let.ord
end
if weight < 500
enable_shield
#inventory[#location] = #item
return true
else
return false
end
end
end

Ruby on Rails - Validating columns of a CSV file by calling validation methods with the inject method

Here is the RoR code which I want to use to validate columns in a csv file.
But the values from the "rowdata" array is not passed to the validation methods. Any help is greatly appreciated.
#Ruby on Rails code
def validate_rows
count_row=0
##passed_file is a csv file which is read from a submitted html form.
#parsed_file=CSV::Reader.parse(params[:dump][:csvfile])
#parsed_file.each do |row|
# Array of columns to be validated
validate_cols = [:admission_no, :class_roll_no]
rowdata={'admission_no'=>row[0],'class_roll_no'=>row[1]}
#validate colums by sending value from the array (rowdata) to a method injected
#by the following code. However value from rowdata array is not passed
#to the method.
if count_row >=1
valid = validate_cols.inject(true){|valid_sum, col|
valid_sum && send("validate_#{col}", rowdata[col])
}
#if validation fails return row number.
if not (valid)
return count_row
end
end
count_row=count_row+1
end
#if validation suceeds return 0
return 0
end
#The following methods are called by the inject funnction (valid)
def validate_admission_no(passed_value)
if(passed_value)
return true
else
return false
end
end
def validate_class_roll_no(passed_value)
if(passed_value)
return true
else
return false
end
end
My suggestion is to use strings instead of symbols
def validate_rows
count_row=0
##passed_file is a csv file which is read from a submitted html form.
#parsed_file=CSV::Reader.parse(params[:dump][:csvfile])
#parsed_file.each do |row|
# Array of columns to be validated
validate_cols = ["admission_no", "class_roll_no"]
rowdata={'admission_no'=>row[0],'class_roll_no'=>row[1]}
#validate colums by sending value from the array (rowdata) to a method injected
#by the following code. However value from rowdata array is not passed
#to the method.
if count_row >=1
valid = validate_cols.inject(true){|valid_sum, col|
valid_sum && send("validate_#{col}", rowdata["#{col}"])
}
#if validation fails return row number.
if not (valid)
return count_row
end
end
count_row=count_row+1
end
#if validation suceeds return 0
return 0
end

ruby on rails check if value exist in array always returns true

I am trying to check if a set pset(aka problem set) exist in an array in order to display the correct page but the following code always returns true...
def c
allowed_psets = [1]
pset_id = 12323
if allowed_psets.include?(pset_id)
//do something here
else
render_404//error
end
end
do i miss something here?
working code:
def c
allowed_psets = [
1
]
pset_id = params[:pset_id]
if allowed_psets.include?(pset_id.to_i)
#do something here
else
render_404#error
end
end

Rails - Triggering Flash Warning with method returning true

I'm trying to trigger a warning when a price is entered too low. But for some reason, it always returns true and I see the warning regardless. I'm sure there something wrong in the way I'm doing this as I'm really new to RoR.
In model:
def self.too_low(value)
res = Class.find_by_sql("SELECT price ……. WHERE value = '#{value}'")
res.each do |v|
if #{value} < v.price.round(2)
return true
else
return false
end
end
end
In controller:
#too_low = Class.too_low(params[:amount])
if #too_low == true
flash[:warning] = 'Price is too low.'
end
I would write it somewhat different. You iterate over all items, but you are only interested in the first element. You return from inside the iteration block, but for each element the block will be executed. In ruby 1.9.2 this gives an error.
Also i would propose using a different class-name (Class is used to define a class)
So my suggestion:
Class YourGoodClassName
def self.too_low(amount)
res = YourGoodClassName.find_by_sql(...)
if res.size > 0
res[0].price.round(2) < 1.00
else
true
end
end
end
You can see i test if any result is found, and if it is i just return the value of the test (which is true or false); and return true if no price was found.
In the controller you write something like
flash[:warning] = 'Price is too low' if YourGoodClassName.too_low(params[:amount])

Resources