Error "undefined method last_comment"
This error message may occur when rspec gets loaded by rake, e.g. when you migrate the test database.
NoMethodError: undefined method 'last_comment' for #<Rake::Application:0x0055a617d37ad0>
Rake 11 removes a method that rspec-core < 3.4.4 depends on. To fix, lock Rake to < 11 in your Gemfile:
gem 'rake', '< 11', # Removes a method that rspec-core < 3.4 depends on
How to install guard-livereload 2.5.2 on Ruby < 2.2.5
There are some inconvenient Gem dependencies. Resolve them by adding/modifying these lines in your Gemfile:
gem 'guard-livereload', '>= 2.5.2', require: false # Fixes a security issue
gem 'listen', '< 3.1' # 3.1 requires Ruby 2.2.5
It is not possible to install guard-livereload 2.5.2 on Ruby 1.8.7 because it depends on guard 2.8, which requires Ruby 1.9.
JSONP for Rails
The rack-contrib gem brings a JSONP middleware that just works™. Whenever a JSON request has a callback parameter, it will wrap the application's JSON response appropriately.
The project is a bit dated, but the JSONP middleware is ok.
[jruby] TruffleRuby Status, start of 2017
TruffleRuby is an experimental Ruby implementation that tries to achieve ~10x performance over MRI.
This has been on our radar for a while. They seem to have made significant progress running Rails, reducing start-up time and becoming runtime-independent of the JVM.
Also see [Running Optcarrot, a Ruby NES emulator, at 150 fps with the GUI!](https://eregon.me/blog/2016/11/28/optcarrot.htm...
How to tackle complex refactorings in big projects
Sometimes huge refactorings or refactoring of core concepts of your application are necessary for being able to meet new requirements or to keep your application maintainable on the long run. Here are some thoughts about how to approach such challenges.
Break it down
Try to break your refactoring down in different parts. Try to make tests green for each part of your refactoring as soon as possible and only move to the next big part if your tests are fixed. It's not a good idea to work for weeks or months and wait for all puzzle pieces ...
Enabling ** in your bash
You may know the double asterisk operator from Ruby snippets like Dir['spec/**/*_spec.rb'] where it expands to an arbitrary number of directories.
However, it is disabled by default on most systems. Here is how to enable it.
If you check your globstar shell option, it is probably disabled:
$ shopt globstar
globstar off
In that case, ** behaves just like * and will match exactly 1 directory level.
$ ls spec/**/*_spec.rb
spec/models/user_spec.rb
To enable it, run
shopt -s globstar
The double ast...
Ruby: String representations of regular expressions
Ruby's regular expressions can be represented differently.
When serializing them, you probably want to use inspect instead of to_s.
For the examples below, consider the following Regexp object.
regexp = /^f(o+)!/mi
to_s
Using to_s will use a format that is correct but often hard to read.
>> regexp.to_s
=> "(?mi-x:^f(o+)!)"
inspect
As the Ruby docs say:
...
Fix Rubygems binary error: undefined method `activate_bin_path' for Gem:Module (NoMethodError)
So you're getting an error like this:
undefined method `activate_bin_path' for Gem:Module (NoMethodError)
Here is what happened:
- You installed a recent version of Rubygems
- You installed some gems that install a binary (like
bundle,rakeorrails) with code that only works with modern Rubygems versions - You downgraded Rubygems to an older versions, which doesn't change any binaries
- When calling binaries with the old Rubygems version, it cannot process the line
Gem.activate_pin_path(...)that was written out by th...
Net::SSH::Exception: could not settle on encryption_client algorithm
TL;DR: Update the 'net-ssh' gem by adding to your Gemfile:
gem 'net-ssh', '=2.9.1'
Now run bundle update net-ssh. It has no dependencies so it shouldn't update other gems.
If you're using Ruby 1.8.7 and want to update net-ssh to a version > 2.9.1 you also need to add this to your gemfile:
gem 'backports', :require => false
... and in your deploy.rb add this:
require 'backports/1.9.2/array/select'
Background
You propably have an older version of Capistrano and thereby an older version of `n...
Bundler: Gemfile.lock is corrupt & gems are missing from the DEPENDENCIES section
So you're getting this failure when running bundle install on an older project:
Your Gemfile.lock is corrupt. The following gems are missing from the DEPENDENCIES section: 'archive-tar-minitar' 'hoe' 'rcov'
This happens when you are using a new version of Bundler with a project that was bundled with a very old version of Bundler. For reasons unknown, the Bundler dependency API returns different dependencies for some gems (like ruby-debug or rainpress) than the dependencies found in the downloaded gemspecs. While old versi...
A collection of graph and diagram tools
- Plot graphs in Ruby
- WebGraphviz renders in your browser via JavaScript (to store the rendered graph, extract the SVG using your browser's DOM inspector)
- GraphViz with DOT: Online http://graphs.grevian.org/graph https://graphviz.christine.website/ or offline https://makandracards.com/makandra/1589-auto-generate-state_machine-graphs-as-png-images
- Balsamiq
- Draw.io
- [Excalidraw](https:...
Summarizing heredoc in Ruby and Rails
This card tries to summarize by example the different uses of heredoc.
- In Ruby
<<vs.<<-vs.<<~ - In Rails
strip_heredocvs.squish
strip_heredoc should be used for a text, where you want to preserve newlines. (multi-line -> multi-line)
squish should be used for a text, where you want to squish newlines. (multi-line -> one-line)
Ruby 2.3+
def foo
bar = <<~TEXT
line1
line2
line3
TEXT
puts bar.inspect
end
foo => "line1\nline2\nline3\n"
Read more: [Unindent HEREDOCs in Ruby 2.3](/m...
Linux: Using grep with a regular expression
You can use three different versions of the regular expression syntax in grep:
- basic:
-G - extended:
-E(POSIX) - perl:
-P(PCRE)
Difference between basic and extended:
In basic regular expressions the meta-characters '?', '+', '{', '|', '(', and ')' loose their special meaning; instead use the backslashed versions '?', '+', '{', '|', '(', and ')'.
Difference between extended (POSIX) and perl (PCRE): E.g. \d is not supported in POSIX.
This g...
Debugging cucumber feature with javascript + firefox vnc
TL;DR Debugging problems with javascript errors in cucumber tests is sometimes easier in the browser. Run the test, stop at the problematic point (with Then pause from Spreewald 1.7+) and open VNC for Firefox.
Features:
- It does not freeze your server like when you're using a debugger. (Compared to the
Then consolestep) - It enables interacting with the server. (Compared to taking screenshots in Capybara)
- It is a faster alternat...
Howto: Free disk space when /boot is full
Easy mode
This method will remove automatically installed packages that no other packages depend on any more. This, of course, includes obsolete kernel versions, with the explicit exception of the currently running kernel, the kernel version that was installed on the system before that and, of course, the latest updated version of the kernel. However, it will also remove any and all other packages that have been marked as installed automatically but have no other packages depending on them. This could lead to unexpected removal of packag...
Aruba: Stubbing binaries
When testing your command line application with Aruba, you might need to stub out other binaries you don't want to be invoked by your test.
Aruba Doubles is a library that was built for this purpose. It is not actively maintained, but works with the little fix below.
Installation
Install the gem as instructed by its README, then put this Before block somewhere into features/support:
Before do
Arub...
Hide a Rake task from the `rake -T` list
A Rake task appears in rake -T if it has a description:
desc 'Compile assets'
task :compile do
...
end
To not list it, simply omit the description:
task :compile do
...
end
You can also hide a Rake task that has been defined by someone else (like a gem) by removing the description:
Rake::Task['compile'].clear_comments
Or you can whitelist which tasks should be listed:
visible_tasks = %w(compile build package)
Rake::Task.tasks.each do |task|
visible_tasks.include?(task.name) or task.clear_comments
en...
Ruby: Writing specs for (partially) memoized code
When you're writing specs for ActiveRecord models that use memoization, a simple #reload will not do:
it 'updates on changes' do
subject.seat_counts = [5]
subject.seat_total.should == 5
# seat_total is either memoized itself, or using some
# private memoized method
subject.seat_counts = [5, 1]
subject.seat_total.reload.should == 6 # => Still 5
end
You might be tempted to manually unmemoize any memoized internal method to get #seat_total to update, but that has two disadvant...
Subclassing module
Yesterday I stumbled across a talk in which the guy mentioned module sub-classing. I was curious what you can do with it and found his blog post with a cool example. It allows you to inject some state into the module you are including elsewhere. Check it out!
class AttributeAccessor < Module
def initialize(name)
@name = name
end
def included(model)
super
define_accessors
end
private
def define_accessors
ivar = "@#{@name}"
define_writer(ivar)
define_reader(ivar)
end
def define_writer(ivar)
...
How to monitor Sidekiq: A working example
In order to have monitoring for Sidekiq (like queue sizes, last run of Sidekiq) your application should have a monitoring route which returns a json looking like this:
{
"sidekiq": {
"totals": {
"failed": 343938,
"processed": 117649167
},
"recent_history": {
"failed": {
"2016-11-06": 1,
"2016-11-07": 46,
"2016-11-08": 0,
"2016-11-09": 0,
"2016-11-10": 0
},
"processed": {
"2016-11-06": 230653,
"2016-11-07": 230701,
"2016-11-08"...
mceachen/closure_tree: Easily and efficiently make your ActiveRecord models support hierarchies
Closure_tree lets your ActiveRecord models act as nodes in a tree data structure.
This promises a few improvements over the battle-tested ancestry gem, such as:
- Better performance
- Pre-ordered trees (painful to do with ancestry)
- Holds a mutex during tree manipulations (an issue with ancestry, where concurrent updates can cause deadlocks and corrupt data).
It has some more moving parts than ancestry though (see below).
Implementation
--------------...
Detecting if a Ruby gem is loaded
Detect if a gem has been activated
A gem is activated if it is either in the current bundle (Gemfile.lock), or if you have manually activated it using Kernel#gem (old-school).
To detect if e.g. activerecord has been activated:
if Gem.loaded_specs.has_key?('activerecord')
# ActiveRecord was activated
end
Detect if a particular gem version has been activated
To detect if e.g. activerecord ma...
makandra/gemika: Helpers for testing Ruby gems
We have released a new library Gemika to help test a gem against multiple versions of Ruby, gem dependencies and database types.
Here's what Gemika can give your test's development setup (all features are opt-in):
- Test one codebase against multiple sets of gem dependency sets (e.g. Rails 4.2, Rails 5.0).
- Test one codebase against multiple Ruby versions (e.g. Ruby 2.1.8, Ruby 2.3.1).
- Test one codebase against multiple database types (currently MySQL or PostgreSQL).
- Compute a matrix of all possib...
Fix "libmysqlclient.so.20: cannot open shared object file: No such file or directory"
This error can be caused by the mysql2 gem under mysterious circumstances. You need to remove it with gem uninstall mysql2 and then reinstall it (or just run bundle).
gem pristine mysql2 will not be enough.