Ruby Guard ignore files - ruby

I would like to run the requirejs optimization script when any .js file is changed (except for built.js).
I read there is an ignore method. I have the following in my Gaurdfile (which is causing an infinite loop).
guard 'shell', :ignore => 'built.js' do
watch(/script\/(.*).js/) { `node r.js -o build.js` }
end
My question is: How do I configure my Guardfile to ignore the file built.js?

First, assuming you already have the guard-shell gem installed...
I think this gives you something to work from given what you are trying to do.
It will ignore the script/build.js file and trigger a shell command when any other .js file changes.
ignore /script\/build.js/
guard :shell do
watch /.*\.js/ do |m|
`yourcommandhere`
msg = "Processed #{m[0]}"
n msg, 'mycustomshellcommand'
"-> #{msg}"
end
end
See this link for Guardfile examples.
See this link for the syntax of guard-shell.

Related

Aruba: Command "seedly-calculator" not found in PATH-variable

So, I am trying to run the test but I am getting an error says.
Aruba::LaunchError:Command "seedly-calculator.rb" not found in PATH-variable
-seedly-calculator
-bin
-src
-seedly-calculator.rb
I have tried to change the path in rake file but it doesn't work.
My seedly-calculator.rb file is in the root directory.
require "rspec/core/rake_task"
namespace :spec do
desc "Run the functional suite against the CLI"
RSpec::Core::RakeTask.new(:functional, [] => [:set_path])
task :set_path do
project_bin_dir = File.join(File.dirname(File.expand_path(__FILE__)), '..', 'bin')
ENV['PATH'] = project_bin_dir + ':'+ ENV['PATH']
end
end
it shows error like:
Failure/Error: let(:command) { run "seedly-calculator.rb" }
Aruba::LaunchError:
Command "seedly-calculator.rb" not found in PATH-variable "/Users/bilaltariq/Desktop/seedly-calculator/functional_spec/bin:/Users/bilaltariq/Desktop/seedly-calculator/functional_spec/exe:/Users/bilaltariq/.rbenv/versions/2.6.2/lib/ruby/gems/2.6.0/bin:/Users/bilaltariq/Desktop/seedly-calculator/functional_spec/../bin:/Users/bilaltariq/.rbenv/versions/2.6.2/bin:/usr/local/Cellar/rbenv/1.1.1/libexec:/Users/bilaltariq/.rbenv/shims:/Users/bilaltariq/.asdf/shims:/Users/bilaltariq/.asdf/bin:/usr/local/bin:/Users/bilaltariq/.bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin".
I expect it to hit the file so i can write some test.
am i doing something wrong?
require 'spec_helper'
RSpec.describe 'Command Validation', type: :aruba do
let(:command) { run "seedly-calculator.rb" }
it "wrong/missing arguments" do
command.write("lookup\n")
stop_all_commands
expect(command.output).to end_with("Missing bank_name argument.\n")
end
end
seedly-calculator.rb:
#!/usr/bin/env ruby
# Complete bin/setup so that after it is
# run, ruby seedly-calculator.rb can be used to launch
# it.
# frozen_string_literal: true
require_relative './src/runner'
if !ARGV.length.zero?
input = ARGV
Runner.new.send('process_input', input)
else
puts "Arguments required!."
end
Update
To run a ruby script using run you need to make sure your ruby script is executable and contains a shebang so your system knows to run it with ruby. Here's example from this starter example
#!/usr/bin/env ruby
file = ARGV[0]
if file.nil? || file.empty?
abort "aruba-test-cli [file]: Filename is missing"
elsif !File.exist? file
abort "aruba-test-cli [file]: File does not exist"
end
puts File.read(file).chomp
So in your case you'll need to add this to the first line of your seedly-calculator.rb file
#!/usr/bin/env ruby
Then run this from command line to make it executable.
chmod +x #!/usr/bin/env ruby
I made a simple example forked off the one I reffed above. See this commit
Rspec convention is that it should match the same file structure of your project. It is not a good idea to set PATH manually.
Rake tasks are normally put in a tasks folder so you should have in project root a tasks folder
my_project/tasks/something.rake
Then you should have a spec folder that matches
my_project/spec/tasks/something_spec.rb
Then you should be able to get rid of task :set_path do end block and just run the spec without that.
You should also have a Gemfile to load your gems, run bundle install then invoke your test with
bundle exec rspec spec/tasks/sometask_spec.rb

Cannot rerun my app with guard or rerun

So I have an app, the tree is something like this:
- Gemfile
- Guardfile
- source/
- dist/
- app.rb
The command to start the server is ruby app.rb ( or require_relative './app.rb', which does the same thing)
I want to run this command and re run it whenever any file changes.
The only exception is the dist/ folder - any file changes in there should be ignored.
Here's my attempt so far with guard and guard-shell (apologies for the code dump):
require 'childprocess'
# Global constant tracking whether the app has been started
RunningProcess = {gen_rb: false}
# Method to stop the app if it's been started
def ensure_exited_server
begin
RunningProcess[:gen_rb] && RunningProcess[:gen_rb].poll_for_exit(10)
rescue ChildProcess::TimeoutError
RunningProcess[:gen_rb].stop # tries increasingly harsher methods to kill the process.
end
nil
end
# Start the app using 'child-process'
def start_app
# prevent 'port in use' errors
ensure_exited_server
# The child-process gem starts a process and exposes its stdout
RunningProcess[:gen_rb] = ChildProcess.build("ruby", "gen.rb")
RunningProcess[:gen_rb].io.inherit!
RunningProcess[:gen_rb].start
nil
end
# Always start the app, not just when a file changes.
start_app
# The guard-shell gem runs a block whenever some set of files has changed.
guard :shell do
# This regex matches anything except the dist/ folder
watch /^[^dist\/].+/ do |m|
start_app
# Print a little message when a file changes.
m[0] + " has changed."
end
nil
end
# Make sure the app does not run after guard exits
at_exit { ensure_exited_server }
This doesn't ever restart my app.
The problem with rerun is something I raised an issue on their repo about: see https://github.com/alexch/rerun/issues/107
How about something like this for your Guardfile?
guard :shell do
watch(%r{^source/.+\.(rb)}) do |m|
`ruby app.rb`
end
watch('app.rb') do |m|
`ruby app.rb`
end
end
Instead of listing which directories to ignore, this watch states which directories/files to use.

Using guard-minitest on a single Ruby file

I'm clearly doing something wrong. I'm trying to write and test plain ruby in a single file. I want guard to watch the file and the test file and run minitest any time either file changes.
So, two files: game.rb and game_test.rb
game.rb
class Game
end
game_test.rb
require 'rubygems'
require 'minitest/autorun'
require './game'
class GameTest < MiniTest::Unit::TestCase
def test_truth
assert true
end
end
I also have a Guardfile that looks like this:
notification :terminal_notifier
guard 'minitest', test_folders: '.' do
watch('game.rb')
watch('game_test.rb')
end
Now, I'm probably forgetting something, but I can't for the life of me figure out what it is.
If I start guard and press Enter, "Run All" happens and the tests run.. at least most of the time. However, I have to press Enter for it to happen.
Also, if I make a change to the files nothing happens. I've tried putting gem 'rb-fsevent' in a Gemfile and running with "bundle exec guard" but that doesn't seem to help either.
Any help would be much appreciated. I'm going nuts.
Thanks,
Jeremy
Your first "watch" definition will simply pass "game.rb", which is not a test file so it won't be run.
The second "watch" is correct so when you save "game_test.rb", the tests should run.
This should be a more correct Guardfile:
notification :terminal_notifier
guard 'minitest', test_folders: '.' do
watch('game.rb') { 'game_test.rb' }
watch('game_test.rb')
end

Using yaml files within gems

I'm just working on my first gem (pretty new to ruby as well), entire code so far is here;
https://github.com/mikeyhogarth/tablecloth
One thing I've tried to do is to create a yaml file which the gem can access as a lookup (under lib/tablecloth/yaml/qty.yaml). This all works great and the unit tests all pass, hwoever when I build and install the gem and try to run under irb (from my home folder) I am getting;
Errno::ENOENT: No such file or directory - lib/tablecloth/yaml/qty.yaml
The code is now looking for the file in ~/lib/tablecloth... rather than in the directory the gem is installed to. So my questions are;
1) How should i change line 27 of recipe.rb such that it is looking in the folder that the gem is installed to?
2) Am I in fact approaching this whole thing incorrectly (is it even appropriate to use static yaml files within gems in this way)?
Well first of all you should refer to the File in the following way:
file_path = File.join(File.dirname(__FILE__),"yaml/qty.yaml")
units_hash = YAML.load_file(filepath)
File.dirname(__FILE__) gives you the directory in which the current file (recipe.rb) lies.
File.join connects filepaths in the right way. So you should use this to reference the yaml-file relative to the recipe.rb folder.
If using a YAML-file in this case is a good idea, is something which is widely discussed. I, myself think, this is an adequate way, especially in the beginning of developing with ruby.
A valid alternative to yaml-files would be a rb-File (Ruby Code), in which you declare constants which contain your data. Later on you can use them directly. This way only the ruby-interpreter has to work and you save computing time for other things. (no parser needed)
However in the normal scenario you should also take care that reading in a YAML file might fail. So you should be able to handle that:
file_path = File.join(File.dirname(__FILE__),"yaml/qty.yaml")
begin
units_hash = YAML.load_file(filepath)
rescue Psych::SyntaxError
$stderr.puts "Invalid yaml-file found, at #{file_path}"
exit 1
rescue Errno::EACCES
$stderr.puts "Couldn't access file due to permissions at #{file_path}"
exit 1
rescue Errno::ENOENT
$stderr.puts "Couldn't access non-existent file #{file_path}"
exit 1
end
Or if you don't care about the details:
file_path = File.join(File.dirname(__FILE__),"yaml/qty.yaml")
units_hash =
begin
YAML.load_file(filepath)
rescue Psych::SyntaxError, Errno::EACCES, Errno::ENOENT
{}
end

How to get rspec-2 to give the full trace associated with a test failure?

Right now if I run my test suite using rake spec I get an error:
1) SegmentsController GET 'index' should work
Failure/Error: get 'index'
undefined method `locale' for #
# ./spec/controllers/segments_controller_spec.rb:14:
in `block (3 levels) in '
This is normal as I do have an error :)
The problem is that the trace isn't very helpful. I know it broke in segments_controller_spec.rb, line 14, but this is just where I call the test:
### segments_controller_spec.rb:14
get 'index'
I would prefer to have the actual line breaking and the complete trace, not the part in the spec folder.
Running with --trace doesn't help.
You must run rspec with -b option to see full backtraces
Another (easier) alternative is to edit the .rspec file, and add the backtrace option.
It should look somewhat like this:
--colour
--backtrace
That will give you the full backtrace.
Hope this helps.
This will also work:
# rails_helper.rb
RSpec.configure do |config|
config.full_backtrace = true
end
Another approach is to clear all backtrace exclusion patterns in spec_helper.rb. I like this solution most as I'm able to keep all RSpec settings in one place and get rid of .rspec file or explicit --backtrace in .travis.yml.
# spec_helper.rb
RSpec.configure do |config|
config.backtrace_exclusion_patterns = []
end
I don't know how to get the controller error to show up in rspec. Sometimes it shows up but I don't know what conditions cause it to show up. Here is a way to see the error fairly quickly though:
Open another terminal session and run:
tail -f log/test.log
Then go back to the terminal session and run just the spec that had the error:
bin/rspec -b spec/requests/posts/index_spec.rb
Go back to the tail of the log and you should see the error, hopefully without too much other stuff surrounding it (because you ran the failing test by itself).
One more option when all else fails is to just add a rescue block and print out the stack try or add a binding pry statement there and use show-stack.
rescue Exception => e
puts ""
puts e.backtrace
puts ""

Resources