active record import

to read:

https://github.com/zdennis/activerecord-import/wiki

https://github.com/zdennis/activerecord-import/wiki/MySQL:-On-Duplicate-Key-Update-Support

https://github.com/zdennis/activerecord-import/wiki/Examples

determine if a constant is defined

  1. use the Ruby built-in: defined?  It works for constants, methods, classes, etc.
  2. self.class.const_defined?(:My_Constant)

There is no better among these two choices. Choosing which one depends on the user case. The second way specifies the scope to check if the constant exists, while the first way will seek for this constant through the ancestor trees. If you defines two constants with the same name but different values, you’d better use the 2nd way.

see http://tech.groups.yahoo.com/group/Houston-RoR/message/2926

  • scope of constants:Ruby searches for the constant definition in this order:
    1. The enclosing scope
    2. Any outer scopes (repeat until top level is reached)
    3. Included modules
    4. Superclass(es)
    5. Object
    6. Kernel

better read: http://coderrr.wordpress.com/2008/03/11/constant-name-resolution-in-ruby/

class C
  X = 1
  module M
    X = 2
    class D
      X = 3
      puts X          # => 3
      puts C::X       # => 1
      puts C::M::X    # => 2
      puts M::X       # => 2    
    end
  end
end

stub method to return different values based on the times it is called

You can stub a method to return different values each time it’s called;

@family.stub(:location).and_return('first', 'second', 'other')

So the first time you call @family.location it will return ‘first’, the second time it will return ‘second’, and all subsequent times you call it, it will return ‘other’.

source: http://stackoverflow.com/questions/5947999/can-rspec-stubbed-method-return-different-values-in-sequence

stub a method and return the value depending on the parameter

stub! can accept a block. The block receives the parameters; the return value of the block is the return value of the stub:

class Interface
end

describe Interface do
  it "should have a stub that returns its argument" do
    interface = Interface.new
    interface.stub!(:get_trace) do |arg|
      arg
    end
    interface.get_trace(123).should eql 123
  end
end

source: http://stackoverflow.com/questions/5938049/rspec-stubbing-return-the-parameter