Wednesday, April 14, 2010

blank? Is All You Need


if data.nil? || data.blank?
  inform_user
end
I've seen the above code often enough lately that I thought a brief post was in order to inform/remind folks that blank? is all you need. Here's a script/console session proving just that.

$ script/console
Loading development environment (Rails 2.3.5)
>> data = nil
=> nil
>> data.nil?
=> true
>> data.blank?
=> true
Thus, we can eliminate the first half of the conditional expression.

if data.blank?
  inform_user
end
Now, if you find you want to check !blank? but you prefer to express your conditional checks positively instead of negatively, you can use present?.

if !data.blank?
  show_it
end
becomes

if data.present?
  show_it
end
Using blank? and present? enables clearer and more concise conditionals, a benefit not only now but every time someone reads the code.

Tuesday, April 13, 2010

Using script/console with jruby-complete

On my current project, we're trying jruby-complete 1.4.0 in development. I'm new to JRuby. The one thing I haven't liked so far was that I couldn't figure out how to use script/console. What I expected to work didn't:

$ java -Xmx500m -Xss1024k -jar path/to/jruby-complete-1.4.0.jar -S script/console
Loading development environment (Rails 2.3.5)
Error opening script file: /Users/cdemyanovich/work/my_project/file:/path/to/jruby-complete-1.4.0.jar!/META-INF/jruby.home/bin/jirb (No such file or directory)
Searching Google by several different combinations of terms from my error message proved fruitless. I joined the #jrubyonrails IRC channel on freenode, greeted everyone, asked my question and received an answer from nicksieger in minutes.

$ java -Xmx500m -Xss1024k -jar path/to/jruby-complete-1.4.0.jar -S irb
irb(main):001:0> require 'config/environment'
JRuby limited openssl loaded. gem install jruby-openssl for full support.
http://jruby.kenai.com/pages/JRuby_Builtin_OpenSSL
=> true
irb(main):002:0> User.count
=> 1
irb(main):003:0> 
I'm happy to have this oft-used tool working again. If you have any other problems with JRuby, you'll find friendly experts ready, willing and able to help in the #jruby and #jrubyonrails channels on freenode.