Hashblock (tentative name) is a simple gem that converts free form blocks into hashes.
Here’s how to use it
-> parser = Hashblock::Parser.new
=> #<Hashblock::Parser ...>
-> to_parse = Proc.new do
foo :bar
ping :pong
nest_this do
abra :cadabra
end
end
=> #<Proc:...>
-> parser.parse(to_parse)
=> {:foo=>:bar, :ping=>:pong, :nest_this=>{:abra=>:cadabra}}
This may be useful if you’re creating an acts_as_* type plugin, for example. Say you want your users to invoke your plugin thusly:
acts_as_whizbang do
config do
whiz :bang
end
other_config :foo
end
Youll want to handle that like this:
def acts_as_whizbang(&block)
@config = Hashblock::Parser.new.parse(block)
end
Now, suppose you want the user to also be able to supply options via a Hash:
def acts_as_whizbang(hash, &block)
if block_given?
@config = Hashblock::Parser.new.parse(block)
else
@config = hash
end
end
This allows users of your plugin to configure acts_as_whizbang via a hash, too:
acts_as_whizbang :config => { :whiz => :bang }, :other_config => :foo