Skip to content

Instantly share code, notes, and snippets.

@alandipert
Created May 4, 2012 23:44
Show Gist options
  • Save alandipert/2598465 to your computer and use it in GitHub Desktop.
Save alandipert/2598465 to your computer and use it in GitHub Desktop.
A different way to organize Ruby code
class Ns
def initialize
use.each do |pkg, method_names|
method_names.each do |name|
self.class.send(:define_method, name) do |*args|
pkg.method(name).call(*args)
end
end
end
end
end
module Math
def self.dec(n) n - 1; end
def self.inc(n) n + 1; end
end
module Cows
def self.meh_cow; "Moo." end
def self.angry_cow
[meh_cow.slice(0..-2)].
cycle.
take(3).
zip(["! "].cycle).
flatten.
join.
slice(0..-2)
end
end
# Meanwhile, back at the farm:
class Main < Ns
def use
{Math => [:inc],
Cows => [:meh_cow, :angry_cow]}
end
def main
puts "The meh cow says '#{meh_cow}', the angry cow says '#{angry_cow}', and 1+1 is #{inc 1}!"
end
end
Main.new.main
@alandipert
Copy link
Author

I rolled this into a gem that includes the ability to import methods into blocks: https://github.com/alandipert/rns

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment