Skip to content

Instantly share code, notes, and snippets.

# Override Paperclip's content-type guessing support to add more MIME types.
# We actually have to monkey-patch File to do this, because Paperclip
# monkey-patches File to add #content_type (from module Paperclip::Upfile).
class File
def content_type_with_extras
type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
case type
when "pdf" then "application/pdf"
# add more content types here
else content_type_without_extras
@samstokes
samstokes / regex-groups-global.rb
Created November 18, 2009 03:28
How to extract groups from a regex match in Ruby without globals or temporary variables. Code snippets supporting http://blog.samstokes.co.uk/post/251167556/regex-style-in-ruby
if "[email protected]" =~ /@(.*)/
$1
else
raise "bad email"
end
# => "example.com"
@samstokes
samstokes / regex-snippet.rb
Created November 20, 2009 20:46
Code snippet from http://www.kalzumeus.com/2009/11/17/practical-metaprogramming-with-ruby-storing-preferences/ that taught me something new about Ruby syntax and regex usage.
caller[0][/`([^']*)'/, 1]
"[email protected]"[/@(.*)/, 1] # => "example.com"
@samstokes
samstokes / equi.rb
Created January 8, 2010 21:05
Solution to Codility demo problem, finding equilibrium index of an array
def sums_before(src)
dest = [0]
src.each_with_index do |item, index|
dest[index + 1] = dest[index] + item
end
dest
end
def equi ( arr )
sums_left = sums_before(arr)
Foodiddlybar