From: ara howard Date: 2008-01-09T14:08:55+09:00 Subject: Re: struct equivalent with rails-y keyword args hash? On Jan 8, 2008, at 10:02 PM, Giles Bowkett wrote: > Anyway, is there an easy equivalent to Struct which, instead of taking > stuff in sequence, takes a Hash of options, in a Rails-y style? Like a > HashStruct? Does Facets have such a thing, maybe haps? If not, is the > basic code for Struct in Ruby, and/or is a class like Struct but with > Hashes easy to build? i use this alot in rails projects: require 'attributes' class OpenObject alias_method "__inspect__", "inspect" alias_method "__to_s__", "to_s" alias_method "__instance_eval__", "instance_eval" instance_methods.each{|m| undef_method m unless m[%r/__/]} alias_method "instance_eval", "__instance_eval__" alias_method "inspect", "__inspect__" alias_method "to_s", "__to_s__" def method_missing m, *a, &b super if(a.empty? and b.nil?) m = m.to_s setter = m.delete!('=') || a.first || b if setter if a.empty? __attribute__ m, &b else __attribute__ m => a.shift end else nil end end def configure kvs = {}, &b kvs.each{|k,v| __attribute__ k => v} __instance_eval__ &b if b end alias_method "initialize", "configure" alias_method "eval", "configure" def __singleton_class__ &b sc = class << self self end b ? sc.module_eval(&b) : sc end def extend *a, &b if b __singleton_class__ &b self else super end end alias_method "extending", "extend" def attributes *a, &b __attributes__ *a, &b end def to_hash __attributes__.inject(Hash.new){|h,a| h.update a => __send__(a)} end def as_query require 'cgi' e = lambda{|x| CGI.escape x.to_s} to_hash.map{|k,v| "#{ e[k] }=#{ e[v] }"}.join("&") end def respond_to? *a, &b true end end def openobject(*a, &b) OpenObject.new(*a, &b) end class Object def Open *a, &b OpenObject.new(*a, &b) end end it's all that and so much more. a @ http://codeforpeople.com/ -- share your knowledge. it's a way to achieve immortality. h.h. the 14th dalai lama