Skip to content

Instantly share code, notes, and snippets.

@rickychilcott
Created January 22, 2020 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickychilcott/557a99511e401153fb7cf5f53c12bb58 to your computer and use it in GitHub Desktop.
Save rickychilcott/557a99511e401153fb7cf5f53c12bb58 to your computer and use it in GitHub Desktop.
Create a dynamic module
# 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