Skip to content

Instantly share code, notes, and snippets.

@mlanett
Last active August 29, 2015 14:06
Show Gist options
  • Save mlanett/fb0db463b7d5a8d14b94 to your computer and use it in GitHub Desktop.
Save mlanett/fb0db463b7d5a8d14b94 to your computer and use it in GitHub Desktop.
Meta-programming for a fluent keyword.
# 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