Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

def block in rake task

I got undefined local variable or method 'address_geo' for main:Object with the following rake task. What's the problem with it?

include Geokit::Geocoders  namespace :geocode do   desc "Geocode to get latitude, longitude and address"   task :all => :environment do     @spot = Spot.find(:first)     if @spot.latitude.blank? && [email protected]?       puts address_geo     end      def address_geo       arr = []       arr << address if @spot.address       arr << city if @spot.city       arr << country if @spot.country       arr.reject{|y|y==""}.join(", ")     end   end end 
like image 617
Victor Avatar asked Sep 04 '11 08:09

Victor


People also ask

How do you define a Rake task?

Rake enables you to define a set of tasks and the dependencies between them in a file, and then have the right thing happen when you run any given task. The combination of convenience and flexibility that Rake provides has made it the standard method of job automation for Ruby projects.

What is environment Rake task?

Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment , you won't have access to any of those extras.

What is Rakefile in Ruby?

Rake is a tool you can use with Ruby projects. It allows you to use ruby code to define "tasks" that can be run in the command line. Rake can be downloaded and included in ruby projects as a ruby gem. Once installed, you define tasks in a file named "Rakefile" that you add to your project.


1 Answers

Update: Gotcha

This potentially adds the method to global scope and will conflict with any other method with the same name. Look at @Hula_Zell's answer https://stackoverflow.com/a/44294243/584440 for a better way.

Original answer

You are defining the method inside the rake task. For getting the function, you should define outside the rake task (outside the task block). Try this:

include Geokit::Geocoders  namespace :geocode do   desc "Geocode to get latitude, longitude and address"   task :all => :environment do     @spot = Spot.find(:first)     if @spot.latitude.blank? && [email protected]?       puts address_geo     end   end    def address_geo     arr = []     arr << address if @spot.address     arr << city if @spot.city     arr << country if @spot.country     arr.reject{|y|y==""}.join(", ")   end end 
like image 58
rubyprince Avatar answered Oct 11 '22 07:10

rubyprince