Overwrite similar methods, shorter syntax

In the Ruby class, I overwrite the three methods, and in each method I basically do the same thing:

class ExampleClass

  def confirmation_required?
    is_allowed && super
  end

  def postpone_email_change?
    is_allowed && super
  end

  def reconfirmation_required?
    is_allowed && super
  end

end

Is there a more compact syntax? How can I shorten the code?

+4
source share
3 answers

How to use an alias?

class ExampleClass

  def confirmation_required?
    is_allowed && super
  end

  alias postpone_email_change? confirmation_required?
  alias reconfirmation_required? confirmation_required?
end
+8
source
class ExampleClass
  %i|confirmation_required?
     postpone_email_change?
     reconfirmation_required?|.each do |m|

    define_method m do |*args, &cb|
      is_allowed && super(*args, &cb)
    end
  end
end

Note. %i|symbol1 symbol2|- shortcut for [:symbol1, :symbol2]is ruby โ€‹โ€‹2.0+ syntax for creating a list of characters from words.

+1
source

The approach eval. Code smell is considered, but in this case it has better readability. It is also easier to understand for less experienced people on your team.

class ExampleClass
  WRAPPED_METHODS = %i(
    confirmation_required?
    postpone_email_change?
    reconfirmation_required?
  )

  WRAPPED_METHODS.each do |method_name|
    class_eval("
      def #{method_name}
        is_allowed && super
      end
    ")
  end
end
0
source

Source: https://habr.com/ru/post/1667385/


All Articles