Home > database >  Ruby - How to create a class variables to access in function
Ruby - How to create a class variables to access in function

Time:12-08

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.

CodePudding user response:

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.

  • Related