On 16.05.2010 09:25, Une B=E9vue wrote:
> Une B=E9vue<unbewusst.sein / google.com.invalid>  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 =3D HFSFile.new(a_path)
> p hfsf.path
> p hfsf.modification_date
> ...
>
> because i do :
>
> class HFSFile
>    def initialize(a_path)
>      @attr =3D {}
>      @attr[:path] =3D a_path
>      @attr[:modification_date] =3D ...
>      ...
>      @data =3D 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 =3D 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 =3D 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 =3D Struct.new :name, :modification_date do
   def self.parse(s)
     o =3D new
     s.scan /\s*([\w\s]+):\s*([^,]+),?/ do
       field =3D normalize($1)
       val =3D $2.strip
       o[field] =3D 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"
=3D> #<struct HFSFile name=3D"the_name_value", modification_date=3D"the d=
ate">
irb(main):034:0>

You'll get a NameError if you parse fields from the String that are not=20
present in the struct.  If you need to cope with additional fields you=20
need to either ignore them or store them in an additional Hash member.=20
You can use HFSFile.members (or just members in method parse()) to test=20
for field presence.

Kind regards

	robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/