Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method inside a class method in Ruby

Tags:

ruby

I have a question.

This is my class:

class Provider
  include HTTParty
  CONFIG = Rails.configuration.mediaset[Rails.env]

  def self.category
    response = HTTParty.get(CONFIG['category_url'])
    category_hash = JSON.parse response.body
    if category_hash['resultCode'] == 'OK' 
      return convert_categories(category_hash)
    end
  end

  def convert_categories(cat_hash)
    h = cat_hash.find_all_values_for('categoryList')
    category_array = h.map { |c| c.except!('categoryList') }
  end
end

When I try to call 'Provider.category' the result is:

undefined method `convert_categories' for Provider:Class

How can I add a function to process my hash?

like image 414
Roberto Pezzali Avatar asked Sep 13 '26 15:09

Roberto Pezzali


1 Answers

As has been suggested, just make your "simple function" a class method as well...

  def self.convert_categories(cat_hash)
    h = cat_hash.find_all_values_for('categoryList')
    h.map { |c| c.except!('categoryList') }
    return h
  end

do that, and the code will work.

Without the self. the method is an instance method and can only be called on an object of the Provider class.

Although admittedly the h.map... line is pointless. The result isn't saved anywhere, you're still returning the original h object.

like image 120
SteveTurczyn Avatar answered Sep 15 '26 11:09

SteveTurczyn