Flowdock

Notes posted by leente

RSS feed
December 30, 2011
0 thanks

See also: sample

sample randomly picks 1 or n elements from the array

September 30, 2011 - (v3.0.0 - v3.1.0)
0 thanks

Without module

If you want to have only the path prefix without namespacing your controller, pass :module => false.

Normal:

namespace :account do
  resources :transactions, :only => [:index]
end

account_transactions GET /account/transactions(.:format)
{:controller=>"account/transactions", :action=>"index"}

With :module => false:

namespace :account, :module => false do
  resources :transactions, :only => [:index]
end

account_transactions GET /account/transactions(.:format)
{:controller=>"transactions", :action=>"index"}
March 15, 2011
0 thanks

Don't cache it!

Don’t store a connection in a variable, because another thread might try to use it when it’s already checked back in into the connection pool. See: ActiveRecord::ConnectionAdapters::ConnectionPool

connection = ActiveRecord::Base.connection

threads = (1..100).map do
  Thread.new do
    begin
      10.times do
        connection.execute("SELECT SLEEP(1)")  # WRONG
        ActiveRecord::Base.connection.execute("SELECT SLEEP(1)")  # CORRECT
      end
      puts "success"
    rescue => e
      puts e.message
    end
  end
end

threads.each(&:join)
December 21, 2010 - (<= v2.3.8)
0 thanks

reload next time referenced

After calling reset on an association, it will be forced to be reloaded next time it’s referenced. Useful after you manipulate an associated object/collection with SQL, and you want to make sure subsequent uses don’t get the invalid cached version. Better than reload in that it doesn’t actually reload if not needed.

October 13, 2010 - (v2.1.0 - v3.0.0)
1 thank
September 13, 2010 - (>= v1.0.0)
2 thanks

No concurrency

If you want to handle concurrency, this doesn’t work:

a = Article.first
b = Article.first
a.increment!(:view_count)
b.increment!(:view_count)
a.reload.view_count # -> 1
b.reload.view_count # -> 1

Instead, use SQL:

def increment_with_sql!(attribute, by = 1)
  raise ArgumentError("Invalid attribute: #{attribute}") unless attribute_names.include?(attribute.to_s)
  original_value_sql = "CASE WHEN `#{attribute}` IS NULL THEN 0 ELSE `#{attribute}` END"
  self.class.update_all("`#{attribute}` = #{original_value_sql} + #{by.to_i}", "id = #{id}")
  reload
end
November 23, 2009
3 thanks

Make directory if not exists

If the directory already exists, mkdir raises exception. To prevent this:

Dir.mkdir(dir) unless File.exists?(dir)
October 10, 2009
2 thanks

Example

[5,6,7].each_with_index do |x,i|

puts "#{i} -> #{x}"

end

Outputs: 0 -> 5 1 -> 6 2 -> 7