Created
January 22, 2020 12:30
-
-
Save rickychilcott/557a99511e401153fb7cf5f53c12bb58 to your computer and use it in GitHub Desktop.
Create a dynamic module
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
# Requires Ruby 2.7.0 | |
class Positional < Module | |
# def self.[](position:) | |
# new(position: position) | |
# end | |
def self.[](...) | |
new(...) | |
end | |
# def self.call(position:) | |
# new(position: position) | |
# end | |
def self.call(...) | |
new(...) | |
end | |
def initialize(position:) | |
raise RuntimeError, "provide block for Positional module" unless position && position.is_a?(Proc) | |
define_method :position, &position | |
end | |
end | |
class TestPositionalClass | |
include Positional[position: -> { value * 1000 }] | |
# include Positional.(position: -> { value * 1000 }) | |
# include Positional.new(position: -> { value * 1000 }) | |
def initialize(value:) | |
@value = value | |
end | |
def calculate | |
instance_eval &:position | |
end | |
private | |
attr_reader :value | |
end | |
t = TestPositionalClass.new(value: 1) | |
puts t.calculate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment