Skip to content

Instantly share code, notes, and snippets.

@tompave
tompave / gist:942dec39d2112cced0d8
Created May 19, 2014 15:36
client IP in Rails 3.2
# in a controller
# request.remote_ip -> http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-remote_ip
# default IP lookup -> http://api.rubyonrails.org/classes/ActionDispatch/RemoteIp/GetIp.html#method-i-calculate_ip
#
# request.remote_ip looks at different sources and makes a "best guess" to find the correct IP. This is usually easy
# with a plain app-server setup, but with reverse-proxy configurations (Mongrels behind Apache, Unicorns behind nginx) the
# requests are issued by the reverse-proxy (often localhost).
#
# Since we have a cluster of Unicorns behind a nginx reverse-proxy, the actual client IP is (almost) surely found in the
@tompave
tompave / User.rb
Created May 24, 2014 15:44
An example of auto expiring user tokens
require 'digest/md5'
class User
attr_accessor :name, :token_valid_for
attr_reader :pwd_hash
def initialize(name, pwd)
self.name = name
self.password = pwd
@tompave
tompave / foobar_config.rb
Last active August 29, 2015 14:01
Some configuration techniques in Ruby
module Foobar
module Config
class << self
attr_writer :foo, :bar, :baz
def foo(value = nil)
if value
self.foo = value
else
@foo
@tompave
tompave / timer.rb
Created June 25, 2014 23:37
Ruby simple timer
def timer(seconds, &block)
Thread.new {
t_0 = Time.now
sleep seconds
elapsed = Time.now - t_0
puts "timer triggered after #{elapsed} seconds (error: #{elapsed - seconds})."
yield
}
end
@tompave
tompave / random_iterations.rb
Created June 27, 2014 17:08
SecureRandom effectiveness
require 'securerandom'
REGEX = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])((?=.*[^\w])|(?=.*_))/
def run
times = 0
word = begin
times += 1
SecureRandom.urlsafe_base64
module SendMethodList
def send_method_list(*methods)
results = methods.map do |sym|
begin
self.send(sym)
rescue => error
error
end
end
end
@tompave
tompave / locals_and_blocks.rb
Last active August 29, 2015 14:04
Scoping in Ruby blocks
def set_context(c)
@context = c
end
def context
@context
end
def with_context(cont, &block)
@tompave
tompave / better_puts.rb
Created August 5, 2014 23:35
Improved, more sensible implementation of Ruby's Kernel#puts
module Kernel
TABLE_FLIP = <<-EOS
(╯°□°)╯︵ ┻━┻
EOS
alias_method :original_puts, :puts
@tompave
tompave / impersonation_utilities.rb
Last active August 29, 2015 14:05
Poor Man's cross-authentication
# impersonation_utilities.rb
require 'digest/md5'
module ImpersonationUtilities
SHARED_SECRET = "I'm a secret string!"
TOKEN_VALID_FOR_DAYS = 1
class << self
@tompave
tompave / try_chain.rb
Created January 11, 2015 19:30
Try Chain
require 'active_support/core_ext/object/try'
module TryChain
def try_chain
@proxy = Proxy.new(self)
end
class Proxy