Skip to content

Instantly share code, notes, and snippets.

@delba
delba / routes.rb
Last active December 18, 2015 23:09
Routes syntax
root to: 'dashboard#index'
get 'signin' => 'sessions#new'
root 'dashboard#index'
get 'signin', to: 'sessions#new'
@delba
delba / application_helper.rb
Last active December 18, 2015 23:09
View block helper
module ApplicationHelper
def admins_only
yield if current_user.try(:admin?)
end
end
@delba
delba / capybara.rb
Last active December 19, 2015 04:19
Capybara DSL
assert_selector 'article', count: Article.count
assert_selector 'article', exact: Article.count
assert find_button('Save article', disabled: true).disabled?
assert has_link?('New article', href: new_article_path)
# assert that a link with text 'New article' and href new_article_path exists
# not necessarily good to track bugs
assert_equal new_article_path, find('a', text: 'New article')[:href]
@delba
delba / article_test.rb
Created June 30, 2013 18:40
Delegate constant lookup
require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
delegate :validators_on, to: Article
test "validates presence of title" do
refute_emtpy validators_on(:title).grep PresenceValidator
end
private
@delba
delba / flash.rb
Created June 30, 2013 19:25
Flash messages
# DEFAULTS (notice and alert)
flash.notice = 'notice'
flash[:notice] = 'notice'
redirect_to root_url, notice: 'notice'
notice # in view
# CUSTOM TYPES
add_flash_types :warning
@delba
delba / test_helper.rb
Created July 1, 2013 00:33
Poltergeist
require 'capybara/rails'
require 'capybara/poltergeist'
class ActionDispatch::IntegrationTest
include Capybara::DSL
Capybara.javascript_driver = :poltergeist
setup do
Capybara.current_driver = Capybara.javascript_driver
@delba
delba / generators.rb
Created July 1, 2013 16:19
Migrations
$ rails g model user email
=begin
create_table :users do |t|
t.string :email
t.timestamp
end
=end
@delba
delba / person.rb
Created July 3, 2013 22:15
Multi-line blocks
class Person; def hello; 'hello'; end; end;
Person.new.tap do |p|
puts p.hello
end.tap do |p|
puts p.hello
end
Person.new.tap { |p|
puts p.hello
@delba
delba / article.rb
Created July 9, 2013 20:19
Markdown to HTML
require 'markdown'
class Article < ActiveRecord::Base
before_save do
self.html = Markdown.new(content).to_html
end
end
@delba
delba / autofocus.js
Created July 10, 2013 13:55
Never lose focus
$(document).on('blur', '#input', function(e) {
var $this = $(this);
setTimeout(function() {
$this.focus();
});
});