Background...
I'm writing a parser that looks at strings and tries to determine what products they might contain. I've created my own Token
class to help.
class Token < ActiveRecord::BaseWithoutTable
attr_accessor :regex
attr_accessor :values
end
Example of a Token:
Token.new(:regex => /apple iphone 4/, :values => { :brand => "Apple", :product => "iPhone", :version => 4})
(where the hash keys all correspond to database columns in the products table.)
Here is the problem: In my Parser
, when a Token
is found, I attempt to add the associated values to a Product
instance, like so:
token.values.each do |v|
attrib, value = v[0], v[1]
my_product.instance_variable_set(:@attributes, { attrib.to_s => value })
end
This works except that it seems as if I have to set all my attributes at the same time. If I do it in stages (ie: as I discover new tokens), it overwrites any unspecified attributes with nil
. Am I missing something? Is there a better way to do this?