Unsafe string methods in Rails
When you encouter an unsafe string that you actually made html_safe before, perhaps you called one of the following methods on it:
"capitalize", "chomp", "chop", "delete", "downcase", "gsub", "lstrip", "next", "reverse", "rstrip", "slice", "squeeze", "strip", "sub", "succ", "swapcase", "tr", "tr_s", "upcase"
All these methods are possibly unsafe, so they will return an unsafe String even if called on a SafeBuffer. If used for in-place replacements (e.g. sub! instead of sub), a TypeError is raised.
This is to prevent tric...
Rails for Zombies
Learning Rails for the first time should be fun, and Rails for Zombies allows you to get your feet wet without having to worry about configuration. You'll watch five videos, each followed by exercises where you'll be programming Rails in your browser.
Use ActiveSupport autoloading outside of Rails
The following code activates autoloading using ActiveSupport 3.x:
require 'active_support'
require 'active_support/dependencies'
relative_load_paths = %w[app/controllers app/models]
ActiveSupport::Dependencies.autoload_paths += relative_load_paths
Fixing "undefined local variable or method `version_requirements' for #<Rails::GemDependency:0x...> (NameError)"
Phillip Koebbe from Ruby on Rails suggested inserting following code between the "bootstrap" and "initialize" sections of enviroment.rb. This hack fixes the problem.
if Gem::VERSION >= "1.3.6"
module Rails
class GemDependency
def requirement
r = super
(r == Gem::Requirement.default) ? nil : r
end
end
end
end
List of :status symbols for rendering in Rails
When your Rails controller calls render, you can pass a :status option for the HTTP status code:
render 'results', status: 400
All important status codes also have a symbol alias, which makes your code easier to read:
render 'results', status: :bad_request
Attached is a list of available symbol values for :status.
Resolve Aspell errors with your Rails application
If you get an error message like that you are missing the Aspell files a specific language:
No word lists can be found for the language "de"
Solve it by installing the proper package, e.g. on Ubuntu:
sudo apt-get install aspell-de
Create an application with an older Rails version
sudo gem install rails --version="=1.2.3"
rails _1.2.3_ new-project-folder
Introducing GoodJob 1.0, a new Postgres-based, multithreaded, ActiveJob backend for Ruby on Rails
GoodJob is a new background worker gem. It's compatible with ActiveJob.
We're huge fans of Sidekiq for its stability and features. One advantage of GoodJob over Sidekiq is that GoodJob doesn't require Redis. So in cases where you don't have Redis or don't want to pay for a Redis HA quorum node, this might be an alternative worth checking out.
Rails: Running specific migrations
When running migrations with rake db:migrate, there's the STEP and VERSION parameters that you can pass to nearly all commands.
# Migrate
rake db:migrate
rake db:migrate STEP=2
rake db:migrate VERSION=20080906120000
# Redo
rake db:migrate:redo
rake db:migrate:redo STEP=2
rake db:migrate:redo VERSION=20080906120000
# Rollback (starting from latest migration)
rake db:rollback
rake db:rollback STEP=2
# Run the `down` migration path of a certain migration file
rake db:migrate:down VERSION=20080906120000
When Rails does not recognize Rake tasks in lib/tasks
When you put a Rake task into lib/tasks, but running it fails with...
Don't know how to build task name:of:task
... does your Rake task's filename end in .rb? It needs to end in .rake instead.
Silencing Deprecation Warnings in Rspec
If you’re testing the behavior of deprecated code in your Ruby project, the warning messages littered throughout your spec output is incredibly noisy.
You could silence all warnings with ::ActiveSupport::Deprecation.silenced = true, but you might miss out on an important warning in one of your dependencies. It’s tempting to remove the tests altogether (the code will be burned soon too, right?), but I figured out something a little nicer a little while back in Formtastic’s test suite.
marco-polo improves your Rails console prompt
MarcoPolo shows your app name and environment in your console prompt so you don't accidentally break production
Officially supporting IRB (standard rails console) and pry (via pry-rails gem).
Example:
$ rails console
Loading development environment (Rails 4.2.1)
agencyapp(dev)>
How to generate a Rails-compatible query string
From Rails 3.0.9, there is a method Hash#to_query that will turn a Hash into a query string:
>> {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B%5D=c&b%5B%5D=d&b%5B%5D=e"
>> CGI.unescape _
=> "a=a&b[]=c&b[]=d&b[]=e"
If you're on the browser side, you can serialize nestd objects to query strings using jQuery's $.param.
Freeze a specific Rails version
sudo apt-get install unzip
rake rails:freeze:edge RELEASE=2.2.2
How to fix zero-byte downloads with Rails 3 and Apache / Passenger
You probably need to activate X-Sendfile.
The Complete Guide to Rails Caching
Very detailed guide to caching Ruby on Rails.
Goes well with the official Rails guide on caching.
4 Lessons Learned Doing Angular on Rails
We’ve been working on one of our first Angular projects with a Rails backend. It’s been a great experience. I wanted to share a few things we learned that we hope are helpful to others building Angular on Rails apps.
Rails 4 Countdown to 2013 | The Remarkable Labs Blog
With the impending release of Ruby on Rails 4, it looks like a lot of developers will be updating their web applications in the coming new year.
To help with this transition, over the next 31 days, we are going to be releasing a series of blog posts going over everything you will need to know about Rails 4 for an effortless upgrade.
How to express ordinality with numbers in Rails
If you have an integer and want to use it to represent an element's position (like "1st" for 1, or "2nd" for 2), you can use ActiveSupport's ordinalize:
1.ordinalize # => "1st"
2.ordinalize # => "2nd"
1002.ordinalize # => "1002nd"
1003.ordinalize # => "1003rd"
-11.ordinalize # => "-11th"
-1001.ordinalize # => "-1001st"
When Rails no longer renders changes in view templates or Sass stylesheets
Do you have page caching enabled for the development environment and there are cached pages lying around in public/?
Error during Rails 5 upgrade: Environment data not found in the schema
This error is raised because your old database does not have a configured environment yet, which Rails 5 enforces.
If this error occurs while migrating your parallel test databases, make sure to update the parallel_tests gem first: current versions fix this. If you're still using Cucumber < v3, the latest version of parallel_tests will be 2.18.0.
Migrations are versioned in Rails 5 | BigBinary Blog
Rails 5 migration classes look like this now:
class CreateUsers < ActiveRecord::Migration[5.0]
Mind the [5.0] at the end.
They do this to evolve the ActiveRecord::Migration API without breaking your historical migrations in db/migrate.
Using PostgreSQL and jsonb with Ruby on Rails
Postgres 9.4 introduces a new column type: jsonb. json and jsonb columns store data differently, so just compare the two when you want to store JSON data and choose the one that matches your use case best.
Rails 4.2 includes support for jsonb columns, too. The article outlines different ways on how to interact with the serialized object.
Rails 4 drops support for the :assets group in Gemfile
Previously the assets group existed to avoid unintended compilation-on-demand in production. As Rails 4 doesn't behave like that anymore, it made sense to remove the asset group.