Skip to content

Instantly share code, notes, and snippets.

@ntl
ntl / simple_exposing.rb
Last active August 29, 2015 13:56
The idea here is to give you a simple method that can define your ivar for you, protecting against `nil` proactively, and record the location where the ivar was defined. Best part is, if someone looks for where `#expose` is defined, they'll be happy to find out it's not in a gem. Easy to modify/understand.
# Instead of ditching ivars, just make them easier to discover:
class ApplicationController < ActionController::Base
private
# Expose an object as an ivar to your views. Explodes if you try to assign nil.
#
# Use:
#
# The controller; yeah it's not great but I want to show the tests
class ProductsController < ApplicationController
def index
if params[:min_rating]
@products = Product.where("average_rating >= ?", params[:min_rating])
else
@products = Product.to_a
end
end
end
@ntl
ntl / event_sourcing_example.rb
Last active August 29, 2015 13:57
In my usage so far, an "Event" doesn't get its own type; it's an object that transports attributes. The listeners also use a class method to route events to methods on the object. In this way, you can test event handlers as you would any other ruby method.
# app/commands/receive_bonus_command.rb
# Commands look like ActiveModel+virtus "ish" objects
class ReceiveBonusCommand < Command
attribute :income_source_id, String
attribute :bonus_amount, Integer
attribute :effective_date, Date
validates :account_id, presence: true
def validate
source "https://rubygems.org"
gem "whatever"
# Load minitest and red-green
group :minitest do
gem "minitest"
gem "minitest-rg"
end
class InitializerArgumentsPaymentProcessor
def initialize(number, expiration_date, amount)
@number, @expiration_date, @amount = number, expiration_date, amount
end
def call
if SomeGateway.(number, expiration_date, amount)
true
else
false
@ntl
ntl / pattern-matching.rb
Created June 15, 2018 21:02
Conditional Examples in Ruby
# This is an example using Eventide's message handling DSL for declaring different
# handler methods based on message type
class SomeHandler
include Messaging::Handle
handle SomeMessage do |some_msg|
# ...
end
handle OtherMessage do |other_msg|