Rotten Tomatoes API with Ruby - ruby-on-rails

I'm new to Ruby & trying out this API. I want to build a simple game which asks an user for two movies names to guess / compare which one received a better audience rating or any other comparative parameter. The API is working and I tried substituting the code with the user input but that's where it breaks down. (I have also mentioned the class I am calling)
require_relative 'workspace/lib/select'
require_relative 'workspace/lib/brand'
require 'json'
require 'rest-client'
# puts "hello world"
def create_reviewer
puts "What is your name?"
name = gets.strip
puts "So, #{name} what genre are you interested in?"
genre = gets.strip
Select.new(name, genre)
end
def create_brand
puts "Enter the first brand"
brand_a = gets.strip
puts "Enter the second brand"
brand_b = gets.strip
Brand.new(brand_a, brand_b)
end
review = create_reviewer
brands = create_brand
def get_rotten_tomatoes
response = JSON.load(RestClient.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=SECRET&q=#{brand_a}&page_limit=30'))
response["movies"].map do |entry|
brand_a = entry["ratings"]["audience_score"]
brand_b = entry["ratings"]["critics_score"]
final_score = {brand_a: audience_score, brand_b: critics_score}
final_score
end
goodies = get_rotten_tomatoes
puts goodies
----
class Brand
attr_accessor :brand_a, :brand_b
def initialize(name, genre)
#brand_a = brand_a
#brand_b = brand_b
end
# def to_s
# "Tenant: #{#name} \n Credit Score: #{#credit_score}."
# end
end

Related

I want to concatenate two values into a single string

I have two different values systolic and diastolic blood pressure readings in string. When those two values come from front-end I'll store them into a single string, e.g., if systolic ='120' and diastolic='80' I want bp='120/80'
module Api
module V1
module CheckinMachine
class BpsController < ApplicationController
include MachineError
before_action :authenticate_user!
def create
raise BatteryNotFunctionalError if battery_functional?
# user = User.find_by!(bp_machine_imei: params[:imei])
health_reading = current.health_readings.create!(key: :blood_pressure, value: bp_value)
Solera::PostActivityApi.call(user,
bp,
health_reading.solera_activities.new)
head :ok
rescue ActiveRecord::RecordNotFound => _e
render_machine_error and return
end
def show
puts params
end
private
def bp
{
systolic_blood_pressure: params[:systolic],
diastolic_blood_pressure: params[:diastolic]
}
end
end
end
end
end
That's what i have tried, what do i do to make it exactly like i want it to be
like bp = '120/80'
Since you already have the 2 values stored in params, this is super easy:
bp = " #{params[:systolic] / #{params[:diastolic]} "
> bp = " 120/80 "
Remember that Ruby has the variable substitution in strings using the #{x} syntax where x is a variable value.
So for instance:
x = "apples"
y = 5
string = "I have #{y} units of #{x} to sell you"
puts(string)
> "I have 5 units of apples to sell you"

Parse API and Show Output in Rails View

So, I wrote a program that sends a get request to HappyFox (a support ticket web app) and I get a JSON file, Tickets.json.
I also wrote methods that parse the JSON and return a hash with information that I want, i.e tickets with and without a response.
How do I integrate this with my Rails app? I want my HappyFox View (in rails) to show the output of those methods, and give the user the ability to refresh the info whenever they want.
Ruby Code:
require 'httparty'
def happy_fox_call()
auth = { :username => 'REDACTED',
:password => 'REDACTED' }
#tickets = HTTParty.get("http://avatarfleet.happyfox.com/api/1.1/json/tickets/?size=50&page=1",
:basic_auth => auth)
tickets = File.new("Tickets.json", "w")
tickets.puts #tickets
tickets.close
end
puts "Calling API, please wait..."
happy_fox_call()
puts "Complete!"
require 'json'
$data = File.read('/home/joe/API/Tickets.json')
$tickets = JSON.parse($data)
$users = $tickets["data"][3]["name"]
Count each status in ONE method
def count_each_status(*statuses)
status_counters = Hash.new(0)
$tickets["data"].each do |tix|
if statuses.include?(tix["status"]["name"])
#puts status_counters # this is cool! Run this
status_counters[tix["status"]["name"]] += 1
end
end
return status_counters
end
Count tickets with and without a response
def count_unresponded(tickets)
true_counter = 0
false_counter = 0
$tickets["data"].each do |tix|
if tix["unresponded"] == false
false_counter += 1
else true_counter += 1
end
end
puts "There are #{true_counter} tickets without a response"
puts "There are #{false_counter} ticket with a response"
end
Make a function that creates a count of tickets by user
def user_count(users)
user_count = Hash.new(0)
$tickets["data"].each do |users|
user_count[users["user"]["name"]] += 1
end
return user_count
end
puts count_each_status("Closed", "On Hold", "Open", "Unanswered",
"New", "Customer Review")
puts count_unresponded($data)
puts user_count($tickets)
Thank you in advance!
You could create a new module in your lib directory that handles the API call/JSON parsing and include that file in whatever controller you want to interact with it. From there it should be pretty intuitive to assign variables and dynamically display them as you wish.
https://www.benfranklinlabs.com/where-to-put-rails-modules/

Array not saving user input in ruby

This is what I have so far, but the array is not saving the first value if the user enters 2 or more car types. If I remove the car.get_ methods the program runs fine without saving the users input. Is there a method I am missing?
class Cars
def set_make(make)
end
def set_model(model)
end
def set_year(year)
end
array_of_cars = Array.new
print "How many cars do you want to create? "
num_cars = gets.to_i
puts
for i in 1.. num_cars
puts
print "Enter make for car #{i}: "
make = gets.chomp
print "Enter model for car #{i}: "
model = gets.chomp
print "Enter year of car #{i}: "
year = gets.to_i
c = Car.new
c.set_make(make)
c.set_model(model)
c.set_year(year)
array_of_cars << c
end
puts
puts "You have the following cars: "
for car in array_of_cars
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
end
Ok so the primary issue is that you calling the Car.new where the Car class is defined. You should not have an array of cars in the car class. You could try creating a Dealership class that has an array of cars then you could do something like this
class Dealership
attr_accessor :car_lot
def initialize
#car_lot = []
end
def add_car(car)
#car_lot << car
end
end
crazy_carls = Dealership.new
car1 = Car.new(make, model, year)
crazy_carls.add_car(car1)
crazy_carls.car_lot.each do |car
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
You need to refactor the car class a good deal first though, look into how to use the initialize method, attr_accessor, and instance variables.

#<IO:<STDOUT>> received :puts with unexpected arguments - Random number and Rspec issue

So im currently using the Learn.co gem in which I am trying to solve a blackjack lab. https://github.com/learn-co-curriculum/simple-blackjack-cli
The following Rspec code expects a specific output which confuses me since we working with random numbers. Here is the Rspec code:
describe "#runner" do
before(:each) do
def get_user_input
"h"
end
end
it "calls on the #welcome method,
then on the #initial_round method,
then calls #hit? and #display_card_total methods
-until- the card sum is greater than 21,
then calls on the #end_game method" do
expect(self).to receive(:deal_card).at_least(3).times.and_return(10)
expect(self).to receive(:get_user_input).and_return("h")
expect($stdout).to receive(:puts).with("Welcome to the Blackjack Table")
expect($stdout).to receive(:puts).with("Your cards add up to 20")
expect($stdout).to receive(:puts).with("Type 'h' to hit or 's' to stay")
expect($stdout).to receive(:puts).with("Your cards add up to 30")
expect($stdout).to receive(:puts).with("Sorry, you hit 30. Thanks for playing!")
runner
end
end
But since we using random numbers in the following code, how can it be the exact output of Rspec. Here is the Ruby code:
def welcome
# code #welcome here
puts "Welcome to the Blackjack Table"
end
def deal_card
randomNumber = rand(1..11)
end
def display_card_total(total_cards)
puts "Your cards add up to #{total_cards}"
return total_cards
end
def prompt_user
puts "Type 'h' to hit or 's' to stay"
end
def get_user_input
letter = gets.chomp
end
def end_game(card_total)
puts "Sorry, you hit #{card_total}. Thanks for playing!"
end
def initial_round
initOne = deal_card()
initTwo = deal_card()
sumInit = initOne + initTwo
display_card_total(sumInit)
end
def hit?(myNumber)
prompt_user()
result = get_user_input()
card_total = myNumber
if result == 's'
return myNumber
elsif result == 'h'
sumInit = myNumber + deal_card()
return sumInit
else
invalid_command()
end
end
def invalid_command
puts "Please enter a valid command"
end
#####################################################
# get every test to pass before coding runner below #
#####################################################
def runner
welcome()
number = initial_round()
until number > 21
hit?(number)
display_card_total(number)
number += hit?(number)
end
end_game(number)
end
How can the output match the Rspec test if we dealing with random numbers?
The following code in the runner method fixed the problem.
def runner
welcome()
number = initial_round()
until number > 21
number = hit?(number)
display_card_total(number)
end
end_game(number)
end

Rails test involving an object that requires an api update

I am trying to get a Bill object to perform tests on. This is a US congress bill, which I have in xml via rsync on a data directory. My code takes in the name of the bill, say "h1.xml", parses the xml and then gets the full text of the bill from www.govtrack.us. So, in my main app, to create a bill
Get a bill name (e.g. h1) (via globbing in the method def self.update_from_directory)
def self.update_from_directory
Dir.glob("#{Rails.root}/data/bills/small_set/*.xml").each do |bill_path|
bill_name = bill_path.match(/.*\/(.*).xml$/)[1]
b = Bill.find_or_create_by(:govtrack_name => bill_name)
b.update_bill
b.save!
end
end
Update the bill
def update_bill
file_data = File.new("#{Rails.root}/data/bills/#{self.govtrack_name}.xml", 'r')
bill = Feedzirra::Parser::GovTrackBill.parse(file_data)
if bill && (self.introduced_date.nil? || (bill.introduced_date.to_date > self.introduced_date))
self.congress = bill.congress
self.bill_type = bill.bill_type
self.bill_number = bill.bill_number
... and so on . . . until:
get_bill_text
Update the bill record with the bill text
def get_bill_text
bill_object = HTTParty.get("#{GOVTRACK_URL}data/us/bills.text/#{self.congress.to_s}/#{self.bill_type}/#{self.bill_type + self.bill_number.to_s}.html")
self.bill_html = bill_object.response.body
self.text_updated_on = Date.today
Rails.logger.info "Updated Bill Text for #{self.ident}"
end
My goal is very simple, I want to mock a whole bill for a test:
def setup
#my_test_bill = Bill.new(:govtrack_id => "h1")
#my_test_bill.update_bill
end
I am trying to get webmock and vcr working, but all the examples I can find, provide a way to mock a specific call and I don't want to have to retype a whole new update_bill method.
Any thoughts greatly appreciated.
Tim
Consider changing your update_bill method to:
def update_bill
file_data = File.new("#{Rails.root}/data/bills/#{self.govtrack_name}.xml", 'r')
bill = Feedzirra::Parser::GovTrackBill.parse(file_data)
if bill && (self.introduced_date.nil? || (bill.introduced_date.to_date > self.introduced_date))
self.congress = bill.congress
self.bill_type = bill.bill_type
self.bill_number = bill.bill_number
# Yield to a block that can perform arbitrary calls on this bill
if block_given?
yield(self)
end
# Fill bill text if empty
if bill_html.blank? && text_updated_on.blank?
get_bill_text
end
end
Then change your setup method to:
def setup
#my_test_bill = Bill.new(:govtrack_id => "h1")
#my_test_bill.update_bill do |bill|
bill.text_updated_on = Date.today
bill.bill_html = "The mock bill contents"
end
end
That may not be exactly the solution, but this kind of approach--passing the receiver back to a block given to the method, allows you to modify the exact behavior of a given method at runtime.

Resources