The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Block to Hash Conversion for Ruby Config Blocks

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Gabriel Horner

Posts: 62
Nickname: cldwaker
Registered: Feb, 2009

Gabriel Horner is an independent consultant who can't get enough of Ruby
Block to Hash Conversion for Ruby Config Blocks Posted: Feb 16, 2009 4:55 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Gabriel Horner.
Original Post: Block to Hash Conversion for Ruby Config Blocks
Feed Title: Tagaholic
Feed URL: http://feeds2.feedburner.com/tagaholic
Feed Description: My ruby/rails/knowledge management thoughts
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Gabriel Horner
Latest Posts From Tagaholic

Advertisement

While I was busy scratching an irb itch, I came up with a handy technique for converting a method’s block definition into a hash. Here’s an example of using such a method:

  Alias.init do |a|
    a.verbose = true
    a.constant = {'Array' = 'A'}
    a.instance_method = {'String'=>{'downcase'=>'dc' },'Array'=>{'select'=>'s'}}
  end

What I wanted was a quick but clean way to convert the data structure described in the method’s block to a hash. So knowing about OpenStruct, I peered into its internals and saw that it stores its attributes as a hash in @table. Since there isn't a public method for @table, I realized I was going to have to use instance_variable_get(:@table). Now if I only wanted to be quick, I could simply have used that. But wanting code clarity (ie not have to read OpenStruct’s internal variables each time) and to avoid monkeypatching (I have been bitten), I came up with:

Using it is simple. Pass your method’s block to ConfigStruct.block_to_hash() and you’ll get back a hash with whatever was defined in the block:

  def init(*args, &block)
    config = ConfigStruct.block_to_hash(block)
    #process your config ...
  end
     
  init do |c|
    c.some = "config"
    c.info = "goes here"
  end
  # In init(), config = {:some=>'config', :info=>'goes here'}

If you decide to not pass your method a block? No worries. You get back an empty hash. To see this idea in my ruby gem, see here.

Read: Block to Hash Conversion for Ruby Config Blocks

Topic: On shells Previous Topic   Next Topic Topic: New Ruby Blog

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use