Wednesday, 8 May 2013

regex to update from rspec 1 to rspec 2

Rspec 2 removes assign_to and replace it with assigns, here are the regex I'm using in sublime text 2 for the update:


should assign_to\((.*)\).with\(nil\)
assigns($1).should be_nil

should assign_to\(:(.+)\).with\((.+)\)
assigns(:$1).should == $2

should_not assign_to\(:(.*)\)
assigns(:$1).should be_nil

should assign_to\(:(.*)\)
assigns(:$1).should_not be_nil


Links to some doc here

Sunday, 14 April 2013

quick upload to amazon S3 with Fog and Carrierwave

require 'rubygems'
require 'fog' # version 1.10.1


fog_credentials = {
  provider: "AWS",
  aws_access_key_id: "QWERTTYQWERTTYQWERTT",
  aws_secret_access_key: "q1w2e3r4t5yQWERTYUq1w2e3r4t5yQWERTYasdf1",
  region: "ap-southeast-2" # Sydney ;)
}


CONNECTION = Fog::Storage.new fog_credentials

S3 = CONNECTION.directories.get 'bucket-name'
S3.files.create(key: 'test_me/test1', body: 'xxxxxxxxx')

The following works with Carrierwave
require 'carrierwave'
require 'fog'

CarrierWave.configure do |config|
  config.fog_credentials = {
    provider:              'AWS',
    aws_access_key_id:     'QWERTYQWERTYQWERTYTY',
    aws_secret_access_key: 'qewr1234qewr1234qwer1234qwer1234qwer1234',
    region:                'ap-southeast-2' # Sydney :)
  }
  config.fog_public    = false
  config.fog_directory = 'bucket-name'
end

class MyUploader < CarrierWave::Uploader::Base
  storage :fog
end

file = File.open('/tmp/tmp.txt')
uploader = MyUploader.new
uploader.store!(file)

Monday, 18 March 2013

ruby operator precedence explained with an example

OR has lower precence than ||, in particular assignments (=) are in the middle, therefor:
a = false || true # => true
a                 # => **true**  => a = (false || true)
# BUT
a = false or true # => true
a                 # => **false** => (a = false) or true

# another BIG difference
:a || :b && :c  # => :a          => (:a || :b) && :c
# BUT 
:a or :b and :c # => **c**       => :a or (:b and :c)


Got it?
Where does it make sense to use the English operators?
a = value or raise "a cannot be nil"

def tail_color(args)
  animal = args[:animal] and
  tail = animal.tail and
  tail.color
end


Conclusion: only use English operators for flow control, not in if statements
also see this table

Sunday, 24 February 2013

validates exclusion of controller names when catching all routes

Of course catching all routes is bad, but if you have to:
class Account < ActiveRecord::Base
  INVALID_PAGE_NAMES = Dir[Rails.root.join('app/controllers/*_controller.rb')].map { |path| path.match(/(\w+)_controller.rb/); $1 }
  validates :page_name, :exclusion => { :in => INVALID_PAGE_NAMES,
    :message => "Page %{value} is reserved." }
end