1

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

tks @stefan. I found what I want. I used class_variables for this
@tai.groddy note that a class variable (with @@) is shared between the class and its subclasses. You probably want to have a class instance variable (with @ as shown above) so each subclass can have its own array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.