I have a command line shell that I plan to run over and over again.
It’s base functionality is to accept a list of files names and a file
name containing the logic to be applied to the contents of said files.
My shell script contains the logic for accepting the shell commmands
and list of files. However, I am unable to figure out how to accept a
simple block of logic from a separate file and use it as a method
within the shell. An example of the type of logic would be:
Find parm arg that follows equal sign and upper case it.
If the arg contains D:, then change to E:\ if it is
not a “Work File Directory” parm.
def updatevalue(rec) # rec is the record to update
i = nil # create i
i = parm.index(’=’)+1 if parm =~ /^[*\s]|^(BEGIN|END)/
if i # If i has a value
j = rec.length-i # determine length of value
rec[i,j] = rec[i,j].upcase # upper case that portion of text
i = rec.index(‘D:\’) # Does arg contain D:?
rec = rec[0,i]+‘E:’+rec[i+3,rec.length-i] if i && (rec !~ /^Work
File Directory/)
end
rec
end
class StuffType < ActiveRecord::Base
has_many :Stuff
end
class Stuff < ActiveRecord::Base
set_table_name “stuff”
belongs_to :StuffType
def initialize
StuffType.find_all.each do |typ|
class_eval %(#{typ.name} = #{typ.id})
end
end
end
StuffType is a DB table with two columns, name, and id. E.g. 1 = small,
2 = medium, 3 = large.
I want to use it to create an enum for my Stuff class.
Stuff is another DB table with, among other things, a stuff_type_id
column identifying what type it is.
Unfortunately when I plug this code into irb and type something like
Stuff::small, expecting to get 1 returned, I get undefined method
`small’ for Stuff:Class. What am I doing wrong? Is there a better way
to do what I want?
class Stuff < ActiveRecord::Base
set_table_name “stuff”
belongs_to :StuffType
def initialize
StuffType.find_all.each do |typ|
class_eval %(#{typ.name} = #{typ.id})
end
end
end
When you create a new Stuff record you aren’t guaranteed it has an id,
ie, has it been saved to the database or not? Also,
ActiveRecord doesn’t create new records (when finding records from the
database) using the “new” method, so “initialize” never
gets it.
When do you want your “enum” like behavior to be created, after
creation, after update, after find, when the class lods?
Also, do you want the relationship to StuffType to be an the instance
level or at the class.
ie, do you want to say:
stuff = Stuff.find( 1 )
stuff.small # assume small is one of your fields in stuff_types
or do you want to say:
Stuff.small #assume small is one of your fields in stuff_types