Skip to content

Instantly share code, notes, and snippets.

@Schwad
Schwad / Sandbox.rb
Created May 11, 2018 12:43
Description to self about certain ruby methods. For safe keeping really. If you've stumbled on here for some reason, hello!
# Enumerable's Detect
# - returns first element for which block returns true and then stops. If none returns nil.
(1..100).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> 35
# Find All
(1..10).find_all { |i| i % 3 == 0 } #=> [3, 6, 9]
# Reject
class AttributesApiExample < ApplicationRecord
attribute :start_date, :date, default: -> { 1.day.from_now }
attribute :end_date, :date, default: -> { 8.days.from_now }
attribute :my_attribute, :my_type, default: -> { 'My Default Value' }
end
class Current < ActiveSupport::CurrentAttributes
attribute :account, :user
attribute :request_id, :user_agent, :ip_address
resets { Time.zone = nil }
def user=(user)
super
self.account = user.account
Time.zone = user.time_zone
@Schwad
Schwad / deploy
Created December 5, 2017 16:19
bin/deploy deployment of a Ruby on Rails application to Heroku
# Sets up APPLICATION_NAME_HERE and deploys to Heroku. This should be run while on master
# NOTE: if you get a permission denied error, try running `chmod u+x bin/deploy` in the terminal
# Fails script if any commands fail
set -e
echo '== Installing dependencies =='
bundle install
def blocks_double_render_error
@books = Book.all
render 'index' and return
render 'show'
@books.last.update_column(:title, 'Or am I?')
end
#=> Rendering books/index.html.haml within layouts/application
#=> Book.last.title
#=> "Surprise Surprise"
def double_render_error
@books = Book.all
render 'index'
render 'show'
end
#=> AbstractController::DoubleRenderError - Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action.
def extra_curricular_activity
@book = Book.find(params[:id])
render 'show'
@book.update_column(:title, 'Surprise Surprise')
end
#=> SQL (7.1ms) UPDATE "books" SET "title" = 'Surprise Surprise' WHERE "books"."id" = $1 [["id", 1]]
def show
@book = Book.find(params[:id])
render 'unexpected'
end
#=> Rendering books/unexpected.html.haml within layouts/application
def index
@books = Book.all
end
#=> Rendering books/index.html.haml within layouts/application
@Schwad
Schwad / nostalgic_case.rb
Created July 30, 2017 11:30
Nostalgic Case extension for String class in ruby.
class String
def nostalgic_case
upcase.chars.join(" ")
end
end