From: Robert Klemme Date: 2010-05-16T18:25:12+09:00 Subject: Re: class best way for getters ? On 16.05.2010 09:25, Une Bévue wrote: > Une Bévue wrote: > >> Then, I'll have a look on Struct. > > i had a first look and i wonder how to use it in order to get a new > class "HFSFile" which can be used such a way, using OpenStruct : > > hfsf = HFSFile.new(a_path) > p hfsf.path > p hfsf.modification_date > ... > > because i do : > > class HFSFile > def initialize(a_path) > @attr = {} > @attr[:path] = a_path > @attr[:modification_date] = ... > ... > @data = OpenStruct.new(@attr) > end > def attributes > return @attr > end > def data > return @data > end > end > > what is ennoying me in that case is in that i do have to use : > hfsf = HFSFile.new(a_path) > p hfsf.data.path > p hfsf.data.modification_date > ------^^^^^^----------------- > ... > where i would prefer having self being an OpenStruct (extension ?) but i > think i can't do : > self = OpenStruct.new(@attr) > > ??? There is no need for delegation here: you only need one instance and the way through Hash or OpenStruct seems a detour here - at least if the set of fields is fixed. Then you can do HFSFile = Struct.new :name, :modification_date do def self.parse(s) o = new s.scan /\s*([\w\s]+):\s*([^,]+),?/ do field = normalize($1) val = $2.strip o[field] = val end o end def self.normalize(k) k.strip.gsub /\s+/, '_' end end Now you can do: irb(main):033:0> HFSFile.parse "name: the_name_value, modification date: the date" => # irb(main):034:0> You'll get a NameError if you parse fields from the String that are not present in the struct. If you need to cope with additional fields you need to either ignore them or store them in an additional Hash member. You can use HFSFile.members (or just members in method parse()) to test for field presence. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/