Skip to content

Instantly share code, notes, and snippets.

@jimworm
jimworm / deploy.rb
Created April 3, 2023 15:30
using stage configuration variables in capistrano append
# abuse capistrano variable validators to
# use stage configs with the non-lazy #append
# this bit sets a global config before the stage is loaded
append :linked_files, 'config/database.yml', 'config/other.yml'
# this bit will run after the variable you need is set
validate :rails_env do |_, value|
append :linked_files, "config/credentials/#{value}.key"
end
system('clear')
begin
runs, score = 0, 0
3.times do
add, (i1, i2) = rand(2).zero?, [rand(750), rand(250)].sort
sym, answer = if add
['+', (i1 + i2)]
else
['-', (i2 - i1)]
@jimworm
jimworm / searchable.rb
Last active September 7, 2015 16:42
Rails: search for members of a model using its columns or columns of related models, SQL-only
module Searchable
extend ActiveSupport::Concern
module ClassMethods
def searchable(*args)
class_attribute :searchable_attributes
self.searchable_attributes = args
end
def search(search_string, limit=100)
@jimworm
jimworm / change_validator.rb
Created July 20, 2012 07:51
Enforce/prevent attribute change in Rails 3
class ChangeValidator < ActiveModel::EachValidator
# Enforce/prevent attribute change
#
# Example: Make attribute immutable once saved
# validates :attribute, change: false, on: :update
#
# Example: Force attribute change on every save
# validates :attribute, change: true
def initialize(options)
@jimworm
jimworm / temp_locale_controller.rb
Created July 15, 2011 12:26
Quickly do something in a locale then switch back
class ActionController::Base
protected
def do_using_temp_locale(temp_locale, &block)
if I18n.available_locales.include?(temp_locale.to_sym)
original_locale = I18n.locale
I18n.locale = temp_locale
return_value = yield
I18n.locale = original_locale
else
return_value = yield
@jimworm
jimworm / simple_search.rb
Created June 16, 2011 15:36
Simple search for all Rails 3 ActiveRecord models on any string column(s)
class ActiveRecord::Base
class << self
def has_simple_search(*attrs)
raise 'has_simple_search expects at least one attribute' if attrs.empty?
instance_eval do # because this is ActiveRecord::Base, the class inherits this
write_inheritable_attribute(:simple_search_fields, attrs.flatten)
def simple_search(search_string)
attrs = read_inheritable_attribute(:simple_search_fields)
like_s = attrs.map{|f| "#{self.table_name}.#{f.to_s} REGEXP ?"}.join(' OR ')
terms = search_string.split(' ').map{|s| Regexp.escape(s.strip)}