Sun Java JVM/JRE on Ubuntu Linux

Note that you should disable the Java plug-in in your browsers after installation.

Ubuntu >= 12.04

Java 11

sudo apt install openjdk-11-jre-headless

Java 10

sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update
sudo apt-get install oracle-java10-installer

Java 8

You probably want to get rid of OpenJDK (which is installed by default and leads to bad RubyMine performance):

...

Save ActiveRecord models without callbacks or validations (in Rails 2 and Rails 3)

Rails 2

You can use

record.send(:update_without_callbacks)

or

record.send(:create_without_callbacks)

This can be used as a lightweight alternative to machinist's make or FactoryGirl's create, when you just need objects in the database but don't care about any callbacks or validations. Note that create_without_callbacks does not return the object, so you might want to do

record = Record.new.tap(&:create_without_callbacks)

Rails 3

Rails 3 no longer comes with update_without_callbacks or `crea...

Security issues with hash conditions in Rails 2 and Rails 3

Find conditions for scopes can be given either as an array (:conditions => ['state = ?', 'draft']) or a hash (:conditions => { 'state' => 'draft' }). The later is nicer to read, but has horrible security implications in some versions of Ruby on Rails.

Affected versions

Version Affected? Remedy
2.3.18 yes Use chain_safely workaround
3.0.20 no ...

Copying validation errors from one attribute to another

When using virtual attributes, the attached trait can be useful to automatically copy errors from one attribute to another.

Here is a typical use case where Paperclip creates a virtual attribute :attachment, but there are validations on both :attachment and :attachment_file_name. If the form has a file picker on :attachment, you would like to highlight it with errors from any attribute:

class Note < ActiveRecord::Base
  has_attached_file :attachment
  validates_attachment_presence :a...

Deliver Paperclip attachments to authorized users only

When Paperclip attachments should only be downloadable for selected users, there are three ways to go.
The same applies to files in Carrierwave.

  1. Deliver attachments through Rails

The first way is to store Paperclip attachments not in the default public/system, but in a private path like storage inside the current release. You should prefer this method when dealing with sensitive data.

Make ...

Collect all values for a given column in an ActiveRecord scope

In modern Rails versions you can also use ActiveRecord's pluck method.

>> User.active.pluck(:id)
=> [1, 5, 23, 42]

If you are plucking from the id column in particular you can also say:

>> User.active.ids
=> [1, 5, 23, 42]

For a DISTINCT selection, use distinct on your scope (not the resulting array).

>> Article.distinct.pluck(...

Testing state_machine callbacks without touching the database

You should test the callback methods and its correct invocation in two separate tests. Understand the ActiveRecord note before you move on with this note.

Say this is your Spaceship class with a transition launch and a release_docking_clamps callback:

class Spaceship
  state_machine :state, :initial => :docked do
    event :launch do
      transition :docked => :en_route
    end
    before_transition :on => :launch, :do => :release_doc...

Understand ActiveRecord::ReadOnlyRecord error

When you load a record with find options that have SQL fragments in :select or :joins, ActiveRecord will make that record read-only. This is a protective measure by Rails because such a record might have some additional attributes that don't correspond to actual table columns.

You can override that precaution by appending :readonly => false to affected find options or scope options.

Efficiently add an event listener to many elements

When you need to add a event listener to hundreds of elements, this might slow down the browser.

An alternative is to register an event listener at the root of the DOM tree (document). Then wait for events to bubble up and check whether the triggering element (event.target) matches the selector before you run your callback.

This technique is called event delegation.

Performance considerations

Because you only register a single listener, registering is ...

How Rails and MySQL are handling time zones

When working with times and dates in Rails applications, you need to deal with the following problem:

  • In Rails, Time objects have a time zone. You can get the zone name by doing time_object.zone.
  • This zone is considered when doing time calculations, e.g. 10 AM CEST minus 8 AM UTC is zero.
  • A datetime in MySQL does not have a zone. It just stores the literal string "2010-05-01 12:00:00".
  • That means that Rails must make assumptions about timestamps loaded from and written to MySQL.

Rails has two completely different modes ...

Order for SELECT ... IN (5,100,23) queries

When doing a query like this:
SELECT id FROM users WHERE (users.id IN (899,1084,1095,100,2424,2429,2420))

the order of the returned records is undefined. To force the query to return the records in a given order, you have to add ORDER BY FIELD(id, 899, 1084, ...)

So the query looks like this:
SELECT id FROM users WHERE (users.id IN (899,1084,1095,100,2424,2429,2420)) ORDER BY FIELD(id,899,1084,1095,100,2424,2429,2420);

Change default size of Gnome terminal

Open the configuration file:

gksudo gedit /usr/share/vte/termcap/xterm

Find a line like this:

:co#80:it#8:li#24:\

Change the first and last number to your desired columns and rows:

:co#160:it#8:li#40:\

Save your changes and close all open terminals. New terminals should now open with the new size.

Dumping and importing from/to MySQL in an UTF-8 safe way

In a nutshell: to avoid your shell character set from messing with imports, use -r to export and SOURCE when importing.

Dumping safely

# Do not do this, since it might screw up encoding
mysqldump -uroot -p database > utf8.dump # this is bad

Better do:

mysqldump -uroot -p database -r utf8.dump

Note that when your MySQL server is not set to UTF-8 you need to do mysqldump --default-character-set=latin1 (!) to get a correctly e...

UTF-8ify an existing MySQL database

First do

ALTER DATABASE database_name CHARACTER SET "utf8";
ALTER DATABASE database_name COLLATE "utf8_unicode_ci";

After that, for each table:

ALTER TABLE table_name DEFAULT CHARACTER SET "utf8" COLLATE "utf8_unicode_ci";

This just changes the default character set / collation for each table. To convert them, you need:

ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

MySQL replication how-to

This may be awkward to set up, but will work once you're done.

Fun facts:

  • In case of a connection loss the slave will try to reconnect to the master server and resume replication for the next 24 hours
  • If you want to use your slave as a "real" MySQL server, you basically need to switch off replication (STOP SLAVE; RESET SLAVE; and reset your my.cnf) and restart the MySQL daemon.

Master server configuration

  • Create replication user
    : In the MySQL shell:

      CREATE USER 'replicator'@'%' IDENTI...
    

MySQL Server and UTF-8 Defaults

Unless all MySQL server defaults are set to UTF-8, mysqldump encodes UTF-8 characters incorrectly and only outputs correct UTF-8 when you switch to Latin 1 (!). Also you need to setup charset and collation manually for each new database.

To prevent this, make sure your /etc/mysql/my.cnf looks like this:

[mysqld]
default-character-set = utf8mb4
collation-server = utf8mb4_unicode_ci

[mysql]
default-character-set=utf8mb4

After that do

sudo /etc/init.d/mysql restart