Created
October 8, 2009 19:21
-
-
Save reinh/205283 to your computer and use it in GitHub Desktop.
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
module Factor | |
def self.add(name, &block) | |
Factor::Resolvers.add(name, block) | |
end | |
# Facts are provided by returning immediate values and lazily | |
# evaluating value strategy objects (things that respond to #call, like | |
# simple Procs) | |
def self.value(name) | |
value = Factor::Resolvers[name] | |
value = value.call while value.respond_to?(:call) | |
end | |
end | |
module Factor::Resolvers | |
# resolver table | |
RESOLVERS = {} | |
def self.[](key); RESOLVERS[key] end | |
def self.add(name, block) | |
RESOLVERS[name] = instance_eval(block) | |
end | |
private | |
def self.exec(command, &block) | |
block.call(`#{command}`) | |
end | |
# Lazy is used here to wrap an (imaginary) Windows Registry class with the necessary #call | |
# interface. | |
def self.registry(key) | |
lazy { Factor::Platform::Windows::RegistryService.new(key).value } | |
end | |
def self.command(&block) | |
block | |
end | |
def self.extract(regexp, options) | |
exec(options[:from]){|output| output[regexp]} | |
end | |
def self.setcode(str=nil, &block) | |
str ? exec(str) : block | |
end | |
# Provides lazy evaluation of a fact | |
def lazy(&block); block end | |
end | |
# Example: | |
Factor.add(:hostname) do | |
setcode do | |
hostname = nil | |
name = Factor::Util::Resolution.exec('hostname') or nil | |
if name | |
if name =~ /^([\w-]+)\.(.+)$/ | |
hostname = $1 | |
# the Domain class uses this | |
$domain = $2 | |
else | |
hostname = name | |
end | |
hostname | |
else | |
nil | |
end | |
end | |
# becomes | |
exec('hostname') do |name| | |
name[/^([\w-]+)\.?/] | |
end | |
# becomes | |
extract /^([\w-]+)\.?/, :from => 'hostname' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment