[prev in list] [next in list] [prev in thread] [next in thread]
List: ruby-talk
Subject: Re: Call for comments - Structure
From: Brian Candler <lists () ruby-forum ! com>
Date: 2012-04-29 10:08:20
Message-ID: d3db18afbcbe6524dde776d5478462b4 () ruby-forum ! com
[Download RAW message or body]
Hal Fulton wrote in post #1055190:
> What about the automated conversion of a hash to an object with
> accessors?
If the main driver is taking Hash-like data, depending on the
application it might be better to wrap the underlying Hash rather than
copy it into the instance variables of another object.
> Note that from_hash will handle one level and parse_hash will proceed
> recursively.
>
> Am I the only one who likes obj.foo.bar better than obj['foo']['bar'] ?
Oh, I do too. In fact, my main problem with OpenStruct is that it only
implements the first form and not the second. If it did both I'd be very
happy with it.
For an old project (couchtiny) I implemented the following:
# Extend a Hash with this module to get semantics of a Javascript
object:
# me.foo is the same as me['foo']
module JSObjectMixin
def method_missing(meth,*rest,&blk)
key = meth.to_s
if key[-1] == ?=
self[key[0..-2]] = rest.first
else
self[key]
end
end
end
# This class is like a Hash but with the semantics of a Javascript
object:
# me.foo is the same as me['foo']
class JSObject < Hash
include JSObjectMixin
end
Of course, if you are using the accessor methods a lot, this may be less
efficient than having defined accessor methods in the class pointing
directly at instance variables.
Aside: newer versions of the JSON library let you do this:
JSON.parse(src, :object_class => ::JSObject)
so that you get a tree of JSObjects instead of Hashes.
--
Posted via http://www.ruby-forum.com/.
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic