Created
November 5, 2019 09:51
-
-
Save zoki/4e0ddfec82014e88ade0557d5ed8704a to your computer and use it in GitHub Desktop.
Use super with dynamically defined methods in ruby
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
| # frozen_string_literal: true | |
| # Use super with dynamically defined methods in ruby | |
| class Common | |
| class << self | |
| def attribute(*names) | |
| names.each do |name| | |
| define_method(name) do | |
| attributes[name.to_sym] | |
| end | |
| define_method("#{name}=") do |attribute| | |
| attributes[name.to_sym] = attribute | |
| end | |
| end | |
| end | |
| end | |
| attr_accessor :attributes | |
| def initialize | |
| @attributes = {} | |
| end | |
| end | |
| class Awesome | |
| class << self | |
| def attribute(*names) | |
| generated_attributes_names.module_eval do | |
| names.each do |name| | |
| define_method(name) do | |
| attributes[name.to_sym] | |
| end | |
| define_method("#{name}=") do |attribute| | |
| attributes[name.to_sym] = attribute | |
| end | |
| end | |
| end | |
| end | |
| private | |
| def generated_attributes_names | |
| @generated_attributes_names ||= Module.new.tap { |mod| include mod } | |
| end | |
| end | |
| attr_accessor :attributes | |
| def initialize | |
| @attributes = {} | |
| end | |
| end | |
| class CommonRecord < Common | |
| attribute :title, :desc | |
| def desc=(attribute) | |
| if defined?(super) | |
| super("The best #{attribute}!") | |
| else | |
| attributes[:desc] = "Just a #{attribute}" | |
| end | |
| end | |
| end | |
| class AwesomeRecord < Awesome | |
| attribute :title, :desc | |
| def desc=(attribute) | |
| if defined?(super) | |
| super("The best #{attribute}!") | |
| else | |
| attributes[:desc] = "Just a #{attribute}" | |
| end | |
| end | |
| end | |
| common_record = CommonRecord.new | |
| common_record.title = 'Nameless' | |
| common_record.desc = 'Company' | |
| puts "\n" | |
| puts 'CommonRecord' | |
| puts common_record.title | |
| puts common_record.desc | |
| awesome_record = AwesomeRecord.new | |
| awesome_record.title = 'Effectiva' | |
| awesome_record.desc = 'Company' | |
| puts "\n" | |
| puts 'AwesomeRecord' | |
| puts awesome_record.title | |
| puts awesome_record.desc | |
| # CommonRecord | |
| # Nameless | |
| # Just a Company | |
| # AwesomeRecord | |
| # Effectiva | |
| # The best Company! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment