Posts

Fix command: webpack not found on heroku

Mittwoch, 22. Januar 2020, 22:43 Uhr | roberto@vasquez-angel.de |

If you get following message when deploying to heroku (i.e. after upgraping rails):

command webpacker not found

You may need to run following command locally and commit the changes:

rails webpacker:install

Fixing 'find_spec_for_exe': can't find gem bundler

Montag, 11. November 2019, 22:21 Uhr | roberto@vasquez-angel.de |

When you run into following error:

'find_spec_for_exe': can't find gem bundler (>= 0.a) with executable bundle (Gem::GemNotFoundException)

It might be that your gem version is too old and does not fit bundler ~> 2.

Try updating gem:

gem update --system '2.7.9'

Useful commands when developing gems

Montag, 08. Juli 2019, 09:51 Uhr | roberto@vasquez-angel.de |

Yank specific gem version from rubygems in all subfolders:

for d in ./cmor_*/ ; do (cd "$d" && gem yank ${PWD##*/} -v 0.0.16.pre); done

Find all tmp folders in actual directory and delete their content (but keep dotfiles)

Freitag, 03. Mai 2019, 09:22 Uhr | roberto@vasquez-angel.de |
find ./ -type d -name "tmp" -execdir rm -rf tmp/* \;

Linux: Run command in all subdirectories

Donnerstag, 28. März 2019, 22:38 Uhr | roberto@vasquez-angel.de |
for d in ./*/ ; do (cd "$d" && ls -al); done

Clear all docker logs

Dienstag, 26. März 2019, 10:20 Uhr | roberto@vasquez-angel.de |
sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"

Linux: Recursively find all files with a certain name and delete them

Dienstag, 19. März 2019, 15:16 Uhr | roberto@vasquez-angel.de |

This will recursively delte all files named “Gemfile.lock” in the current folder:

find . -name "Gemfile.lock" -type f -delete

Find files recursively and rename/replace with regex

Freitag, 15. März 2019, 10:26 Uhr | roberto@vasquez-angel.de |

This will recursively find all files and directories in the actual directory and replace occurences of “foo” with “bar” in their filename:

find . -iname "*" -exec rename "s/foo/bar/g" {} \;

Find folders with most used inodes

Montag, 11. März 2019, 10:54 Uhr | roberto@vasquez-angel.de |
sudo find . -xdev -type f | cut -d "/" -f 2 | sort | uniq -c | sort -n

Show and delete (cache) files older than a year on linux

Montag, 11. März 2019, 10:52 Uhr | roberto@vasquez-angel.de |

Show the files:

find ~/.cache/ -depth -type f -atime +365 

Delete them:

find ~/.cache/ -type f -atime +365 -delete

Execute RSpec examples with a specific locale

Mittwoch, 12. Dezember 2018, 20:50 Uhr | roberto@vasquez-angel.de |

Add a helper to support :locale as metadata:

# spec/support/i18n.rb
RSpec.configure do |config|
  config.around do |example|
    if example.metadata[:locale]
      @_original_locale = I18n.locale
      I18n.locale = example.metadata[:locale]
      example.run
      I18n.locale = @_original_locale
    else
      example.run
    end
  end
end

Use it in your specs:

RSpec.describe '/en/contact', type: :feature, locale: :en do
  # I18n.locale == :en
end

Get a list of all ActiveRecord::Base descendants that have a count > 0

Donnerstag, 19. Juli 2018, 13:43 Uhr | roberto@vasquez-angel.de |

This is useful for testing, when you want to know which models have changed their counts:

ActiveRecord::Base.descendants.each_with_object({}) { |o,m| m[o.name] = o.count }.sort { |o, c| o[1] <=> c[1] }.reject { |c| c[1] < 1 }

If you want to omit certain classes, you may reject them like this:

ActiveRecord::Base.descendants.reject { |e| e.to_s =~/(ApplicationRecord|ActiveStorage).*/ }.each_with_object({}) { |o,m| m[o.name] = o.count }.sort { |o, c| o[1] <=> c[1] }.reject { |c| c[1] < 1 }

Upgrading Rails: Transform plain css image urls to the asset pipeline

Dienstag, 17. Juli 2018, 19:38 Uhr | roberto@vasquez-angel.de |

This is a find/replace for Sublime to replace vanilla css image url statements to asset pipeline erb tags:

Find: url.*images\/(.*)\".*
Replace: url("<%= asset_path '$1' %>");

Don’t forget to rename the css file to .css.erb.

Upgrading rails apps to 5.x

Montag, 09. Juli 2018, 09:23 Uhr | roberto@vasquez-angel.de |

Changed behaviour for dirty attributes:

# rails < 5
after_update do
  if self.active_changed?
    # ...
  end
end

# rails 5
after_update do
  if saved_change_to_active?
    # ...
  end
end

Changed the way to clear has_many associations:

# rails < 5
self.comments = []

# rails 5
self.comments.clear

Changed the way to make a has_many association unique:

This one is tricky as the exception happens inside ActiveRecord:

[1] pry(#<Catalog::OldProduct>)> comments.clear
NoMethodError: undefined method `extensions' for []:Array
Did you mean?  extend
from /xxx@example_app/gems/activerecord-5.2.0/lib/active_record/associations/association.rb:134:in `extensions'

Solution:

# rails < 5
has_many  :comments, -> { uniq }

# rails 5
has_many  :comments, -> { distinct }

But when trying to clear the association you are presented another exception:

comments.clear
ActiveRecord::ActiveRecordError: delete_all doesn't support distinct
from /xxx@example_app/gems/activerecord-5.2.0/lib/active_record/relation.rb:384:in `delete_all'

Solution:

# rails < 5
comments.clear

# rails 5
comments.all.each(&:destroy)

The way params are passed in RSpec controller specs has changed in newer RSpec versions:

# old syntax
get :find_by_uuid, :format => :json, :uuid => 'some-uuid-1234'


# new syntax
get :find_by_uuid, format: :json, params: { uuid: 'some-uuid-1234' }

Revert a git merge

Sonntag, 10. Juni 2018, 13:32 Uhr | roberto@vasquez-angel.de |
git revert -m 1 <merge-commit>

Kill a process running on a specific port on linux

Dienstag, 05. Juni 2018, 12:00 Uhr | roberto@vasquez-angel.de |
fuser -k 3005/tcp

Search through the source code of all used gems in a bundle

Montag, 14. Mai 2018, 15:40 Uhr | roberto@vasquez-angel.de |
bundle show --paths | xargs grep -r Digest::Digest

Gravierende CPU-Sicherheitslücke: So gut wie alle aktuellen Endgeräte betroffen

Freitag, 05. Januar 2018, 09:49 Uhr | roberto@vasquez-angel.de |

Vor kurzem sind zwei kritische Sicherheitslücken die quasi alle PCs, Macs, Smartphones, Server, etc. betreffen bekannt geworden (Meltdown und Spectre).

Durch diese Sicherheitslücke ist es potentiellen Angreifern möglich auf den gesamten Speicherinhalt des Geräts zuzugreifen.

Das heisst, dass Passwörter, PINs, TANs, etc. die eingegeben werden, oder sich in entsperrten “Password Safes” befinden, durch Angriffe die entweder gegen das Endgerät oder auch gegen die Infrastruktur von Dienstleistern durchgeführt werden in Gefahr sind.

Bis entsprechende Patches für ihre Endgeräte ausgeliefert worden sind ist es im Moment empfehlenswert nach Möglichkeit nur auf PCs oder Macs mit Firefox ab v57.0.4 oder dem aktuellsten Chrome Browser zu surfen und folgende Einstellung vorzunehmen:

  1. Sicherstellen, dass Chrome aktuell ist.

  2. Folgendes in der Adressezeile eingeben: chrome://flags/#enable-site-per-process

  3. Rechts neben “Strict site isolation” auf den “Aktivieren” Knopf klicken.

  4. Browser neustarten.

Updates für aktuelle Betriebssysteme, andere Browser und vor allem Smartphones, Tablets, etc. sind in Kürze zu erwarten oder werden im Moment verteilt.

Quellen:

https://meltdownattack.com

https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)

https://www.heise.de/security/meldung/Gravierende-Prozessor-Sicherheitsluecke-Nicht-nur-Intel-CPUs-betroffen-erste-Details-und-Updates-3932573.html

https://thehackernews.com/2018/01/meltdown-spectre-vulnerability.html

https://www.golem.de/news/spectre-und-meltdown-cpu-bugs-sind-laut-google-schon-seit-juni-2017-bekannt-1801-131958.html

https://www.golem.de/news/spectre-und-meltdown-all-unsere-moderne-technik-ist-kaputt-1801-131961.html

Update vom 08.01.2018, 17.15:

Heise hat eine Zusammenfassung zu Gegemaßnahmen nach Hersteller erstellt: https://www.heise.de/newsticker/meldung/Meltdown-und-Spectre-Die-Sicherheitshinweise-und-Updates-von-Hardware-und-Software-Herstellern-3936141.html

Running stuff in all subdirectories on linux

Montag, 21. August 2017, 12:54 Uhr | roberto@vasquez-angel.de |
for d in ./*/ ; do (cd "$d" && somecommand); done

Scale with CSS

Freitag, 04. August 2017, 12:34 Uhr | roberto@vasquez-angel.de |
.scale-01 { transform: scale(0.1); }
.scale-02 { transform: scale(0.2); }
.scale-03 { transform: scale(0.3); }
.scale-04 { transform: scale(0.4); }
.scale-05 { transform: scale(0.5); }
.scale-05 { transform: scale(0.5); }
.scale-06 { transform: scale(0.6); }
.scale-07 { transform: scale(0.7); }
.scale-08 { transform: scale(0.8); }
.scale-09 { transform: scale(0.9); }
.scale-11 { transform: scale(1.1); }
.scale-12 { transform: scale(1.2); }

.scale-align-top {
    transform-origin: top;
}

.scale-align-left {
    transform-origin:left;
}

.scale-align-top-left {
    transform-origin: top left;
}

Recursively delete all log files

Donnerstag, 29. Juni 2017, 12:44 Uhr | roberto@vasquez-angel.de |
find . -name "*.log" -type f -delete

Rails: Find model with associated record

Mittwoch, 07. Juni 2017, 10:26 Uhr | roberto@vasquez-angel.de |

Sometimes you need all the records, that have an associated record. I.e. you might want to have all People that have an address.

For this purpose you can add following scope to your model:

class Person < ActiveRecord::Base
  has_many :addresses

  scope :with, ->(type) { joins(type) }
end

Then you can use it like this:

Person.with(:addresses).all

First AWS EBS steps

Mittwoch, 24. Mai 2017, 20:21 Uhr | roberto@vasquez-angel.de |

Clean install pip:

sudo -i
apt-get purge -y python3-pip
wget https://bootstrap.pypa.io/get-pip.py
python3 ./get-pip.py
apt-get install python3-pip

Install AWS EB CLI:

sudo pip install awsebcli

Initialize:

eb init

Note: I got a “You are not authorized to perform this operation.” error after entering the ssh key details. I could not get past it, so i uploaded the ssh key on the aws web ui.

Create an environment:

eb create

Deploy the application:

eb deploy

At that stage I sshed into the application and ran pending migrations:

eb ssh
cd /var/app/current
bundle exec rake db:migrate
exit

Then I got the error message “An unhandled lowlevel error occurred. The application logs may have details.” when trying to access the app.

It turned out. that I had to set the SECRET_KEY_BASE on eb.

rails secret
eb setenv SECRET_KEY_BASE=<output of rails secret>

Detailed information can be found at: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-getting-started.html

Handle base64 encoded attachments with paperclip < 3.5.0

Dienstag, 09. Mai 2017, 11:36 Uhr | roberto@vasquez-angel.de |
module Base64EncodedAssets
  extend ActiveSupport::Concern

  included do
    before_validation :decode_base64_asset
  end

  def decode_base64_asset
    if asset.uploaded_file =~ /^data:([-\w]+\/[-\w\+]+);base64,(.*)/
      content_type = $LAST_MATCH_INFO[1]
      asset_data   = $LAST_MATCH_INFO[2]
      decoded_data = Base64.decode64(asset_data)

      file_extension = Rack::Mime::MIME_TYPES.invert[content_type]

      data = StringIO.new(decoded_data)
      
      data.class_eval do
        attr_accessor :content_type, :original_filename
      end

      data.content_type = content_type
      data.original_filename = File.basename("#{SecureRandom.uuid}#{file_extension}")

      self.asset = data
    end
  end
end

include Base64EncodedAssets if Paperclip::VERSION < '3.5.0'

Install mysql 5.6 on newer ubuntu flavors

Donnerstag, 20. April 2017, 08:00 Uhr | roberto@vasquez-angel.de |
sudo add-apt-repository 'deb http://archive.ubuntu.com/ubuntu trusty universe'
sudo apt-get update
sudo apt install mysql-server-5.6 * see note below if you get an error
sudo apt install mysql-client-5.6