Wednesday, May 29, 2013

ruby: skipping elements in iteration cycle

Lets we have this situation:

[7, 2, 3, "a", "b", "c"].sort
ArgumentError: comparison of Fixnum with String failed
from (irb):1:in `sort'
from (irb):1


We want to sort only integer values.

The solution is using reject statement:

[7, 2, 3, "a", "b", "c"].reject{ |x| x.to_i == 0 }.sort
 => [2, 3, 7]

Sunday, May 26, 2013

respond_to? and global methods in Ruby

Lets have an method defined outside of any class:
def my_method 
    "my Method is executed" 
end 


Checking its persistence with respond_to? seems wrong:
respond_to? :my_method => false

The solution to that issue is that the syntax of respond_to? for global methods is different (and absolutely no logical to me). Global methods are presented as private methods of Object class. So the correct verification is:

Object.respond_to?( :my_method, true )




Monday, May 20, 2013

'resque <Exception>' syntax not working in ruby - solved

ensure keyword does, but resque not.

The solution: The correct keyword is rescue not resque. In this case the exception is thrown before go through  the "undefined method" resque.

Monday, May 13, 2013

Java application as a daemon - initd start/stop template file

Your Java application is a daemon and you want to stop it more gracefully than "killall java".

The example below is what you need:

#!/bin/sh
#
# init script for a Java application
#

# Check the application status
#
# This function checks if the application is running
check_status() {

  # Running ps with some arguments to check if the PID exists
  # -C : specifies the command name
  # -o : determines how columns must be displayed
  # h : hides the data header
  s=`ps -C 'java -jar /path/to/application.jar' -o pid h`

  # If somethig was returned by the ps command, this function returns the PID
  if [ $s ] ; then
    return $s
  fi

  # In any another case, return 0
  return 0

}

# Starts the application
start() {