Code written in Ruby

Computer: Where am I right now in my rails application?

Posted by Chad Humphries 9 days ago
# This came from 20 minutes of goofing off
before_filter :where_am_i_right_now

def where_am_i_right_now
  %x{say 'processing #{params[:action].humanize} on the #{params[:controller]} controller'}
end
Language Ruby / Tagged with rails, bad

Create a Hash from two Array objects

# Requires Ruby 1.8.7 or higher.

>> keys = [1,2,[3,4]]
=> [1, 2, [3, 4]]
>> values = ['a','b',['c','d']]
=> ["a", "b", ["c", "d"]]
>> Hash[ * keys.zip(values).flatten(1) ]
=> {1=>;"a", [3, 4]=>["c", "d"], 2=>"b"}
Language Ruby / Tagged with hash, array, arrays, zip

Create a Date object from a Date inspect

Posted by mqj 15 days ago
# Seeing things like "<Date: 4909275/2,0,2299161>" in logs gives no immediate 
# clue what that date is.  Now one can use Date.new_from_inspect to see what date the 
# inspect string represents.


>> Date.new_from_inspect('#<Date: 4909275/2,0,2299161>').to_s
=> "2008-06-20"
>> Date.new_from_inspect(Date.today.inspect) == Date.today
=> true


class Date
  def self.new_from_inspect(date_inspect_string)
    args = date_inspect_string.split(/[^\d]/).reject{|s| s.empty?}.map{|s| s.to_i}
    new!( Rational(*args.first(2)), *args.last(2) )
  end
end
Language Ruby / Tagged with date, inspect

Please install my gem post haste good sir!

Posted by Chad Humphries 23 days ago
# To install most quickly instead of updating the source cache do
gem install rmagick --no-update-sources
Language Ruby / Tagged with rmagick

Never do this please

Posted by Chad Humphries 24 days ago
# Stick this in a model, and enjoy.  Or don't.  Actually don't.  This was 
# written as a crazy experiment all about coulda, not about shoulda.
class ActiveRecord::Base
  def current_user
    ObjectSpace.each_object(ApplicationController) do |found_obj|
      return found_obj.send!(:current_user) if found_obj.respond_to?(:current_user) 
    end
  end
end
Language Ruby / Tagged with rails, ahhh

Where is this defined?

Posted by Chad Humphries 24 days ago
# The original version of this code was found on http://holgerkohnen.blogspot.com/ 
# long ago.  It has since been modified a good deal, renamed, and improved.

module Kernel

  # which { some_object.some_method() } => ::
  def where_is_this_defined(settings={}, &block)
    settings[:debug] ||= false
    settings[:educated_guess] ||= false
    
    events = []
    
    set_trace_func lambda { |event, file, line, id, binding, classname|
      events << { :event => event, :file => file, :line => line, :id => id, :binding => binding, :classname => classname }
      
      if settings[:debug]
        puts "event => #{event}"
        puts "file => #{file}"
        puts "line => #{line}"
        puts "id => #{id}"
        puts "binding => #{binding}"
        puts "classname => #{classname}"
        puts ''
      end
    }
    yield
    set_trace_func(nil)

    events.each do |event|
      next unless event[:event] == 'call' or (event[:event] == 'return' and event[:classname].included_modules.include?(ActiveRecord::Associations))
      return "#{event[:classname]} received message '#{event[:id]}', Line \##{event[:line]} of #{event[:file]}"
    end
    
    # def self.crazy_custom_finder
    #  return find(:all......)
    # end
    # return unless event == 'call' or (event == 'return' and classname.included_modules.include?(ActiveRecord::Associations))
    # which_file = "Line \##{line} of #{file}"
    if settings[:educated_guess] and events.size > 3
      event = events[-3]
      return "#{event[:classname]} received message '#{event[:id]}', Line \##{event[:line]} of #{event[:file]}"
    end
    
    return 'Unable to determine where method was defined.'
  end

end
Language Ruby / Tagged with meta

delegate or return something specific with the built-in delegate

Posted by Chad Humphries about 1 month ago / Source: http://dev.rubyonrails.org/ticket/4134
# You can get the short-circuit behavior you're looking for with the following 
# construct:
delegate :foo, :wibble, :to => '(bar or return nil)'

# Some people will probably find sticking an expression in the :to a bit ugly 
# but it does allow you greater freedom than just "always return nil if :to 
# evaluates to nil":
delegate :foo, :wibble, :to => '(bar or return "bar not there")'

# You could probably make a (strong) argument that it would be clearer to write 
# custom accessors - but personally I like the way delegate() works right now.
Language Ruby / Tagged with rails

Enabling git submodules in capistrano 2

Posted by Chad Humphries about 1 month ago
# Just add the following to your deploy recipe
set :git_enable_submodules, true
Language Ruby / Tagged with capistrano, git

in rjs this is one way to reference an element by class within an element by id

Posted by Ken Barker about 1 year ago
# $$('#comments-11 .author')
page.select("##{@comment.dom_id} .author").first.visual_effect :highlight
Language Ruby / Tagged with rjs

Intercepting activerecord attributes

# So, you wrote a Rails application to track Marathon events. In a sudden 
# change of heart, you pick up your company and move it from the United 
# States to Germany. Why rewrite your app to handle metric distances? 
# Rails provides a solution: write_attribute and read_attribute. 

class Marathon < ActiveRecord::Base
  def distance=(meters)
    write_attribute(:distance, meters * 1609.344)
  end

  def distance
    read_attribute(:distance) / 0.000621371192
  end
end
Language Ruby / Tagged with rails, activerecord