Render a view from a model in Rails
In Rails 5 you can say:
ApplicationController.render(
:template => 'users/index',
:layout => 'my_layout',
:assigns => { users: @users }
)
If a Request Environment is needed you can set attributes default attributes or initialize a new renderer in an explicit way (e.g. if you want to use users_url
in the template):
ApplicationController.renderer.defaults # =>
{
http_host: 'example.org',
https: false,
...
}
...
exception_notification 4.0.0+ makes it easier to ignore errors, crawlers
The new exception_notification has awesome options like :ignore_crawlers => true
and :ignore_if => lambda { ... }
. These options should be helpful in ensuring every notifications means something actionable (instead of a long log of failures that just scrolls by).
Note that you should not ignore crawlers by default. Ideally, cool URLs never change and always respond with a helpful redirect or similar.
Ignore Errors like this:
# config/initializers/exception_notification.rb
Ex...
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...
Cryptic Ruby Global Variables and Their Meanings
The linked page lists and explains global Ruby "dollar" variables, such as:
-
$:
(load path) -
$*
(ARGV
) -
$?
(Last exit status) -
$$
(PID) -
$~
(MatchData
from last successful match) - ...and many more you'll need when reading weird code.
Regex
-
$~
(lastMatchData
) -
$1 $2 $3 $4
(match groups from the last pattern match) -
$&
(last matched string) -
$+
(last match group) - `$`` (the string before the last match)
-
$'
(the string after the last match
See [this extensive list of variables](http://www.tu...
Sprites with Compass
Using CSS sprites for background images is a technique for optimizing page load time by combining smaller images into a larger image sprite.
There are ongoing arguments on how useful this still is, as modern browsers become more comfortable to load images in parallel. However, many major websites still use them, for example amazon, [facebook](...
How I Explained REST to my Wife
A great and enjoyable introduction into the concept of the web and about what HTTP was designed for. The original post has been removed for some stupid gender discussion.
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 ...
Rails: Send links in emails with the right protocol
ActionMailer per default uses http
as protocol, which enables SSL-stripping. When a logged-in user follows an http
link to your application, it sends the cookies along with it. Although the application redirects the user to https
and from that point has a secure connection to the user, an attacker may overhear that first unsafe request and hijack your session.
Teach ActionMailer to use the right protocol
If your application is behind SSL, turn on using https
application-wide. In your environment file (either global or per environ...
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...
Subscribe to Rails security mailing list without Google account
The Ruby on Rails security list archive can be found here: http://groups.google.com/group/rubyonrails-security
You can subscribe to this mailing list without a Google account by pasting this URL into your browser (after replacing the email address obviously).
http://groups.google.com/group/rubyonrails-security/boxsubscribe?email=your.name@example.com
^^^^^^^^^^^^^^^^^^^^^ <- Change this
Duplicate a git repository with all branches and tags
In order to clone a git repository including all branches and tags you need to use two parameters when cloning the old and pushing to the new repository respectively:
git clone --bare http://example.com/old-repo.git
cd old-repo
git push --mirror http://example.com/new-repo.git
Of course, the URLs to your repository might look different depending on the protocol used, username required, etc.
For a user git
using the git protocol, it could be git@example.com:repository-namespace/repository.git
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 =...
Browsers will not send a referrer when linking from HTTPS to HTTP
- When your site is on HTTPS and you are linking or redirecting to a HTTP site, the browser will not send a referrer.
- This means the target site will see your traffic as "direct traffic", i.e. they cannot distinguish such hits from a user who directly typed in the URL.
Reasons for this behavior
It's probably because of this RFC:
Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP request if the referring page was transferr...
Howto: Create a self-signed certificate
Option 1: Creating a self-signed certificate with the openssl binary
As igalic commented on this gist.
openssl req -new -newkey rsa:2048 -sha256 -days 365 -nodes -x509 -keyout server.key -out server.crt
Explanation
req -new
Create a new request ...
- -newkey
-
... using a new key ...
rsa:2048
... of type RSA, 2048 bits long.
- -sha1
-
Make sure to use SHA1 as this certificate's hashing algorithm,
- -nodes
-
don't encrypt the key and
-x509
...
How to not die with ActionView::MissingTemplate when clients request weird formats
When HTTP clients make an request they can define which response formats they can process. They do it by adding a header to the HTTP request like this:
Accept: application/json
This means the client will only understand JSON responses.
When a Rails action is done, it will try to render a template for a format that the client understand. This means when all you are HTML templates, a request that only accepts application/json
will raise an error:
An ActionView::MissingTemplate occurred in pages#foo:
Missing templa...
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...
Manage your AWS credentials for multiple accounts
Create a directory mkdir ~/.aws
Initialise git repository cd ~/.aws && git init
Create a git branch with a name you want (e.g. development
for the aws development account credentials).
Add AWS credential file .aws_credentials
:
AWSAccessKeyId=ABCDEFG1234
AWSSecretKey=4321GFEDCBA
Also add your EC2 cert and private key file.
You can add other AWS account depending files like .fog
or .guignol.yml
too.
Create symlinks for some config files like .aws_credentials
and .fog
:
ln -s ~/.aws/.aws_credentials ~/.aws_cred...
OpenStack instance not configuring network (DHCP) correctly
We ran into trouble when adding additional compute units to our railscomplete Hosting environment lately.
VM-instances on the new compute units where booting and requesting private IP addresses via DHCP correctly (DHCPDiscover
), but after the answer of the dnsmasq dhcp server (DHCPOffer
) we did not see any further traffic on the host machine. FYI: The instance should request the IP via DHCPRequest
which in turn should be acknowledged by a DHCPAcknowledgment
packet.
We assumed this DHCP UDP traffic did not...
How to access your Rails session ID
This only works when you actually have a session ID (not the case for Rails' CookieStore, for example):
request.session_options[:id]
# => "142b17ab075e71f2a2e2543c6ae34b94"
Note that it's a bad idea to expose your session ID, so be careful what you use this for.
Controller specs do not persist the Rails session across requests of the same spec
In specs, the session never persists but is always a new object for each request. Data put into the session in a previous request is lost. Here is how to circumvent that.
What's going on?
You are making ActionController::TestRequest
s in your specs, and their #initialize
method does this:
self.session = TestSession.new
This means that each time you say something like "get :index
", the session in your controller will just be a new one, and you won't see ...
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...