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

Test concurrent Ruby code

To test concurrent code, you will need to run multiple threads. Unfortunately, when you use blocking system calls (e.g. locks on the database), Ruby 1.8 threads won't work because system calls will block the whole interpreter.

Luckily you can use processes instead. fork spins off a new process, IO.pipe sends messages between processes, Process.exit! kills the current process. You will need to take care of ActiveRecord database connections.

Here is a full-fledged example:

describe Lock, '.acquire' do

  before :each do
  ...

Concurrent Tests

Install gem and plugin

sudo gem install parallel
script/plugin install git://github.com/grosser/parallel_tests.git

Adapt config/database.yml

test:
  database: xxx_test<%= ENV['TEST_ENV_NUMBER'] %>

Create test databases

script/dbconsole -p
CREATE DATABASE `xxx_test2`;
...

Generate RSpec files

script/generate rspec

(you'll probably only let it overwrite files in script/)

Prepare test databases...

Convert Haml to ERB

This is about converting Haml to ERB and not the other way round which you probably want!

This process can not be automated 100%, but you can still save time.

First do

script/plugin install http://github.com/cgoddard/haml2erb.git

Then in the console type

hamls = Dir["app/views/**/*.haml"] - ['app/views/layouts/screen.html.haml'];
hamls.each do |haml| 
  puts haml
  erb = haml.sub(/\.haml$/, '.erb')
  File.open(erb, 'w') do |file| 
    file.write Haml2Erb.convert(File.read(haml)) 
  end
end

After th...

How to install the date_performance gem

sudo gem install zip
git clone git://github.com/rtomayko/date-performance.git
cd date-performance
rake package:build
cd dist
sudo gem install --no-ri --no-rdoc date-performance-0.4.7.gem

Clear a Solr index with acts_as_solr

ActsAsSolr::Post.execute(Solr::Request::Delete.new(:query => "#{Location.solr_configuration[:type_field]}:#{ModelClass}"))
ActsAsSolr::Post.execute(Solr::Request::Commit.new)

Fixing "A copy of Klass has been removed from the module tree but is still active"

This can happen during development when classes without automatic reloading are pointing to classes with automatic reloading. E.g. some class in lib is calling Model.static_method.

Workaround A

Stop referencing autoloaded classes from static files. If you can't, see workaround B and C.

Workaround B

Make sure the offending file (the one referencing the autoloaded class) is autoloaded, too. You may do this:

# config/application.rb

  config.paths.add 'offending/file/parent/directory', eager_load: true

Workaroun...