Capybara: Trigger requests with custom request method
Preface: Normally, you would not need this in integrations tests (probably that's why it is so hard to achieve), because it is no actual "integration testing". If you use this step, know what you are doing.
Destroying a record with Capybara is not as easy as calling visit user_path(user, method: :delete)
, because RackTest's visit
can only perform GET requests.
With this step you can destroy a records using either Selenium or RackTest. Ex...
Consul 0.10.0 allows multiple power mappings for nested resources
Consul 0.10.0 now allows multiple power mappings for nested resources.
When using nested resources you probably want two power
checks and method mappings: One for the parent resource, another for the child resource.
Say you have the following routes:
resources :clients do
resources :notes
end
And the following power definitions:
class Power
...
power :clients do
Client.active if si...
Rails: Output helpers for migrations
When you're writing migrations that do more than changing tables (like, modify many records) you may want some output. In Rails > 3.1 you have two methods at hand: announce
and say_with_time
.
In the migration:
class AddUserToken < ActiveRecord::Migration
class User < ActiveRecod::Base; end
def up
add_column :users, :token, :string
announce "now generating tokens"
User.find_in_batches do |users|
say_with_time "For users ##{users.first.id} to ##{users.last.id}" do
users.each do |user|
...
Testing shared traits or modules without repeating yourself
When two classes implement the same behavior (methods, callbacks, etc.), you should extract that behavior into a trait or module. This card describes how to test that extracted behavior without repeating yourself.
Note that the examples below use Modularity traits to extract shared behavior. This is simply because we like to do it that way at makandra. The same techniques apply for modules and overriding self.included
.
Example
---...
RSpec: Where to put shared example groups
Shared example groups are a useful RSpec feature. Unfortunately the default directory structure generated by rspec-rails
has no obvious place to put them.
I recommend storing them like this:
spec/models/shared_examples/foo.rb
spec/models/shared_examples/bar.rb
spec/models/shared_examples/baz.rb
spec/controllers/shared_examples/foo.rb
spec/controllers/shared_examples/bar.rb
spec/controllers/shared_examples/baz.rb
To ma...
angular/angularjs-batarang
Extends the Chrome WebInspector so you can debug AngularJS applications and hunt down performance issues.
It's really, really good.
Git: How to remove ignored files from your repository's directory
When you have files in your .gitignore
they won't be considered for changes, but still you might want to get rid of them, e.g. because they clutter your file system.
While a regular git clean
will ignore them as well, passing the -x
switch changes that:
git clean -x
If you want to see what would happen first, make sure to pass the -n
switch for a dry run:
git clean -xn
Clean even harder by passing the -f
(force cleaning under certain circumstances; I think this is also required by default) or -d
(removes director...
MySQL: Careful when using database locks in transactions
We tend to use database transactions as a magic bullet to get rid of all our concurrency problems. When things get really bad, we might even throw in some locking mechanism, but then are usually done with it.
Unfortunately, transactions semantics in databases are actually very complicated, and chances are, your making some incorrect assumptions.
The MySQL innodb engine actually has [four different modes](ht...
Consul 0.9 lets you optimize records checks
Consul 0.9 comes with many new features to optimize powers that only check access to a given record. e.g. Power.current.post?(Post.last)
. See below for details.
Powers that only check a given object
Sometimes it is not convenient to define powers as a collection. Sometimes you only want to store a method that
checks whether a given object is accessible.
To do so, simply define a power that ends in a question mark:
class Power
...
power :upd...
How to tell ActiveRecord how to preload associations (either JOINs or separate queries)
Remember why preloading associations "randomly" uses joined tables or multiple queries?
If you don't like the cleverness of this behavior, you can explicitely tell ActiveRecord how to preload associations with either JOINs
or separate queries.
This card gives an overview of the different options to preload associations, but
__Whic...
Common mistakes when storing file uploads with Rails
1. Saving files to a directory that is not shared between deploys or servers
If you save your uploads to a made up directory like "RAILS_ROOT/uploads"
, this directory goes away after every deploy (since every release gets a new). Also this directory is not shared between multiple application servers, so your uploads are randomly saved to one local filesystem or another. Fixing this afterwards is a lot of fun.
Only two folders are, by default, shared between our application servers and deployments: "RAILS_ROOT/storage"
and `"RAILS...
Upgrading Rails 2 from 2.3.8 through 2.3.18 to Rails LTS
This card shows how to upgrade a Rails 2 application from Rails 2.3.8 through every single patch level up to 2.3.18, and then, hopefully, Rails LTS.
2.3.8 to 2.3.9
This release has many minor changes and fixes to prepare your application for Rails 3.
Step-by-step upgrade instructions:
- Upgrade
rails
gem - Change your
environment.rb
so it saysRAILS_GEM_VERSION = '2.3.9'
- Change your ...
ActiveRecord.select
Active Record's select method allows you to make use of the power of MySQL select statements. On the one hand it allows you to select specific fields.
Post.select("content")
results in the following query:
"SELECT content FROM `posts`"
This means that your models will be initialized with only the content attribute and you will not be able to access any other attribute. In fact trying so would raise an ActiveRecord::MissingAttributeError error.
Post.select("content").first.title # => ActiveRecord::MissingAttributeErr...
Before you make a merge request: Checklist for common mistakes
Merge requests are often rejected for similar reasons.
To avoid this, before you send a merge request, please confirm that your code ...
- has been reviewed by yourself beforehand
- fulfills every requirement defined as an acceptance criterion
- does not have any log or debugging statements like
console.log(...)
,byebug
etc. - has green tests
- has tests...
Virtus: Coercing boolean attributes
TLDR
Do it like this:
attribute :active, Virtus::Attribute::Boolean
Long story
In Virtus you define attribute with their type like this:
attribute :name, String
attribute :birthday, Date
When defining a boolean attributes, you will probably write it like this:
attribute :active, Boolean
The problem is, there is not actually a Boolean
class in Ruby (there's only TrueClass
and FalseClass
), so use Virtus::Attribute::Boolean
instead.
The reason whil...
How to find out which type of Spec you are
When you need to find out in which kind of spec you are during run-time, it's definitely possible. It's a lot easier in RSpec 2+.
For example, consider this global before
block where you'd want to run some code for specific specs only:
config.before do
# stuff
that_fancy_method
# more stuff
end
RSpec 2+
If you want to run such a block for a specific type of specs, you can use filters:
config.before do
# stuff
# more stuff
end
config.before :type =...
Mac OS: Remove app from Launchpad
Issue this command:
sqlite3 ~/Library/Application\ Support/Dock/*.db "DELETE from apps WHERE title='APP_NAME';" && killall Dock
This tells sqlite3
to remove the app called APP_NAME
from the Launchpad database and then kill the process called Dock
, thereby restarting it.
Fixing authentication in legacy applications
Authentication is hard: there are many edge cases, and most users (including yourself) usually only go the "happy path" once and never see the edge cases. If you have rolled your own authentication, or been using older authentication solutions, or resorted to HTTP Basic Authentication, this card will tell you what to do to make your application safe.
Any application that stores sensitive data in the browser
That is: cookies, e.g. by offering a login.
- Ask the admins to [turn on SSL](https://makandracards.com/makandra/1416-integrate-s...
Good real world example for form models / presenters in Rails
We have often felt the pain where our models need to serve too many masters. E.g. we are adding a lot of logic and callbacks for a particular form screen, but then the model becomes a pain in tests, where all those callbacks just get in the way. Or we have different forms for the same model but they need to behave very differently (e.g. admin user form vs. public sign up form).
There are many approaches that promise help. They have many names: DCI, presenters, exhibits, form models, view models, etc.
Unfortunately most of these approaches ...
Pitfall: ActiveRecord callbacks: Method call with multiple conditions
In the following example the method update_offices_people_count
won't be called when office_id
changes, because it gets overwritten by the second line:
after_save :update_offices_people_count, :if => :office_id_changed? # is overwritten …
after_save :update_offices_people_count, :if => :trashed_changed? # … by this line
Instead write:
after_save :update_offices_people_count, :if => :office_people_count_needs_update?
private
def office_people_count_needs_update?
office_id_changed? || trashed_changed?
end
Or...
Detect city, country from IP address
- You can detect city and country from an IP address by using the GeoLite database. This is a flat file you can copy into your project (~ 20 MB).
- You can access the database using the geoip gem.
- You need to attribute MaxMind if you are using the data.
- Accuracy sort of sucks. For most countries 1/3 of addresses cannot be resolved within 40 kilometers, probably because the Inter...
How to fix: "unexpected token" error for JSON.parse
When using the json gem, you might run into this error when using JSON.parse
:
>> json = 'foo'.to_json
>> JSON.parse(json)
JSON::ParserError: 757: unexpected token at '"foo"'
from /.../gems/json-1.7.7/lib/json/common.rb:155:in `parse'
from /.../gems/json-1.7.7/lib/json/common.rb:155:in `parse'
from (irb):1
Why?
The error above happens because the JSON you supplied is invalid.
While to_json
does work correctly, the result itself is not JSON that can be parsed back, as that s...
How to write complex migrations in Rails
Rails gives you migrations to change your database schema with simple commands like add_column
or update
.
Unfortunately these commands are simply not expressive enough to handle complex cases.
This card outlines three different techniques you can use to describe nontrivial migrations in Rails / ActiveRecord.
Note that the techniques below should serve you well for tables with many thousand rows. Once your database tables grows to millions of rows, migration performance becomes an iss...
ActiveRecord: Passing an empty array into NOT IN will return no records
Caution when using .where
to exclude records from a scope like this:
# Fragile - avoid
User.where("id NOT IN (?)", excluded_ids)
When the exclusion list is empty, you would expect this to return all records. However, this is not what happens:
# Broken example
User.where("id NOT IN (?)", []).to_sql
=> SELECT `users`.* FROM `users` WHERE (id NOT IN (NULL))
Passing an empty exclusion list returns no records at all! See below for better implementations.
Rails 4+
Use the .not
method to let Rails do the logic
`...