I have a methods that converts all DB rows into structs using Struct
class.
–
Dossy Shiobara mail: dossy@panoptic.com
Panoptic Computer Network web: http://www.panoptic.com/
“He realized the fastest way to change is to laugh at your own
folly – then you can let go and quickly move on.” (p. 70)
I have a methods that converts all DB rows into structs using Struct
class. First version was:
res - result objects from DB connector
def create_structs( res )
row_class = Struct.new( ‘SQLRow’, *res.names )
data =
res.each do |row|
data << row_class.new( row )
end
data
end
(…)
it is due to redefinition of Struct::SQLRow methods
I would like to rewrite method create_structs to avoid this problem.
If you pass a name as the first parameter to Struct.new, those
names have to be unique. You can solve your problem by passing
nil as the first argument to Struct.new:
row_class = Struct.new( nil, *res.names )
I suppose you don’t refer to the name “SQLRow” anywhere else in
your program, do you?
Is there any advantage to having it be a Struct instead of an
Array of Hash’es?
I think there is no advantage, but I really like this syntax:
people.each { |man| puts “#{man.name} #{man.surname}” }
This one is not so nice, isn’t it?
people.each { |man| puts “#{man[‘name’]} #{man[‘surname’]}” }
Is there any advantage to having it be a Struct instead of an
Array of Hash’es?
I think there is no advantage, but I really like this syntax:
people.each { |man| puts “#{man.name} #{man.surname}” }
This one is not so nice, isn’t it?
people.each { |man| puts “#{man[‘name’]} #{man[‘surname’]}” }
–
Dossy Shiobara mail: dossy@panoptic.com
Panoptic Computer Network web: http://www.panoptic.com/
“He realized the fastest way to change is to laugh at your own
folly – then you can let go and quickly move on.” (p. 70)
Is there any advantage to having it be a Struct instead of an
Array of Hash’es?
I think there is no advantage, but I really like this syntax:
people.each { |man| puts “#{man.name} #{man.surname}” }
This one is not so nice, isn’t it?
people.each { |man| puts “#{man[‘name’]} #{man[‘surname’]}” }
class Hash
def method_missing(*args)
self[args[0].to_s]
end
end
You can easily misspell method name (man.sername) with method_missing
and will not notice this. In this case better way to use structs as
for me.
You can easily misspell method name (man.sername) with method_missing
and will not notice this. In this case better way to use structs as
for me.
Well, in this case you can use anonymous struct
row_class = Struct.new(nil, *res.names)
ruby will create a new class for each call, or if you want named struct,
something like this (not tested)
@structname = 'SQLRow00'
def find_struct(*names)
ObjectSpace.each_object(Class) do |x|
if x < Struct && /SQLRow\d\d\Z/ =~ x.to_s && x.members == names
return x
end
end
Struct.new(@structname.succ!, *names)
end
def create_struct(res)
row_class = find_struct(*res.names)
# ...
end