Skip to content

Instantly share code, notes, and snippets.

@szimek
Created January 1, 2012 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szimek/1548609 to your computer and use it in GitHub Desktop.
Save szimek/1548609 to your computer and use it in GitHub Desktop.
Tips from Mike Bleigh's presentation @ http://confreaks.net/videos/751-rubymidwest2011-rails-is-the-new-rails + some more

Model based constraints:

constraints Account do
  resources :users
end

class Account < AR::Base
  def self.matches(request)
    Account.find_by_subdomain(request.subdomain).present?
  end
end

GitHub style routing:

resources :repos, path: '', id: /a-z+\/a-z+/i do
  resources :issues
end
  • id: /[a-z]+\/[a-z]+/ - params with slashes in the middle
  • path: '' - skip path prefix, so in URL you'll have "/:id" instead of "/repos/:id"

Disable helper generation when generating controller

# config/application.rb
config.generators.helper = false

SCSS to SASS

# config/application.rb
config.sass.preferred_syntax = :sass if config.sass

Scope Your Assignment Rules

# app/models/user.rb
class User < ActiveRecord::Base
  attr_protected :verified
end

# app/controllers/users_controller.rb
def update
  # won't update the "verified" column
  @user.update_attributes(params[:user])
end

# app/controllers/admin/users_controller.rb
def update
  # will update the "verified" column
  @user.update_attributes(params[:user], as: :admin)
end

Touching for Cache Keys

# app/models/post.rb
class Post < ActiveRecord::Base
  belongs_to :section, touch: true
end
<!-- app/views/sections/index.html.erb -->
<% for section in @sections %>
  <% cache "section/#{section.id}/#{section.updated_at}" do %>
    <%= render partial: "posts/post", collection: section.posts %>
  <% end %>
<% end %>

HTTP Basic

class ApplicationController < ActionController::Base
  http_basic_authenticate_with name: ENV['BETA_USER'], password: ENV['BETA_PASS']
end

Capturing Output

# app/helpers/tabs_helper.rb
module TabsHelper
  def tab_set(&block)
    with_output_buffer(&block).upcase.html_safe
  end
 
  def tab(&block)
    with_output_buffer(&block).upcase.html_safe
  end
end
<%= tab_set do %>
  <%= tab do %>
    <%= link_to "Something", "#" %>
  <% end %>
<% end %>

Enforce mass assignment (possibly on by default in Rails 4.0)

# config/application.rb
config.active_record.whitelist_attributes = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment