Instantly share code, notes, and snippets.

Kris Leech krisleech

View GitHub Profile
View example.rb
# Lets say we have a Book model and we want to fetch some data about the book from an API and store it in the model.
# A Book needs an identifier before it can be fetched from the API. Not all books have an identifier, e.g. it may not have been entered yet.
# Do we silently return in FetchFromApi when the book has no identifer:
class FetchFromApi
def call(book)
return unless record.identifier.present?
# do API call and update record
View app.rb
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'active_record'
gem 'sqlite3'
end
View example.rb
if study.require_participant_type?
packed_permutations << Recruitment::ParticipantType.pluck(:identifier).append(nil)
else
packed_permutations << [].append(nil)
# or packed_permutations << [nil] (same, but less symmetry)
end
# or
packed_permutations << (study.require_participant_type? ? Recruitment::ParticipantType.pluck(:identifier) : []).append(nil)
View HOWTO.md
# in engine

class CreateStudy
  extend ActiveModel::Callbacks
  define_model_callbacks :create

  def call(form)
    if form.valid?
      @study = Study.new(form.study_attributes)
View HOWTO.md
require 'dry-validation'
require 'dry-struct'
require 'active_model/errors'

require_relative '../create_study'

module MyApp
  module Types
    include Dry::Types.module
View activerecord.md

ActiveRecord SQL queries in stdout, good for specs or console:

require 'active_record'
ActiveRecord::Base.logger = Logger.new(STDOUT)
View notes.md

Backtrace lines from engines outside of Rails root or GEM_PATH, i.e. referenced with path in Gemfile are stripped from the backtrace:

Rails.backtrace_cleaner.clean(["#{Rails.root}/lib/foo, '/home/me/dev/otherproject/lib/foo'])
# => ['<rails_root>/lib/foo']


Rails.backtrace_cleaner.remove_silencers!
View renew-gpgkey.md

Renew GPG key

Given that your key has expired.

$ gpg --list-keys
$ gpg --edit-key KEYID

Use the expire command to set a new expire date:

View di_clock_spec.rb
describe '#call' do
let(:today) { Date.parse('20/08/2018') }
let(:clock) { double('Clock', today: today) }
it 'generates report up to last month' do
subject = described_class.new(clock: clock)
# ...
end
end
View cache_buster.rb
# Cache buster
# Generic object which will invalidate a cache key for an event.
class CacheBuster
def initialize(dependencies = {})
@cache = dependencies.fetch(:cache) { Rails.cache }
end
def self.build(options)