Module: GosuWrapper::Util
- Included in:
- GosuWrapper
- Defined in:
- lib/gosu_wrapper/util.rb
Instance Method Summary collapse
Instance Method Details
#method_missing_for(regex, type:, &definition_blk) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/gosu_wrapper/util.rb', line 5 def method_missing_for(regex, type:, &definition_blk) # Regex should include a match group # type should be either :instance or :class # Definition blk is run unless there's an existing method with the same name. # if caller_blk is provided, it will be passed to definition_blk's invocation # # Example: # # class Animal # extend Util # attr_reader :noises # def initialize # @noises = { cat: "meow" } # end # method_missing_for /^(.+)_goes$/ do |match, arg| # puts @noises[match] # end # end # # Animal.new.cat_goes # => "meow" # # Through the use of an anonymous modules (adding method_missing to the # inheritance chain vs overwriting it with define_method), this can be # used multiple times. # anon_module = Module.new do |mod| define_method(:method_missing) do |name, *args, **keywords, &caller_blk| match = name.to_s.scan(regex).flatten[0] if match if respond_to?(name) send(name, *args, &caller_blk) else if type == :instance instance_eval &( definition_blk.call(match, *args, **keywords, &caller_blk) ) elsif type == :class singleton_class.class_exec &( definition_blk.call(match, *args, **keywords, &caller_blk) ) end end else super(name, *args, **keywords, &caller_blk) end end end base = case type when :instance self when :class self.singleton_class end base.prepend anon_module end |