Skip to content

Instantly share code, notes, and snippets.

@tamizhgeek
Last active October 4, 2015 13:27
Show Gist options
  • Save tamizhgeek/2643840 to your computer and use it in GitHub Desktop.
Save tamizhgeek/2643840 to your computer and use it in GitHub Desktop.
Ruby snippets/tit bits which I find useful and don't wish to forget.
.present? is opposite of .blank? = Don't use ugly !blank?
xx
Missing attribute error occurs when you don't select a certain attr in SQL query but
try to use it in ActiveRecord.
xx
User Time.now.to_s(:db) while comparing datetime in mysql.
xx
FFS MySQL doesn't suppport DDL's inside transaction blocks so does rails.
So if you are doing any DDL operations in your code and want to test it,
the test cases would fail. Switch of the transactional_fixtures to avoid failures.
Here's how to you can do in rspec 1.3/rails 2.3.
Spec::Runner.configure do |c|
c.use_transactional_fixtures = false
end
Don't forget to manually cleanup the data after the tests.
xx
Ruby class names should be constants. Other's wont work!
But you can still create anonymous classes with assigning
a variable to Class.new
For ex,
a = Class.new do
def hi
p "hiiii"
end
end
a.new.hi
The above will print "hii". But unless you assign this anonymous thing
to a Ruby constant you can't use many Normal class functionalities.
xx
Dynamic finders in ActiveRecord return nil if no record is found.
Don't expect a empty array.
xx
Returning false in Observers don't abort the transaction of saving a object.
Only raising a exception does. Careful while using them. But callbacks
abort the transaction even when u return false.
xx
If you use ActiveRecord Objects in delayed_job you can use objects only which are already persisted and have a ID.
If you use transient objects you will get cryptic errors.
xx
Iterating on array/hash on console to print something - at the end of block ruby prints the whole array/hash - which will become a trouble when the array/hash is very big. Cause you can't see the actual print statements you have put because the screen will get rolled up. To avoid that add a semicolon and nil at the end of block. The output will be suppressed.
xxx
Don't use Time.now or Date.today in active record scopes - because the scope gets instantiated only once at the application startup so your Time.now is really pointless.
xxx
Instance variable should be declared within methods of a class. Not outside the methods. They have no effect.
xxx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment