Ruby: CLI progress bar with open-uri - ruby

I'm trying to experiment with the open-uri and want to make a Command line interface progress bar.
I've going over the documentation for OpenURI::OpenRead where is has a progress bar code sample.
pbar = nil
open('latest.zip', 'wb') do |fo|
fo.print open('http://wordpress.org/latest.zip',
:content_length_proc => lambda { |t|
if t && 0 < t
pbar = ProgressBar.new("...", t)
pbar.file_transfer_mode
end
},
:progress_proc => lambda {|s|
pbar.set s if pbar
}).read
end
but I'm can keep getting the following error:
zip_dowloader.rb:11:in `block (2 levels) in <main>': uninitialized constant ProgressBar (NameError)

gem install progressbar
Then add:
require 'progressbar'
to the top of your script.
Or, in a bundler-enabled project, add:
gem 'progressbar'
to your Gemfile and run bundle install.

Related

undefined method `entry_mapping' for nil:NilClass

I am trying to play around with the RODA Ruby web framework based on Rack. However, I am having issues with using Minitest with the framework. RSpec was hectic with it too unlike Rails. I tried to reproduce the error with pry, but I couldn't make sense of it. How should I fix this? I am getting
undefined method `entry_mapping' for nil:NilClass.
Below is the associated code:
Gemfile
gem 'contentful_model', '~> 1.3' # ActiveModel-like wrapper for the Contentful SDKs
group :test do
gem 'capybara'
gem 'minitest', '>= 5.7.0'
gem 'minitest-hooks', '>= 1.1.0'
gem "minitest-global_expectations"
gem "warning"
gem 'pry'
end
models/recipe.rb
require 'contentful_model'
class Recipe < ContentfulModel::Base
self.content_type_id = 'recipe'
def self.all_recipes
all.load!
end
end
app.rb | Tree Routing
require './.env' if File.exist?(".env.rb")
require './config/initializers/contentful_model'
require 'roda'
require './models/recipe'
require 'tilt/sass'
class App < Roda
hash_routes do
view '', 'index'
end
route do |r|
#recipes = Recipe.all_recipes
r.public
r.assets
check_csrf!
r.hash_routes('')
r.get String do |id|
#recipe_details = Recipe.find(id)
next unless #recipe_details
view 'show'
end
end
end
spec/models/spec_helper.rb
ENV["RACK_ENV"] = "test"
require_relative '../../models/recipe'
require_relative '../minitest_helper'
spec/models/recipe_spec.rb
require_relative 'spec_helper'
describe Recipe do
let(:recipes) { Recipe.all_recipes }
describe '.all_recipes' do
it 'return all records with content type recipe' do
recipes = Recipe.all_recipes # undefined method `entry_mapping' for nil:NilClass
expect(recipes).to all must_be Recipe
end
end
end
pry debug
From: /Users/tiwa/RubymineProjects/marley-spoon-roda/spec/models/recipe_spec.rb:27 .all_recipes#test_0001_return all records with content type recipe:
24: it 'return all records with content type recipe' do
25: recipes = Recipe.all_recipes # undefined method `entry_mapping' for nil:NilClass
26: binding.pry
=> 27: expect(recipes).to all must_be Recipe
28: end
[1] pry(#<.all_recipes>)> Recipe.all_recipes
NoMethodError: undefined method `entry_mapping' for nil:NilClass
from /Users/tiwa/.gem/ruby/2.7.1/gems/contentful_model-1.3.0/lib/contentful_model/base.rb:124:in `mapping?'
I see the code in contentful_model-1.3.0/lib/contentful_model/base.rb:124 is:
ContentfulModel.configuration.entry_mapping.key?(#content_type_id)
If error msg is undefined method `entry_mapping' for nil:NilClass then
ContentfulModel.configuration
Is nil
To fix this you need configure ContentfulModel. Something like that:
ContentfulModel.configure do |config|
config.access_token = "your access token in here" # Required
config.preview_access_token = "your preview token in here" # Optional - required if you want to use the preview API
config.management_token = "your management token in here" # Optional - required if you want to update or create content
config.space = "your space id in here" # Required
config.environment = "master" # Optional - defaults to 'master'
config.default_locale = "en-US" # Optional - defaults to 'en-US'
config.options = { # Optional
# Extra options to send to the Contentful::Client and Contentful::Management::Client
# See https://github.com/contentful/contentful.rb#configuration
# Optional:
# Use `delivery_api` and `management_api` keys to limit to what API the settings
# will apply. Useful because Delivery API is usually visitor facing, while Management
# is used in background tasks that can run much longer. For example:
delivery_api: {
timeout_read: 6
},
management_api: {
timeout_read: 100
}
}
end
With this config this call is not more nil
ContentfulModel.configuration
See https://github.com/contentful/contentful_model

Dependency Injection causing both Rspec failure and IRB failure

Note: I am a Ruby and programming novice.
I have a class called JourneyLog I am trying to get a method called start to instantiate a new instance of another class, called Journey
class JourneyLog
attr_reader :journey_class
def initialize(journey_class: Journey)
#journey_class = journey_class
#journeys = []
end
def start(station)
journey_class.new(entry_station: station)
end
end
When I go into irbi get the following issue
2.2.3 :001 > require './lib/journeylog'
=> true
2.2.3 :002 > journeylog = JourneyLog.new
NameError: uninitialized constant JourneyLog::Journey
from /Users/BartJudge/Desktop/Makers_2018/oystercard-challenge/lib/journeylog.rb:4:in `initialize'
from (irb):2:in `new'
from (irb):2
from /Users/BartJudge/.rvm/rubies/ruby-2.2.3/bin/irb:15:in `<main>'
2.2.3 :003 >
I also have the following Rspec test
require 'journeylog'
describe JourneyLog do
let(:journey) { double :journey, entry_station: nil, complete?: false, fare: 1}
let(:station) { double :station }
let(:journey_class) { double :journey_class, new: journey }
describe '#start' do
it 'starts a journey' do
expect(journey_class).to receive(:new).with(entry_station: station)
subject.start(station)
end
end
end
I get the following Rspec failure;
1) JourneyLog#start starts a journey
Failure/Error: expect(journey_class).to receive(:new).with(entry_station: station)
(Double :journey_class).new({:entry_station=>#<Double :station>})
expected: 1 time with arguments: ({:entry_station=>#<Double :station>})
received: 0 times
# ./spec/jorneylog_spec.rb:9:in `block (3 levels) in <top (required)>'
I am at a total loss on what the problem is, or where to look for some answers.
I'm assuming I'm not injecting the Journey class properly, but thats as far as I can get myself.
Could someone provide some assistance?
In the journeylog.rb file you need to load the Journey class:
require 'journey' # I guess the Journey class is defined in lib/journey.rb
In the spec file you need to pass journey_class to the JourneyLog constructor:
describe JourneyLog do
subject { described_class.new(journey_class: journey_class) }
# ...

rake spec failed, it cannot load or find constant or global variable

I create standalone rspec test script to testing existing api framework. It works pretty well, but I found problem where in the Rakefile I need to assign some value from YAML file (uri link, email) either CONSTANT or $global_var the code in the Rakefile looks like this:
require 'rubygems'
require 'bundler/setup'
require 'yaml'
require 'rspec/core/rake_task'
task :default => :spec
desc 'Running rspec test'
task :spec, :option do |t, opt|
choice = opt[:choice]
if choice == "production"
puts 'Test running on production'
VAR = YAML::load(File.read(File.expand_path("../config/prod_variable.yml", __FILE__)))
elsif choice == "development"
puts 'Test running on development'
VAR = YAML::load(File.read(File.expand_path("../config/dev_variable.yml", __FILE__)))
end
puts VAR['URI'] #=> print out the value correctly
RSpec::Core::RakeTask.new do |task|
test = Rake.application.original_dir
task.fail_on_error = false
task.rspec_opts = '--format documentation --color'
end
end
When I run the rake command on the terminal, the rspec failed find the VAR constant value. Here is the error message from rspec
Failures:
1) ApiTest Testing API platform for GET request
Failure/Error: #var = ApiTest.new(VAR['URI'] ,
NameError:
uninitialized constant VAR
# ./rspec_test/api_test/api_test_get_spec.rb:8:in `block (2 levels) in <top (required)>'
2) ApiTest Testing API platform for POST request
Failure/Error: #zat = ApiTest.new(VAR['URI'] ,
NameError:
uninitialized constant VAR
# ./rspec_test/api_test/api_test_post_spec.rb:7:in `block (2 levels) in <top (required)>'
Is there any idea how to get this works? I need to get value from VAR constant or global variable, but seems ruby failed to assign the value.
If opt[:choice] is neither "production" nor "development", VAR is undefined in your code.

Disable editing of QTableView in rubyqt

I'm trying to disable editing of QTableView in rubyqt. It's supposed to be done by setting triggers to QAbstractView::NoEdiTriggers:
TableView.setEditTriggers(QAbstractView::NoEditTriggers);
The trouble is, rubyqt doesn't recognize Qt::AbstractView:
irb(main):008:0> require 'Qt4'
=> true
irb(main):009:0> Qt::AbstractView
NameError: uninitialized constant Qt::AbstractView
from (irb):9:in `const_missing'
from (irb):9
from /usr/bin/irb:12:in `<main>'
Is there another way to disable editing with ruby and qt?
EDIT
Oh, and outside of irb:
searcher.rb:72:in `const_missing': uninitialized constant Qt::AbstractView (NameError)
And searcher.rb:72:
#ui.tableView.setEditTriggers(Qt::AbstractView::NoEditTriggers)
Changing it to (Qt::AbstractView.NoEditTriggers) doesn't work, neither.
require 'Qt4'
Qt::Application.new(ARGV) do
Qt::Widget.new do
self.window_title = 'Hello QtRuby v1.0'
resize(200, 100)
button = Qt::PushButton.new('Quit') do
connect(SIGNAL :clicked) { Qt::Application.instance.quit }
end
tv = Qt::TableView.new do
setEditTriggers(Qt::TableView::NoEditTriggers)
end
tm = Qt::StandardItemModel.new(1, 1) do
setItem(0,0,Qt::StandardItem.new("aaa"))
end
tv.setModel tm
self.layout = Qt::VBoxLayout.new do
add_widget(tv, 0, Qt::AlignRight)
add_widget(button, 0, Qt::AlignCenter)
end
show
end
exec
end
The main idea is that if no Abstract class from Qt is binded to Ruby, try looking for it's ancestors or implementations.

Simple use of EM::Synchrony#sync causes 'root fiber' FiberError -- my fault?

This program
require 'em-synchrony' ## v1.0.0
require 'em-hiredis' ## v0.1.0
module EventMachine
module Hiredis
class Client
def self.connect(host = 'localhost', port = 6379)
conn = new(host, port)
EM::Synchrony.sync conn.connect
conn
end
alias :old_method_missing :method_missing
def method_missing(sym, *args)
EM::Synchrony.sync old_method_missing(sym, *args)
end
end
end
end
EventMachine.synchrony do
redis = EM::Hiredis.connect
redis.set('foo', 'bar')
puts redis.get('foo')
EM.stop
end
dies like this
$ ruby /tmp/reddy.rb
/home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-synchrony-1.0.0/lib/em-synchrony.rb:58:in `yield': can't yield from root fiber (FiberError)
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-synchrony-1.0.0/lib/em-synchrony.rb:58:in `sync'
from /tmp/reddy.rb:16:in `method_missing'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/client.rb:119:in `select'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/client.rb:38:in `block in connect'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/event_emitter.rb:8:in `call'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/event_emitter.rb:8:in `block in emit'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/event_emitter.rb:8:in `each'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/event_emitter.rb:8:in `emit'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-hiredis-0.1.0/lib/em-hiredis/connection.rb:15:in `connection_completed'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-1.0.0.beta.4/lib/eventmachine.rb:179:in `run_machine'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-1.0.0.beta.4/lib/eventmachine.rb:179:in `run'
from /home/blt/.rvm/gems/ruby-1.9.3-p0/gems/em-synchrony-1.0.0/lib/em-synchrony.rb:27:in `synchrony'
from /tmp/reddy.rb:22:in `<main>'
I find this deeply confusing. Why doesn't it work and am I at fault? If so, what can I do differently? Unless I've glossed over something, this is kosher, per the em-synchrony README.
I think your code can work if you find the correct version of em-hiredis it is trying to monkey patch, that is one problem with loose dependencies.
Here is a fully working code but based on the master branch of em-synchrony:
Gemfile:
source :rubygems
gem 'em-synchrony', :git => "git://github.com/igrigorik/em-synchrony.git"
gem 'em-hiredis', '~> 0.1.0'
test.rb:
require 'rubygems'
require 'bundler/setup'
require 'em-synchrony'
require 'em-synchrony/em-hiredis'
EventMachine.synchrony do
redis = EM::Hiredis.connect
redis.set('foo', 'bar')
puts redis.get('foo')
EM.stop
end
and then run it with:
$ bundle
$ ruby test.rb
Monkey patching is an inherently flawed way of patching gems unless you ensure the exact version of the gem you patched is used which is something em-synchrony should enforce or at least detect.

Resources