Created
April 8, 2018 19:51
-
-
Save Masa331/b9c31d34da9caa3c29e83b68c752b789 to your computer and use it in GitHub Desktop.
How to call a same method from all included modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module ColorParser | |
| def parse | |
| source.select { |k, _| k == :color } | |
| end | |
| end | |
| module BrandParser | |
| def parse | |
| source.select { |k, _| k == :brand } | |
| end | |
| end | |
| module Mega | |
| def mega | |
| called_from = caller_locations[0].label | |
| included_modules = (self.class.included_modules - Class.included_modules - [Mega]) | |
| included_modules.map { |m| m.instance_method(called_from).bind(self).call } | |
| end | |
| end | |
| class CarParser | |
| include ColorParser | |
| include BrandParser | |
| include Mega | |
| attr_reader :source | |
| def initialize(source) | |
| @source = source | |
| end | |
| def parse | |
| res = mega | |
| res.inject(source.select { |k, _| k == :owner }) { |memo, r| memo.merge r } | |
| end | |
| end | |
| car = CarParser.new({ color: 'green', brand: 'Ford', no_of_seats: '2', owner: 'Mr. Smith', mileage: 45_000 }) | |
| puts car.parse |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment