Skip to content

Instantly share code, notes, and snippets.

View nathanl's full-sized avatar

Nathan Long nathanl

View GitHub Profile
@nathanl
nathanl / activerecord_model_scopes.rb
Last active May 27, 2019 06:39
Rails code to use PostGIS in place of some of Geocoder's functionality - based on http://ngauthier.com/2013/08/postgis-and-rails-a-simple-approach.html
# Scopes that make use of the index
def self.within_distance_of(lat:, lng:, meters:)
where(%{
ST_DWithin(
ST_GeographyFromText(
'SRID=4326;POINT(' || #{table_name}.longitude || ' ' || #{table_name}.latitude || ')'
),
ST_GeographyFromText('SRID=4326;POINT(%f %f)'),
%d
)
@nathanl
nathanl / .vimrc
Created July 8, 2015 19:35
Flash current cursor position in Vim
" <cr> should not only clear highlighted search, but flash the current
" cursor location.
:nnoremap <CR> :nohlsearch<CR>:set cul cuc<cr>:sleep 50m<cr>:set nocul nocuc<cr>/<BS>
@nathanl
nathanl / stupid_t.rb
Last active August 29, 2015 14:22
Quick and dirty way to spot non-localized strings in a Rails app page
# config/initializers/stupid_t.rb
# Any text that doesn't appear as "localized" isn't localized
module ActionView::Helpers::TranslationHelper
def t(*args)
result = I18n.t!(*args)
if result.respond_to?(:map)
result.map { |r| "localized" }
else
"localized"
end
@nathanl
nathanl / exponential_backoff.rb
Created February 25, 2015 14:41
Exponential backoff in Ruby
# Exponential backoff in Ruby
begin
make_request
rescue RequestError => e
if retries <= max_retries
retries += 1
sleep 2 ** retries
retry
else
raise "Timeout: #{e.message}"
@nathanl
nathanl / traveling_salesman_brute_force_time.rb
Created February 21, 2015 13:08
How long it takes to solve the Traveling Salesman problem by brute force
def factorial(n)
(1..n).reduce(:*)
end
SECONDS_PER_STEP = 0.001
def total_seconds(n)
factorial(n) * SECONDS_PER_STEP
end
@nathanl
nathanl / test_pathfinding.rb
Created October 23, 2014 19:55
Test pathfinding
# This can be run from the voltron directory while the NetSkycanner has a couple of `rake pathfinder` processes running
require 'bundler/setup'
Bundler.require :default, :pathfinder
require 'json'
require 'thump'
require 'mr_sulu_messages'
test = "searching"
@nathanl
nathanl / p.rb
Created August 8, 2014 19:10
Ruby `p` with location
def p(*args)
location = caller_locations(1,1)[0]
location_string = "#{location.path.split('/').last}:#{location.lineno}(#{location.label})"
super([*args, location_string])
end
@nathanl
nathanl / ruby_log_formatting.rb
Created February 11, 2014 14:49
Nice Ruby log formatting
require 'logger'
l = Logger.new(STDOUT)
l.formatter = proc { |severity, datetime, progname, msg|
dt = datetime.strftime('%Y-%b-%d@%H:%M:%S:%z')
"#{[severity,dt,progname,msg].join(' ').squeeze(' ')}\n"
}
l.info "woot" #=> INFO 2014-Feb-11@09:48:32:-0500 woot
@nathanl
nathanl / safe_console.js
Last active December 21, 2015 21:29
Safer console.log
// A safer console object (https://gist.github.com/nathanl/6368185)
// - Ensures `console.log` doesn't cause errors in browsers with no console
// - Lets you enable/disable console logging (using console.enable = true/false)
// - Supports all console methods documented here: https://developer.mozilla.org/en-US/docs/Web/API/console
//
// Less fancy but lighter weight than this: http://benalman.com/projects/javascript-debug-console-log/
safe_console = {
enabled: false,
original_console: (function(){
// If the browser has no usable one, define a no-op
@nathanl
nathanl / activerecord_scope_conditions.rb
Created June 11, 2013 14:45
Using joins and conditions in ActiveRecord scopes. (This was hard for me to find documentation on.)
class Person < ActiveRecord::Base
# This manual SQL query...
scope :allowed_to_eat_cheese, joins(
<<-SQL
INNER JOIN cities ON people.city_id = cities.id
INNER JOIN states ON cities.state_id = states.id
SQL
).where('states.allows_cheese_consumption' = 'Yeppers')