Last active
August 29, 2015 14:06
-
-
Save mlanett/fb0db463b7d5a8d14b94 to your computer and use it in GitHub Desktop.
Meta-programming for a fluent keyword.
This file contains 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
# Copyright (c) 2014 Mark Lanett. | |
# Permission is hereby granted, free of charge, to deal in this software without restriction of any sort. | |
module Fluent | |
def self.included(base) | |
base.extend(ClassSingletonMethods) | |
end | |
module ClassSingletonMethods | |
def fluent(name, default = nil) | |
ivar_ = ("@" + name.to_s).to_sym | |
name_ = name.to_sym | |
define_method(name_) do |*parameters| | |
if parameters.size == 0 | |
if instance_variable_defined?(ivar_) | |
instance_variable_get(ivar_) | |
else | |
value = default ? default.call : nil | |
instance_variable_set(ivar_, value) | |
value | |
end | |
else | |
instance_variable_set(ivar_, parameters.first) | |
self | |
end | |
end # define_method | |
end # fluent | |
end # ClassSingletonMethods | |
end # Fluent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment