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

Saturday, 23 February 2013

rials and ruby postcasts and screencasts



Also worth checking

rspec, capybara and factorygirl hints

# spec_helper.rb

# this line will make rpsec end at the first failing test
RSpec.configure do |c|
  c.fail_fast = true
end
# in integration specs

# xpath can be copied from chrome, rx-click on the element (in the dev-tool)
page.should have_xpath("//a[contains(@href,'users')]"), count: num)

rails sandbox tasks

desc 'do not permanently write on the db (good for testing rake tasks)'
task :sandbox => :environment do
  puts "** << USING SANDBOX!! >> **"

  # beginning
  ActiveRecord::Base.connection.increment_open_transactions
  ActiveRecord::Base.connection.begin_db_transaction

  # end
  at_exit do
     ActiveRecord::Base.connection.rollback_db_transaction
     ActiveRecord::Base.connection.decrement_open_transactions
  end    
end

yaml defaults example (postgres on ruby on rails)

postgres:   &postgres
  adapter:  postgresql
  encoding: unicode
  host:     localhost
  username: netengine
  password:

development:
  <<: *postgres
  database: propertyconnect_development

test:
  <<: *postgres
  database: propertyconnect_test