Skip to content

Instantly share code, notes, and snippets.

@zoki
Created November 5, 2019 09:51
Show Gist options
  • Save zoki/4e0ddfec82014e88ade0557d5ed8704a to your computer and use it in GitHub Desktop.
Save zoki/4e0ddfec82014e88ade0557d5ed8704a to your computer and use it in GitHub Desktop.
Use super with dynamically defined methods in ruby
# 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