This is a little snippet I use:
date_of_last_fee_change = Fee.last_updated
To make it happen for all models:
ActiveRecord::Base.class_eval do def self.last_updated last = first(:order => 'updated_at DESC') last.try(:updated_at) end end
date_of_last_fee_change = Fee.last_updated
ActiveRecord::Base.class_eval do def self.last_updated last = first(:order => 'updated_at DESC') last.try(:updated_at) end end
#!/usr/bin/ruby
PATH = '/mnt/apps'
Dir.glob("#{PATH}/*").each do |dir|
Dir.chdir(dir)
puts "(in #{dir})"
ARGV.each { |cmd| system(cmd) }
end
./each-app.rb 'git pull' 'rake db:migrate'
chmod +x each-app.rb
>> [1,2,3].first {|x| x > 1 }
=> 2
class Array
def first
each do |x|
return x if !block_given? || yield(x)
end
end
def last
reverse_each do |x|
return x if !block_given? || yield(x)
end
end
end
a = [1,2,3]
puts a.first # => 1
puts a.first {|x| x>1 } # => 2
puts a.last # => 3
puts a.last {|x| x<2 } # => 1
static VALUE
rb_ary_first(argc, argv, ary)
int argc;
VALUE *argv;
VALUE ary;
{
if (argc == 0) {
if (rb_block_given_p()) {
long i;
RETURN_ENUMERATOR(ary, 0, 0);
for (i=0; ilen; i++) {
if (RTEST(rb_yield(RARRAY(ary)->ptr[i]))) {
return RARRAY(ary)->ptr[i];
}
}
return Qnil;
} else {
if (RARRAY(ary)->len == 0) return Qnil;
return RARRAY(ary)->ptr[0];
}
}
else {
return ary_shared_first(argc, argv, ary, Qfalse);
}
}
class Array
def quicksort
return self if length <= 1
pivot = shift
less, greater = partition {|x| x <= pivot}
less.quicksort + [pivot] + greater.quicksort
end
end
puts [8,99,4,1000,1,2,3,100,5,6].quicksort.join(',')
class MultiplePageSearch
include PagedEnumerable
def each_page
10.times { |page| yield download_page(page) } # simulate 10 pages
end
private
def download_page(page)
puts "downloading page #{page}..."
sleep 1 # simulate slooow operation
start = page*10
start...(start+10)
end
end
paged = MultiplePageSearch.new
puts paged.any? {|x| x > 50} # will only hit 5 pages
paged.each {|x| puts x} # will process all pages
module PagedEnumerable
def self.included(obj)
obj.send :include, Enumerable
end
def each(&blk)
each_page { |page| page.each(&blk) }
end
end
yum install openssl-devel curl-devel expat-devel -y
wget http://www.kernel.org/pub/software/scm/git/git-VERSION.tar.gz
tar xvf git-VERSION.tar.gz
cd git-VERSION
make
make install