Passenger ignores RailsEnv directive for Rails 3 applications
You might find that your Passenger ignores all RailsSomething directives in the vhost for your new Rails 3 application. The culprit is a file config.ru which makes Passenger consider your application a Rack (non-Rails) application.
To fix this you can either use RackEnv in lieu of RailsEnv (it works fine) or delete the config.ru. Unless you have a good reason to do so, go with RackEnv.
How to silence UTF-8 warnings on Rails 2.3 with Ruby 1.9
Rails 2.3.16+ on Ruby 1.9 causes warnings like this:
.../gems/activesupport-2.3.17/lib/active_support/core_ext/string/output_safety.rb:22: warning: regexp match /.../n against to UTF-8 string
Many thanks to grosser for supplying a monkey-patch for Rails 2.3 (Commit f93e3f0ec3 fixed it for Rails 3). Just put it into config/initializers/ to make those warnings go away.
Since we're using RSpec on mos...
Rails has a built-in slug generator
Today I learned that Ruby on Rails has shipped with a built-in slug generator since Rails 2.2:
> "What Up Dog".parameterize
=> "what-up-dog"
> "foo/bar".parameterize
=> "foo-bar"
> "äöüß".parameterize
=> "aouss"
Also see: Normalize characters in Ruby.
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...
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
How to disable Rails raising errors on pending migrations in development
Rails 4 introduced raising an error on pending migrations. This is most annoying when you are crafting a migration but need to play with your application to figure out how to do it.
To disable this behavior, just set the corresponding config option to false:
# in config/environments/development.rb
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = false # was :page_load
Fix LoadError with Rails 3 applications on Passenger
After switching to Rails 3 you may get a LoadError with the following message when trying to use your application via passenger:
no such file to load -- dispatcher
Your Passenger version is most likely out of date.
Update the gem, then install the apache module again:
sudo gem install passenger
sudo passenger-install-apache2-module
Follow any instructions. Update your /etc/apache2/httpd.conf with the lines given at the end of the installation process to use the version you just installed.
Use non-ASCII characters on IRB and Rails consoles with RVM and Mac OS X
If you are using RVM on a Mac and cannot enter 8+ bit characters on an IRB or Rails console, you are missing the readline package. You will need to re-install your Ruby to fix this:
rvm remove ree
rvm package install readline
rvm install ree --with-readline-dir=$rvm_path/usr
rvm default ree
Substitute ree with the name if your Ruby distribution.
This note was contributed by Matthias Marschall from the Agile Web Development & Operations blog.
How to enable Rails' file_fixture helper in FactoryBot
In FactoryBot factories, Rails' file_fixture is not available by default. To enable it, include a support module from rspec-rails:
FactoryBot::SyntaxRunner.include(RSpec::Rails::FileFixtureSupport)
That includes ActiveSupport::Testing::FileFixtures, where file_fixture is defined, but also configures the file_fixture_path so that you can actually use file_fixture.
What The Rails Security Issue Means For Your Startup
January has been a very bad month for Ruby on Rails developers, with two high-severity security bugs permitting remote code execution found in the framework and a separate-but-related compromise on rubygems.org, a community resource which virtually all Ruby on Rails developers sit downstream of. Many startups use Ruby on Rails. Other startups don’t but, like the Rails community, may one day find themselves asking What Do We Do When Apocalyptically Bad Things Happen On Our Framework of Choice? I thought I’d explain that for the general c...
Nice way to set data attributes when creating elements with Rails helpers
You can say this in helpers like link_to and content_tag:
= link_to 'Label', root_url, :data => { :foo => 'bar', :bam => 'baz' }
This will produce:
<a href="/" data-foo="bar" data-bam="baz">Label</a>
Only works in Rails 3. In Rails 2 you do
= link_to 'Label', root_url, 'data-foo' => 'bar', 'data-bam' => 'baz' }
console-for opens a Rails console remotely on a Capistrano deployment target
We're adding a script console-for to open a remote Rails console with one command. Also have a look at shell-for, which this script is relying on.
Run it from any project directory like this, passing a Capistrano multistage deployment target:
console-for staging
This script is part of our geordi gem on github.
Use the Ruby debugger on Rails 2 script/runner scripts
This card needs to be updated for Rails 3+.
Since there is no --debugger flag you need to run:
rdebug script/runner lib/scripts/something.rb
That will open an debugging IRB right away, like this:
require File.dirname(__FILE__) + '/../config/boot'
(rdb:1) _
Enter c to continue and reach your actual debugger call. Then, debug away.
If nothing happens for you: Make sure ruby-debug is available in the Gemfile and you require it.
Creating the inverse of a Rails migration
Let's say you need to revert a migration that happened a while back. You'd create a new migration that removes what was added back then in the up path, while its down path restores the old functionality.
While you could just copy&paste the down and up parts of it to the inverse part of the new migration, you may not want to do that. Especially when the up/down paths already contained some logic (that executed update statements on the created column, for example), copying does not feel right.
Someone already added the logic how to...
What’s Up With All These Changes in Rails?
Yesterday, there was a blog post entitled “What the Hell is Happening to Rails” that stayed at the number one spot on Hacker News for quite a while. The post and many (but not most) the comments on the post reflect deep-seated concern about the recent direction of Rails. Others have addressed the core question about change in the framework, but I’d like to address questions about specific changes that came up in the post and comments.
How to load an SQL dump from a migration
If you want to load an SQL dump from an ActiveRecord migration, you might find this to be harder than you thought. While you can call ActiveRecord::Base.connection.execute(sql) to execute arbitrary SQL commands, the MySQL connection is configured to only accept a single statement per query. If you try to feed it multiple statements, it will die with You have an error in your SQL syntax.
You can work around this by opening a second MySQL connection that does accept multiple statements per call.
Below is an example for a migration that l...
Exporting to Excel from Rails without a gem
See this Railscast.
Basically you can simply write views like index.xlsx.erb:
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="Sheet1">
<Table>
<Row>
<Cell><Data ss:Type="String">ID</Data></Ce...
Rails 4 Engines - TechRabbit
At TaskRabbit, we have gone through a few iterations on how we make our app(s). In the beginning, there was the monolithic Rails app in the standard way with 100+ models and their many corresponding controllers and views. Then we moved to several apps with their own logic and often using the big one via API. Our newest project is a single “app” made up of several Rails engines. We have found that this strikes a great balance between the (initial) straightforwardness of the single Rails app and the modularity of the more service-oriented ar...
Rails: How to provide a public link in a mail
Lets say we have a user with a contract whereas contract is a mounted carrierwave file.
Now we want to send the link to the contract in a mail. For this use case join the root_url with the public contract path in the mailer view:
Plain text email
URI.join(root_url, @user.contract.url)
HTML email
link_to('Show contract', URI.join(root_url, @user.contract.url).to_s)
Note: You need to follow [http://guides.rubyonrails.org/action_mailer_basics.html#g...
wycats/artifice
Artifice allows you to replace the Net::HTTP subsystem of Ruby with an equivalent that routes all requests to a Rack application.
You can use Sinatra, raw Rack, or even Rails as your application, allowing you to build up an equivalent to the remote service you are mocking out using familiar and convenient tools to route requests and build up responses.
Rails 4.2 Foreign Key Support
The migration DSL now supports adding and removing foreign keys. They are dumped to schema.rb as well. At this time, only the mysql, mysql2 and postgresql adapters support foreign keys. @rubyonrails
Workings
add_foreign_key(:comments, :users)
adds a database constraint
ALTER TABLE "comments" ADD CONSTRAINT comments_user_id_fk FOREIGN KEY ("user_id") REFERENCES "user" ("id")
Disadvantage
Foreign key constraints double the validatio...
Some nifty Rails Rake tasks
Did you know?
rake stats # => LOC per controllers, models, helpers; code ratios, and more
rake notes # => collects TODO, FIXME and other Tags from comments and displays them
rake about # (Rails 3+) => Rails, Ruby, Rake, Rack etc. versions, used middlewares, root dir, etc.
Rails 3/4: How to add routes for specs only
If you want to have routes that are only available in tests (e.g. for testing obscure redirects), you can use the with_routing helper -- but that one destroys existing routes which may break a specs that require them to work.
To keep both "regular" and test routes, do this:
class MyApplicationController < ActionController::Base
def show
render text: 'Welcome to my application'
end
end
test_routes = Proc.new do
get '/my_application' => 'my_application#show'
end
Rails.application.routes.ev...