Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
Ruby - How to create a class variables to access in function

I want to create a function to set the instance variable like attr_reader

class Base
    def exec
       # get all functions to check
       # if all functions return true
       # I will do something here
    end
end

And then I have a class inherit Base.

class SomeClass < Base
  check :check_1
  check :check_2

  def check_1
   # checking
  end

  def check_2
   # checking
  end
end

class Some2Class < Base
  check :check_3
  check :check_4
  
  def check_3
   # checking
  end

  def check_4
   # checking
  end
end

Because I only need 1 logic for executing in all classes but I have a lot the different checks for each class, I need to do it flexibly.

Please, give me a keyword for it.

Many thanks.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In order to have check :check_1 you need to define check as a class method:

class Base
  def self.check(name)
    # ...
  end
end

Since you want to call the passed method names later on, I'd store them in an array: (provided by another class method checks)

class Base
  def self.checks
    @checks ||= []
  end

  def self.check(name)
    checks << name
  end
end

This already gives you:

SomeClass.checks
#=> [:check_1, :check_2]

Some2Class.checks
#=> [:check_3, :check_4]

Now you can traverse this array from within exec and invoke each method via send. You can use all? to check whether all of them return a truthy result:

class Base
  # ...

  def exec
    if self.class.checks.all? { |name| send(name) }
      # do something
    end
  end
end

SomeClass.new.exec # doesn't do anything yet

The self.class part is needed because you are calling the class method checks from the instance method exec.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!