Creating a patch in git and how to apply patches
You can convert git commits into patch files. Those can be used to apply to a different repository [1] or by someone else (e.g. sent when sent to them via e-mail).
Creating a patch in git
- Make your changes and commit them.
- Run
git format-patch COMMIT_REFERENCE
to convert all commits since the referenced commit (not including it) into patch files.
For example, let's say you prepared 2 commits. Run:
git format-patch HEAD~~
This will create 2 files, one for each commit since HEAD~~
, like these:
00...
Using :dependent => :destroy – Issues with 'code arrangement' or 'cached objects'
First keep in mind that :dependent => :destroy
hooks into before_destroy
.
So when you use other before_destroy
callbacks the sequential arrangement of your code may be important.
For example:
class Container < ActiveRecord::Base
before_destroy :a_callback
has_many :items, :dependent => :destroy
end
results in
container.destroy
# => a_callback
# => container.items.destroy_all
but
class Container < ActiveRecord::Base
has_many :items, :dependent => :destroy
before_...
Fix multiple CKEditor instances using jQuery adapter - fixed since 4.2
Using the jQuery adapter breaks the built-in save function of CKEditor.
Phenomenon: The page is submitted correctly, but the original values of the form fields were posted instead of what was typed in the editors.
Work around: Basicly instead of initiating the editor using the above example I ended up using the following:
$( 'textarea.editor').each( function() {
CKEDITOR.replace( $(this).attr('id') );
});
Note: This assumes that each field using the editor has its own unique ID.
Rails logs are not flushed automatically (in Rake tasks)
The Rails logger will store its content in a buffer and write it into the file system every 1000 lines. This will come back to bite you when using Rails.logger.info
to write log output during Rake tasks or on a production console.
You often won't notice this because for the development
and test
environments auto_flushing
is set to write after each line. On production environments the Rails logger writes only every 1000 lines -- and not upon shell or script ter...
How to update a MySQL column with ascending numbers
Given the problem you have a new column postion and that column should be updated for all existing rows with ascending numbers. Furthermore these numbers should be generated by a special order. In order to achieve that you could do the following:
execute "SET @pos := 0;"
update " UPDATE pages SET position = ( SELECT @pos := @pos + 1 ) ORDER BY updated_at DESC;"
Properly adding fields with default values to a model
When adding a new field to your model's database table, don't set any defaults in the database.
It makes people wonder why they get such values when reading attributes.\
Why? Because nobody looks at the database layout since such things are part of your application's logic -- and thus they belong into the corresponding model.
How to
Do it like this:
-
In your migration, after adding the field, update all fields to your desired default:
update "UPDATE users SET locked = #{quoted_false};"
-
In your model, set a defau...
Single step and slow motion for cucumber scenarios using @javascript selenium
Single step and slow motion for Cucumber scenarios can come in handy, especially in @javascript
scenarios.
# features/support/examiners.rb
AfterStep('@slow_motion') do
sleep 2
end
AfterStep('@single_step') do
print "Single Stepping. Hit enter to continue"
STDIN.getc
end
If you're using spreewald, these tags are available as @slow-motion
and @single-step
(with dashes instead of underscores).
Note: You can also [prevent the selenium webbrowser wind...
Open a MySQL shell using credentials from database.yml
In order to open a MySQL shell without the need to enter user and password, you can say the following in any Rails 2 project:
script/dbconsole -p
In Rails 3 you can say:
rails dbconsole -p
If you'd like to enter a database for an environment other than development
you can say:
script/dbconsole -p staging
MySQL: For each group, retrieve a comma-separated list of values in a given column
The technique described in this card has an important caveat: The result of GROUP_CONCAT
is truncated to the maximum length that is given by the group_concat_max_len
system variable, which has a default value of 1024. This will cause horrible, data-destroying bugs in production. For this reason you should probably not use GROUP_CONCAT
ever. At least you must set the value of group_concat_max_len
to an insanely high value on every database server your application runs on.
Lik...
Using heredoc for prettier Ruby code
You can use heredoc to avoid endlessly long lines of code that nobody can read. Heredoc strings preserve linebreaks and can be used like this:
def long_message
puts(<<-EOT)
Here goes a very long message...
Sincerely,
foobear
EOT
end
<<-EOT
will be somewhat of a placeholder: anything you write in the line after you used it will be its value until you write EOT
in a single line.
You can use any string to flag your heredocs. To be more verbose you...
Couldn't create database for ...
When you run rake db:create
and get this error message
Couldn't create database for {"encoding"=>"utf8", "username"=>"root", "adapter"=>"mysql", "database"=>"project_development", "password"=>"topsecret"}, charset: utf8, collation: utf8_unicode_ci (if you set the charset manually, make sure you have a matching collation)
make sure the user you have specified (root/topsecret) in your database.yml
has access to MySQL. You can check this by running mysql -uroot -p
.
Solving "cannot remove Object::ClassMethods"
Most likely you run rake
and your code is causing an exception which is not the one shown in your terminal.
Rails tries to catch this exception and clean up constants but -- while it's still booting up -- fails on this which causes another exception:
rake aborted!
cannot remove Object::ClassMethods
Running rake
with the --trace
parameter will give you no love; the backtrace is useless in most cases.
Try these approaches:
First: Check if there is a helpful error message
- Ha...
MySQL: How to clone a database
Here is a way to create a duplicate of one database, with all its tables and their data, under a new name.
-
Make a dump of your source database:
mysqldump -uroot -p my_project -r my_project.sql
Or, if you only want to dump the database's table structure (schema) without any contents:
mysqldump -uroot -p my_project -r my_project.sql --no-data
-
Open up a MySQL shell:
mysql -uroot -p
-
From the MySQL shell, create a new database and populate it with the dumped data:
CREATE DATABASE my_project_copy;
...
Machinist's #make breaks on has_many associations when defining method `empty?`
Observed on Rails 2.3 and machinist 1.0.6
Like the title says, when you define the method empty?
like in the following example, you may not longer use collection.make
.
class Book
has_many :pages
def empty?
pages.empty?
end
end
Assuming
b1 = Book.find(1)
b2 = Book.find(2)
instead of expected
b1.pages.make #=> #<Page id: 1, book_id: 1>
b2.pages.make #=> #<Page id: 2, book_id: 2>
you'll get
b1.pages.make #=> #<Page id: 1, book_id: 3>
b2.pages.make #=> #<Page id: 2,...
dbconsole in Rails 3 requires the environment as the first argument
There is a bug in Rails 3's dbconsole
script, which makes the following command open a database console for the development
environment:
rails dbconsole -p test
You need to write this instead:
rails dbconsole test -p
Rendering a custom 404 page in Rails 2
Simple: Tell the application controller how to handle exceptions, here a RecordNotFound
error.
Do this with the following line:
# application_controller.rb
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
This will call the method render_404
whenever a RecordNotFound
error occurs (you could pass a lambda
instead of a symbol, too).
Now write this method:
def render_404
render 'errors/404', :status => '404'
end
Finally create a 404 document views/errors/errors.html.haml
.
%h1 Record...
Rails 3.1.0 has been released!
jQuery as new default Javascript library, streaming response support, attr_accessible with roles, prepared statements, easier migrations.
Invoices: How to properly round and calculate totals
While it might seem trivial to implement an invoice that sums up items and shows net, gross and vat totals, it actually involves a lot of rules and caveats. It is very easy to create invoices where numbers don't add up and a few cents are missing. A missing cent is a big deal for an accountant, so it is important for your invoices to list correct numbers.
Note that this is not legal advice. Also note that while this note has a number of code examples in Ruby and MySQL, the concepts apply to all programming languages and data stores.
When ...
Always show all form errors during development
You've been there: A form cannot be submitted, but you don't see a validation error because the field at fault has no corresponding input field on the form. Because this is usually a bug, you insert debug information listing all errors into the form view. And once the bug is fixed, you forget to take out that debug information.
There is a better way. By copying one of the attached initializers into config/initializers
, your forms will always render a small box listing all form errors in the bottom right corner of the screen. This box is n...
Timecop creates records in the past after calling Timecop.freeze
This is a bug in Timecop 0.3.4 or lower. You should upgrade to 0.3.5.
An ActiveRecord is invalid, but has no errors
Did you return false
in a before_validation
callback?
Random list of ActiveSupport goodies
I recently browsed through the ActiveSupport code and found some nice stuff I did not know about:
ActiveSupport::Callbacks
-
ActiveRecord-like callbacks, if you need callbacks in non ActiveRecord objects
ActiveSupport::MessageEncryptor
-
encrypt and decrypt ruby objects
[ActiveSupport::MessageVerifier
](https://github.com/rails/rails/blob/mast...
Ruby GetText will eval scripts containing ActiveRecord classes
When the Ruby parser module of Ruby-GetText comes across a file in one of its search directories (e.g. lib/scripts/
) and finds out that you are defining ActiveRecord classes inside it, it evaluates the whole file. Here is how to avoid that.
What's happening?
Let's say you have the following script which is only run once, manually, via script/runner
:
# lib/scripts/doomsday.rb
class User < ActiveRecord::Base; end
User.destroy_all
In that case we ...
List sizes of MySQL databases
Do you wonder which databases are actually taking up how much space but only have one huge ibdata1
in your /var/lib/mysql
and the directories inside your mysql data directory don't represent the actual database sizes? This is for you!
Run from a mysql root console:
SELECT table_schema AS "Database name", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema;
This will get you a result like the following:
+----------------------+--------------+
| Database name ...