Firefox >= 23 will block mixed content when using SSL
Non-SSL contents on SSL pages are blocked by default
Bug 834836 – Turn on pref to block mixed active content
Firefox 18 introduced preferences to block loading contents from non-SSL (http) sites on SSL (https) pages. One of those preferences, security.mixed_content.block_active_content is now enabled by default in order to enhance user security. That means insecure scripts, stylesheets, plug-in contents, inline frames, Web fonts and WebSockets are blocked on secure pages, and a notification is displayed instead. It will not block...
Rails: Overwriting default accessors
All columns of a model's database table are automagically available through accessors on the Active Record object.
When you need to specialize this behavior, you may override the default accessors (using the same name as the attribute) and simply call the original implementation with a modified value. Example:
class Poet < ApplicationRecord
def name=(value)
super(value.strip)
end
end
Note that you can also avoid the original setter and directly read/write from/to the instance's attribute storage. However this is dis...
parallel_tests: Disable parallel run for tagged scenarios
Note: This technique is confusing and slows down your test suite.
Copy the attached code to features/support
. This gets you a new Cucumber tag @no_parallel
which ensures that the tagged scenario does not run in parallel with other scenarios that are tagged with @no_parallel
. Other scenarios not tagged will @no_parallel
can still run in parallel with the tagged test. Please read the previous sentence again.
This can help when multiple test processes that access a single resource that is hard to shar...
ApacheBench may return "Failed requests" for successful requests
When you use ab
to do some performance benchmarking, you might run into output like this:
Complete requests: 200
Failed requests: 5
(Connect: 0, Receive: 0, Length: 5, Exceptions: 0)
Note that in our example these "Failed requests" actually never failed.\
For some requests, the application just returned a response with a different content length than the first response. This is indicated by the "Length: 5
" bit in the example above.
If you see requests that failed with other kinds of errors, they probably fail...
Rails' Insecure Defaults - Code Climate Blog
Rails’ reputation as a relatively secure Web framework is well deserved. Out-of-the-box, there is protection against many common attacks: cross site scripting (XSS), cross site request forgery (CSRF) and SQL injection. Core members are knowledgeable and genuinely concerned with security.
However, there are places where the default behavior could be more secure. This post explores potential security issues in Rails 3 that are fixed in Rails 4, as well as some that are still risky. I hope this post will help you secure your own apps, as w...
Comparing Rails' flash hashes will not respect their internal lists of used entries
Rails flashes (FlashHash
) track a list of used keys, which is not respected when comparing flash hashes.
This does not concern you under most circumstances.
Basics
When ActionController
picks up a flash object, it will call the #sweep
method once; that method checks the list of used flash entries and deletes those. All other entries are flagged as used. This means they will be deleted on the next request, but are still be available for rendering during the current request.
Fun facts: When redirecting, this does not happen. Also,...
Don't assign time values to date attributes
Do not pass times to date attributes. Always convert times to dates when your application uses time zones.
Background
A time-zoned Time
attribute on a Rails record is converted to UTC using to_s(:db)
to be stored, and converted back into the correct time zone when the record is loaded from the database. So when you are not on UTC, time objects will be converted as follows.
>> Time.current
=> Fri, 15 Mar 2013 11:56:03 CET +01:00
>> Time.current.to_s(:db)
=> "2013-03-15 10:56:03" # This is now UTC
Problem
That will...
MySQL: How to create columns like "bigint" or "longtext" in Rails migrations, and what :limit means for column migrations
Rails understands a :limit
options when you create columns in a migration. Its meaning depends on the column type, and sometimes the supplied value.
The documentation states that :limit
sets the column length to the number of characters for string
and text
columns, and to the number of bytes for binary
and integer
columns.
Using it
This is nice since you may want a bigint
column to store really long numbers in it. You can just create it by ...
How to copy your „Google Chrome“ or „Chromium“ profile without creating an online account
Google Chrome saves your profile data in ~/.config/google-chrome
.
To transfer the profile to for example a system you have setup freshly do following steps:
- make a copy of
~/.config/google-chrome
- install google-chrome
- restore your backuped profile to
~/.config/google-chrome
- launch google-chrome
(Replace google-chrome by chromium-browser if you use chromium-browser)
ActiveRecord: count vs size vs length on associations
TL;DR: You should generally use #size
to count associated records.
size
- Counts already loaded elements
- If the association is not loaded, falls back to a
COUNT
query
count
- If a counter cache is set up, returns the cached value
- Issues a
COUNT
query else
Caveats
- If you trigger a
COUNT
query for an association of an an unsaved record, Rails will try to load all children where the foreign keyIS NULL
. This is not what you want. To prevent this behavior, you can useunsaved_record.association.to_a.size
. - `c...
Loading dumps via SSH, unpacking and sourcing them, all with a progress bar
Here is a hacky way to load dumps directly from the source server, without fully copying them over and extracting them first.
It may break horribly for you. This is the dark side of the force.
- Install pipe viewer, if you don't have it already:
sudo apt-get install pv
- Know the location of the dump file on the remote server. We'll use
/mnt/dumps/my_project.dump.bz2
in the example below. - Find out the size of the (bzipped) file in by...
MySQL will not use indexes if you query the wrong data type
When MySQL refuses to use your index, there's a number of things that you may be doing wrong. One of them might be conditions with improper data types.
An example
For example, let's assume you have a users
table with an email
field (varchar
) which is indexed.
MySQL will use the index when your query is well-formed:
mysql> EXPLAIN SELECT * FROM users WHERE email = 'foo@example.com';
+----+-------------+-------+-------+----------------------+----------------------+---------+-------+------+-------+
| id | select_type |...
Capturing signatures on a touch device
If you need to capture signatures on an IPad or similar device, you can use Thomas J Bradley's excellent Signature Pad plugin for jQuery.
To implement, just follow the steps on the Github page.
The form
If you have a model Signature
with name: string, signature: text
, you can use it with regular rails form like this:
- form_for @signature, :html => { :class => 'signature_form' } do |form|
%dl
%dt
= form...
Rails SQL Injection Examples
This page lists many query methods and options in ActiveRecord which do not sanitize raw SQL arguments and are not intended to be called with unsafe user input. Careless use of these methods can open up code to SQL Injection exploits. The examples here do not include SQL injection from known CVEs and are not vulnerabilites themselves, only potential misuses of the methods.
Please use this list as a guide of what not to do.
Edge Rider: Power tools for ActiveRecord scopes
In our continued quest to extract proven code snippets from makandropedia into tested and upgradable gems, we have released Edge Rider.
Edge Rider was created with two intents:
- Provides a number of utility methods to facilitate hardcore work with scopes.
- Provide a stable API for working with scopes across multiple versions of Rails, since Rails has a tradition of breaking details of its scope API every other release.
The gem bundles multiple patches and initializers we've been using for hard...
Traverse an ActiveRecord relation along an association
The Edge Rider gem gives your relations a method #traverse_association
which
returns a new relation by "pivoting" around a named association.
Say we have a Post
model and each Post
belongs to an author:
class Post < ActiveRecord::Base
belongs_to :author
end
To turn a relation of posts into a relation of its authors:
posts = Post.where(:archived => false)
authors = posts.traverse_association(:author)
You can traverse multiple associations in a single call.
E....
The many gotchas of Ruby class variables
TLDR: Ruby class variables (@@foo
) are dangerous in many ways. You should avoid them at all cost. See bottom of this card for alternatives.
Class variables are shared between a class hierarchy
When you declare a class variable, it is shared between this and all descending (inheriting) classes. This is rarely what you want.
Class variables are bound at compile-time
Like unqualified constants, class variables are bound to your current scope *whe...
Allow setting the #id attribute when creating an ActiveRecord
When creating an ActiveRecord with .new
, .create
or create!
, you cannot set the ID attribute (note: When using Machinist's .make
you can).
This is because even when you are not using attr_protected
or attr_accessible
, some attributes are always protected. These attributes are #id
and #type
.
If you want to allow setting #id
on .new
, .create
or create!
you can include the attached module in order to whitelist #id
on a model of your choice like this:
class MyModel <...
ActiveRecord 2.3: Nested attribute changes disappear
There is a bug in ActiveRecord 2.3.x that leads to changes in nested forms getting lost.
class Project < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks
end
If you access project.tasks
after setting tasks through the nested attribute logic, all tasks will be reloaded and all changes will be lost. This usually happens
- in validations
- in callbacks
- after validation errors, when rendering the view again
The attached initializer fixes those issues.
High Performance Networking in Google Chrome
About Chrome's network stack and optimizations to load web pages faster.
Regex: Be careful when trying to match the start and/or end of a text
Ruby has two different ways to match the start and the end of a text:
-
^
(Start of line) and$
(End of line) -
\A
(Start of string) and\z
(End of string)
Most often you want to use \A and \z.
Here is a short example in which we want to validate the content type of a file attachment. Normally we would not expect content_type_1
to be a valid content type with the used regular expression image\/(jpeg|png)
. But as ^
and $
will match lines, it matches both content_type_1
and content_type_2
. Using \A
and \z
will wo...
Pitfall: ResourceController overwrites where ActiveRecord enqueues
Defining one callback several times in the same class behaves different in ActiveRecord and ResourceController.
While in ActiveRecord the callbacks are enqueued, they overwrite each other in ResourceController.
ActiveRecord - a common practice
class Post < ActiveRecord::Base
does 'post/behavior'
before_validation :do_something
end
module Post::BehaviorTrait
as_trait do
before_validation :do_something_else
end
end
do_something_else
and do_something
are executed before validation in exactly this order
ResourceC...
Consul: Querying a power that might be nil
Consul 0.6.1+ gives your Power
class a number of static methods that behave neutrally in case Power.current
is nil
. This allows you to create authorization-aware models that still work when there is no user at the end of a web browser, e.g. on the console, during tests or during batch processes.
You will often want to access Power.current
from another model, to e.g. iterate through the list of accessible users:
class UserReport
def data
Power.current.users.c...