Module: MethodFallback::ClassMethods

Defined in:
lib/method_fallback.rb

Overview

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#fallback(*attribute_names, to:, **aliased_attributes) ⇒ Object

Define fallbacks

Examples:

class Author
  def name
    'Jane Doe'
  end
end

class Article
  include MethodFallback

  def author
    Author.new
  end

  def author_name
    nil
  end

  fallback author_name: :name, to: :author
end

Parameters:

  • attribute_names (Array<String, Symbol>)
  • to: (String, Symbol)
  • aliased_attribtutes (Hash{String, Symbol => String, Symbol})

Since:

  • 0.1.0



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/method_fallback.rb', line 40

def fallback(*attribute_names, to:, **aliased_attributes)
  aliased_attributes = attribute_names
    .reduce({}) do |memo, attribute_name|
      memo[attribute_name] = attribute_name; memo
    end
    .merge!(aliased_attributes)

  aliased_attributes.keys.each do |name|
    alias_method "#{name}_without_fallback", name
  end

  mod = Module.new do
    aliased_attributes.each do |name, aka|
      define_method(name) do |*args, &block|
        value = super(*args, &block)

        if value.nil?
          send(to)&.send(aka, *args, &block)
        else
          value
        end
      end
    end
  end

  prepend mod
end