Showing posts with label invoke. Show all posts
Showing posts with label invoke. Show all posts

Wednesday, November 30, 2011

How to invoke method in ruby?

Guys,
         Do you aware about the method invocation in ruby using different ways?
 want to know? There are 3 different ways to invoke a method in ruby.

a) Using period operator
    eg. we have class called 'Car' and we need to access the method called 'car_detail'
    car = Car.new
    car.car_detail

b) Using .send method
    car = Car.new
    car.send(:car_detail)

c) Using .call method
    car = Car.new
    car.method(:car_detail).call

So, these are the three ways to invoke method in ruby.  Hope this post will help you.

Thursday, August 18, 2011

Run rake task in background

Hey rubies,
                Some time we need immediate response at that time we have option to run functionality in background by invoking rake task.

Here is the small example

Assume we have task called 'generate_random_number' which we need to invoke in background. below is the steps for that.

Invoke the background task by

call_rake 'generate_random_number', {:initial => 10}

definition for call_rake

def call_rake(task, options = {})   
    # define rails environment as option etc...
    options[:rails_env] ||= RAILS_ENV
    # collect argument list
    args = options.map { |n, v| "#{n.to_s.upcase}='#{v}'" }         
    # invoke task from rails and generate log
    system "rake #{task} #{args.join(' ')} --trace 2>&1 >> #{RAILS_ROOT}/rake.log &"   
  end

Here is the task definition.
desc "Generate Random Number"
task :generate_random_number, [:initial] => :environment do |t, args|
    puts "here is your random number " + rand(args[:initial] ).to_s
end

This the way how task execute in background. If you have any query or suggestion then post the comment.