Skip to content

Instantly share code, notes, and snippets.

@delba
delba / answer_test.rb
Last active December 17, 2015 19:09
Testing that a callback is triggered
require 'test_helper'
class AnswerTest < ActiveSupport::TestCase
def setup
Answer.before_save do
instance_variable_set :@first_callback, true
end
@answer = Answer.create!
end
@delba
delba / question_test.rb
Last active December 17, 2015 19:19
Testing validations with I18n and validators_on
require 'test_helper'
class QuestionTest < ActiveSupport::TestCase
include ActionView::Helpers::TranslationHelper
test "title is required" do
question = Question.new.tap(&:valid?)
assert_includes question.errors[:title],
t('errors.messages.blank')
end
@delba
delba / refinements.rb
Last active December 17, 2015 20:19
Ruby refinements
module FloatDivision
refine Fixnum do
def /(other)
self.to_f / other
end
end
end
using FloatDivision
@delba
delba / song.rb
Last active December 18, 2015 00:38
Store formatted duration like 03:30 in seconds
class Song < ActiveRecord::Base
def length=(length)
return unless length =~ /\A\d+:\d{2}\z/
minutes, seconds = length.split(':').map(&:to_i)
write_attribute(:length, minutes * 60 + seconds)
end
def length
return unless length = read_attribute(:length)
"%02d:%02d" % length.divmod(60)
@delba
delba / create_users.rb
Created June 5, 2013 18:57
Add unique index
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :password_digest
t.index :username, unique: true
t.index :email, unique: true
@delba
delba / user.rb
Created June 5, 2013 20:04
one-line Active Record Callback
class User < ActiveRecord::Base
before_save(if: :username_changed?) { username.downcase! }
before_save 'username.downcase!', if: :username_changed?
before_save ->{ username.downcase! }, if: :username_changed?
end
@delba
delba / application_controller.rb
Last active March 17, 2016 09:57
use current_user in controller tests
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
private
def signed_in?
!!session[:user_id]
end
helper_method :signed_in?
@delba
delba / time.rb
Created June 12, 2013 19:09
strftime
Time.now.strftime("%I:%M%p") #=> "09:06PM"
Time.now.strftime("%H:%M") #=> "21:06"
@delba
delba / constraints.rb
Created June 18, 2013 20:47
Constraints in routes
# config/initializers/contraints.rb
module Constraints
class Subdomain
def self.matches?(request)
request.subdomain.present? && request.subdomain != 'www'
end
end
class SignedIn
@delba
delba / form_helper.rb
Created June 21, 2013 23:33
Use helpers in Capybara tests
module FormHelper
def login_form
find('#new_session')
end
end