What edge_rider offers you
edge_rider is Power tools for ActiveRecord relations (scopes). Please note that some of the functions edge_rider provides have native implementations in newer rails versions.
Useful in applications
Relation#traverse_association(*names)
Edge Rider gives your relations a method #traverse_association
which returns a new relation by "pivoting" around a named association. You can traverse multiple associations in a single call. E.g. to turn a relation of posts into a relation of all posts o...
MySql lost connection trouble
Directly from the MySql docs:
There are three likely causes for this error message.
Usually it indicates network connectivity trouble and you should check the condition of your network if this error occurs frequently. If the error message includes during query, this is probably the case you are experiencing.
Sometimes the during query form happens when millions of rows are being sent as part of one or more queries. If you know that this is happening, you should try increasing net_read_timeout from its default of 30 seconds to 60 s...
terminator keyboard shortcuts
When connecting to multiple (i.e. > 4) servers to dive into logfiles or do security updates, terminator is what you want.
There are several keyboard shortcuts available:
- Ctrl-Shift-E: Split the view vertically.
- Ctrl-Shift-O: Split the view horizontally.
- Ctrl-Shift-P: Focus be active on the previous view.
- Ctrl-Shift-N: Focus be active on the next view.
- Ctrl-Shift-W: Close the view where the focus is on.
- Ctrl-Shift-Q: Exit terminator.
- Ctrl-Shift-X: Enlarge active window...
assignable_values 0.11.0 can return *intended* assignable values
As you know, assignable_values does not invalidate a record even when an attribute value becomes unassignable. See this example about songs:
class Song < ActiveRecord::Base
belongs_to :artist
belongs_to :record_label
assignable_values_for :artist do
record_label.artists
end
end
We'll create two record labels with one artist each and create a song for one artist. When we change the song's record label, its artist is still valid.
makandra = RecordLabel.create! name: 'makandra records'
dominik...
PSA: Umlauts are not always what they seem to be
When you have a string containing umlauts which don't behave as expected (are not matched with a regexp, can't be found with an SQL query, do not print correctly on LaTeX documents, etc), you may be encountering umlauts which are not actually umlaut characters.
They look, depending on the font, like their "real" umlaut counterpart:
- ä ↔ ä
- ö ↔ ö
- ü ↔ ü
However, they are not the same:
'ä' == 'ä' # false
'ä'.size # 1
'ä'.size # 2
Looking at how those strings are constructed reveals what is going on:
'ä'.unpack('U*...
patbenatar/jquery-nested_attributes
jQuery plugin that makes it easy to dynamically add and remove records when using ActiveRecord's nested attributes.
Discarding cached SQL query results in ActiveRecord
ActiveRecord caches results of SQL queries. If you want to discard the cached results for one model, you can call MyModel.connection.clear_query_cache
.
Retrieving the class an ActiveRecord scope is based on
Edge Rider gives your relations a method #origin_class
that returns the class the relation is based on.
This is useful e.g. to perform unscoped record look-up.
Post.recent.origin_class
# => Post
Note that #origin_class
it roughly equivalent to the blockless form of #unscoped
from Rails 3.2+, but it works consistently across all Rails versions. #unscoped
does not exist for Rails 2 and is broken in Rails 3.0.
What's new in edge Rails: Active Record enums
Declare an enum attribute where the values map to integers in the database, but can be queried by name.
Why Ruby Class Methods Resist Refactoring
In a nutshell:
- Splitting a long method into sub methods is easier in instances since it is in classes. Since you must not save state in a class, you need to pass around context as a long chain of parameters again and again.
- If your public API has a single entry point, you can still have a class-level method that takes care of constructing the instance etc. So it's all win.
Why your previous developer was terrible
When you, as a developer, look at the choices used to build a particular application, you’re blown away at the poor decisions made at every turn. “Why, oh why, is this built with Rails when Node.js would be so much better?” or “how could the previous developer not have forseen that the database would need referential integrity when they chose MongoDB?” But what you may not realize is that you are seeing the application as it exists today. When the previous developer (or team) had to develop it, they had to deal with a LOT of unknowns. They...
BrowserStack has browser plugins for local testing
Local testing allows you to test your private and internal servers using the BrowserStack cloud, which has support for firewalls, proxies and Active Directory.
ActiveRecord: validate_uniqueness_of is case sensitive by default
By default, Rails' validates_uniqueness_of
does not consider "username" and "USERNAME" to be a collision. If you use MySQL this will lead to issues, since string comparisons are case-insensitive in MySQL.
(If you use PostgreSQL, read this instead.)
Say you have a user model
class User < ActiveRecord::Base
validates_uniqueness_of :name
end
with a unique index in the database.
If you try to create the users "user" and "USER", this will not trigger a validation error, but may fail with an SQL error due ...
all_blank_except for accepts_nested_attributes_for
Put the attached file to config/initalizers
to ignore some fields for rejecting nested records (e.g. hidden input fields).
class Post < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments, :reject_if => all_blank_except(:position, :other_nested_attrs)
end
Your Rails sandbox console
Just found out about a great feature in Rails that seems to be around since Rails 2. Start a console with the --sandbox
(or -s
) parameter:
rails console --sandbox
All changes you make to the database will be rolled back on exit.
Warning
Changes beyond the database (deleting files, sending emails, etc) cannot be rolled back!
Don't ever use the float type for database columns
Like in any language, a FLOAT
will eventually corrupt data due to rounding errors.
Please use DECIMAL
, which has well-defined behavior for rounding and range overflows.
Using Arel to Compose SQL Queries
Arel is a library that was introduced in Rails 3 for use in constructing SQL queries. Every time you pass a hash to where, it goes through Arel eventually. Rails exposes this with a public API that we can hook into when we need to build a more complex query.
[Openstack] "Failed to schedule_prep_resize: No valid host was found." when trying to resize an instance
If you get this error while trying to resize an openstack instance:
# nova resize fooinstance 16 --poll
==> /var/log/nova/nova-scheduler.log <==
2014-01-30 17:40:34 WARNING nova.scheduler.manager [req-aaaaaaa-bbbb-cccc-dddd-1ed34b64adef bajd7394hftgs71dba31d642342effa0f bfe2djhg6538sg384jgb82ks070ce0b] Failed to schedule_prep_resize: No valid host was found.
2014-01-30 17:40:34 WARNING nova.scheduler.manager [req-aaaaaaa-bbbb-cccc-dddd-1ed34b64adef bajd7394hftgs71dba31d642342effa0f bfe2djhg6538sg384jgb82ks070ce0b] Setting ...
Bash: Setting the title of your terminal tab
If your terminal has many tabs, you'll want to keep them organized. To change their title from the prompt, run this function:
function tab_title {
if [ -z "$1" ]
then
title=${PWD##*/} # current directory
else
title=$1 # first param
fi
echo -n -e "\033]0;$title\007"
}
Put it into your ~/.bashrc
to have it always available. Adjust to your needs.
Usage
$> tab_title
# title set to the current directory's name
$> tab_title new_title
# title set to "new_title"
Auto-setting the title
=================...
How to load only a subset of a massive MySQL dump
I had a huge MySQL dump that took forever (as in: days) to import, while I actually just wanted to have the full database structure with some data to use on my development machine.
After trying several suggestions on how to speed up slow MySQL dump imports (which did not result in any significant improvement), I chose to import just some rows per table to suffice my needs. Since editing the file was not an option, I used a short Ruby script to manage that.
Here is how:
pv huge.dump | ruby -e 'ARGF.each_line { |l| m = l.match(/^INSERT ...
Don't use "self" as a Javascript variable
You might sometimes use self
to capture the context of this
before it is destroyed by some function.
Unfortunately self
is also an alias for window
, the global top-level object. Save your future self some headaches and use another name like me
instead (Coffeescript chose to use _this
).
The new Modularity 2 syntax
We have released Modularity 2. It has many incompatible changes. See below for a script to migrate your applications automatically.
There is no does method anymore
We now use traits with the vanilla include
method:
class Article < ActiveRecord::Base
include DoesTrashable
end
When your trait has parameters, use square brackets:
class Article < ActiveRecord::Base
include DoesStripFields[:name, :brand]
end
Note how you ...
Careful with '||=' - it's not 'memoize'
When you do something like this in your code:
def var_value
@var ||= some_expensive_calculation
end
Be aware that it will run some_expensive_calculation every time you call var_value if some_expensive_calculation returns nil.
This illustrates the problem:
def some_expensive_calculation
puts "i am off shopping bits!"
@some_expensive_calculations_result
end
When you set @some_expensive_calculations_result to nil, ||= runs some_expensive_calculation every time....
Threads and processes in a Capybara/Selenium session
TLDR: This card explains which threads and processes interact with each other when you run a Selenium test with Capybara. This will help you understand "impossible" behavior of your tests.
When you run a Rack::Test (non-Javascript) test with Capybara, there is a single process in play. It runs both your test script and the server responding to the user interactions scripted by your test.
A Selenium (Javascript) test has a lot more moving parts:
- One process runs your test script. This is the process you...