Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Can I use instance methods inside a class method?

I have a class that contains this class method:

def self.get_event_record(row, participant)
  event = Event.where(
      :participant_id   => participant.id,
      :event_type_code  => row[:event_type],
      :event_start_date => self.format_date(row[:event_start_date])
  ).first

  event = Event.new(
      :participant_id   => participant.id,
      :event_type_code  => row[:event_type],
      :event_start_date => self.format_date(row[:event_start_date])
  ) if event.blank?

  event
end

And I also have, in the same class, an instance method:

def format_date(date)
  parsed_date = date.split('/')

  # if month or day are single digit, make them double digit with a leading zero
  if parsed_date[0].split("").size == 1
    parsed_date[0].insert(0, '0')
  end
  if parsed_date[1].split("").size == 1
    parsed_date[1].insert(0, '0')
  end

  parsed_date[2].insert(0, '20')

  formatted_date = parsed_date.rotate(-1).join("-")
  formatted_date
end

I'm getting an 'undefined method' error for #format_date. (I tried it without the self in front, at first). Can you not use instance methods in class methods of the same class?

like image 494
steve_gallagher Avatar asked Jun 28 '12 13:06

steve_gallagher


2 Answers

Short answer is no, you cannot use instance methods of a class inside a class method unless you have something like:

class A
  def instance_method
    # do stuff
  end

  def self.class_method
     a = A.new
     a.instance_method
  end
end

But as far as I can see, format_date does not have to be an instance method. So write format_date like

def self.format_date(date)
   # do stuff
end
like image 64
tdgs Avatar answered Oct 02 '22 16:10

tdgs


Just create class method

def self.format_date (..)
  ...
end

And if u need instance method, delegate it to class method

def format_date *args
  self.class.format_date *args
end

And i don't think that it is good idea to call instance methods from class scope

like image 41
Yuri Barbashov Avatar answered Oct 02 '22 17:10

Yuri Barbashov