LoginSignup
1
1

More than 5 years have passed since last update.

Examples of Metaprogramming in Ruby

Last updated at Posted at 2013-02-10

Define a method if it's not already defined

Code could be found in the i18n gem.

https://github.com/svenfuchs/i18n/blob/master/lib/i18n/core_ext/hash.rb

class Hash

  

  def deep_merge!(data)
    merge!(data, &MERGER)
  end unless Hash.method_defined?(:deep_merge!)

  

end

By adding unless Hash.method_defined?(:deep_merge!) after the end of the method, Hash.deep_merge! will be defined if it's not already defined.
This prevents monkey patch.
In Rails, active_support also defines Hash.deep_merge!. So i18n doesn't override that method.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1