Hi all,
I have some code where I’d like to set up an instance of a non-database
model from another, ActiveRecord, model in order to use some custom
methods on a string, without mixing extra methods into the String class.
I understand this might be less-than-sensible as models should normally
stand on their own…?
My two models:
#######################
models/qualified_name.rb
#######################
t.column :make, :text
t.column :model, :text
t.column :origin_country, :text
class QualifiedName < ActiveRecord::Base
Work some magic – let’s populate the instance using the raw name
string (e.g. “Honda Civic”)
def magically_understand(name_string)
raw_name = RawName.new(name_string)
if raw_name.is_one_word then
self.make = raw_name.contents
else
if raw_name.is_two_words then
self.make = raw_name.words.first
self.model = raw_name.words.last
end
end
if raw_name.make_could_be_japanese then
self.origin_country = "Japan"
end
return true
end
end
###################
models/raw_name.rb
###################
class RawName
def initialize(contents)
@contents = contents
@words = @contents.split(’ ')
end
def contents
@contents
end
Nice to be able to say raw_name.words.first
def words
@words
end
Is the string just one word long? Return boolean.
def is_one_word
@words.length == 1
end
Is the string two words long? Return boolean.
def is_two_words
@words.length == 2
end
Work out whether the first word (the make) ends in -a, -i or -u
def make_could_be_japanese
if @words.first.last(1) =~ /[aiu$]$/i : return true
else
return false
end
end
end
and so I want to be able to do the following kind of thing:
name = QualifiedName.new
=> #<QualifiedName:0x353df60 @new_record=true,
@attributes={“origin_country”=>nil, “make”=>nil, “model”=>nil}>
name.magically_understand(“Honda Civic”)
=> nil
name
=> #<QualifiedName:0x353df60 @new_record=true,
@attributes={“origin_country”=>“Japan”, “make”=>“Honda”,
“model”=>“Civic”}>
All this model code is of course very verbose, but it’s obviously just
an example. I know there are simpler ways to get this particular result,
but I want to be able to do more complex analyses of the ‘raw name’ and
populate the qualified name accordingly.
Is there a more maintanable structure I could be looking at? Should I
ditch the RawName model altogether and do everything within
QualifiedName - and if so how should I declare the helper methods like
make_could_be_japanese?
Thanks for any thoughts or inspiration!
Toby