Hash#without

Mange Oct 7, 2009 4 thanks

Here's a small helper for doing the "opposite" of this method: class Hash def without(*keys) cpy = self.dup keys.each { |key| cpy.delete(key) } cpy end end

h = { :a => 1, :b => 2, :c => 3 }
h.without(:a)      #=> { :b => 2, :c => 3 }
h.without(:a, :c)...

Streaming XML with Builder

mutru Oct 7, 2009 3 thanks

To generate larger XMLs, it's a good idea to a) stream the XML and b) use Active Record batch finders.

Here's one way of doing it:

def my_action
@items = Enumerable::Enumerator.new(
  Item.some_named_scope,
  :find_each,
  :batch_size => 500)

respond_to do |format|
  f...

Using argument version in ruby < 1.8.7

Mange Oct 5, 2009 1 thank

The argument to this method was added in Ruby 1.8.7. If you want to use this form in an earlier version, you must instead use the slice! method.

It is mentioned up in the docs, but here it is again for reference:

# Ruby >= 1.8.7
p = list.pop(n)

# Ruby < 1.8.7
p = list.slice!(-n, n...

collect/map

Mange Oct 5, 2009 3 thanks

If you'd like to use this method for something like Enumerable#collect, you are looking at the wrong place. This method will return the initial integer, not the values from the block.

a = 20.times { |n| n * 2 } #=> 20

Instead, use Range#collect:

a = (0...20).collect { n * 2 }

Making ActiveRecord models readonly

autonomous Oct 2, 2009 2 thanks

To force an ActiveRecord model to be read only you can do something along these lines:

class DelicateInfo < ActiveRecord::Base

def readonly?

true end

end

When you try to save the model it will raise an ActiveRecord::ReadOnlyRecord exception:

info = DelicateInfo.first info.save #...