Module: Common

Includes:
ColumnGroup, GenericGrep, GenericTableHtml
Defined in:
app/models/no_db.rb,
app/models/generic_table.rb

Overview

module ActiveRecord

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Methods included from GenericTableHtml

#column_html, #rails_route, #row_html

Class Method Details

.db2yamlObject

def


325
326
327
328
329
330
# File 'app/models/no_db.rb', line 325

def self.db2yaml
	skip_tables = ["schema_info","tedprimaries","weathers"]
  (	ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
		table2yaml(table_name)
	end #each
end

Instance Method Details

#acquireObject

method monitor


130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'app/models/no_db.rb', line 130

def acquire
	@acqClasses=Generic_Acquisitions.parse_classes(m)
	@acqClasses.map do |ac|
		@acquisitionData=acquire
	end #map
	@acquisitionData.each do |ad|
		if acquisitionUpdated?(ad) then
			row=self.create
			row=process(ad)
			row.printLog
		else
			puts ad
		end
	end
end

#adaptiveAcquisitionObject


174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'app/models/no_db.rb', line 174

def adaptiveAcquisition
	notModifieds=0
	done=false
	begin
		@acquisitionData=acquire 
		if acquisitionsUpdated? then
			done=true
		else
			notModifieds=notModifieds+1
			if notModifieds.modulo(10)==0 then
#				Global::log.info("notModifieds=#{notModifieds}")
#				Global::log.info("@acquisitionData=#{@acquisitionData}")
			else
#				Global::log.info("not updated")	
			end
		end	
		#sleep self[:interval]
		wait
	end until done
#	Global::log.info("notModifieds=#{notModifieds}")
	return @acquisitionData
end

#addColumn(name, type) ⇒ Object


242
243
244
245
246
# File 'app/models/no_db.rb', line 242

def addColumn(name,type)
	sql="ALTER TABLE  #{@table_name} ADD COLUMN #{name.downcase} #{type};"
	errorMessage=DB.execute(sql)
	return errorMessage
end

#addPrefix(variableHash, prefix) ⇒ Object


265
266
267
268
269
270
271
# File 'app/models/no_db.rb', line 265

def addPrefix(variableHash,prefix)
	ret=Hash.new
	variableHash.each_pair do |key,value|
		ret["#{prefix}#{key}"]=value
	end
	return ret
end

#association_state(association_name) ⇒ Object

Display attribute or method value from association even if association is nil


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'app/models/no_db.rb', line 332

def association_state(association_name)
	case self.class.association_arity(association_name)
	when :to_one
		foreign_key_value=foreign_key_value(association_name)
		if foreign_key_value.nil? then # foreign key uninitialized
			return "Foreign key #{association_name.to_s}_id defined as attribute but has nil value."
		#~ elsif foreign_key_value.empty? then # foreign key uninitialized
			#~ return "Foreign key #{association_name.to_s}_id defined as attribute but has empty value."
		else
			ass=send(association_name)
			if ass.nil? then
				return "Foreign key #{association_name.to_s}_id has value #{foreign_key_value.inspect} but the association returns nil."
			else
				return "Foreign key #{association_name.to_s}_id has value #{foreign_key_value.inspect},#{ass.inspect} and returns type #{ass.class.name}."
			end
		end
	when :to_many
		ass=send(association_name)
		associations_foreign_key_name=(self.class.name.tableize.singularize+'_id').to_sym
		if ass.nil? then
			return "Association #{association_name}'s foreign key #{associations_foreign_key_name} has value #{ass[self.class.name.to_s+'_id']} but the association returns nil."
		elsif ass.empty? then
			ret= "Association #{association_name} with foreign key #{associations_foreign_key_name} is empty; "
			case self.class.association_class(association_name).association_macro_type(self.class.name.tableize.singularize)
			when :has_many
				return ret+"but has many."
			when :belongs_to
				return ret+"but belongs_to."
			when :neither_has_many_nor_belongs_to
				return ret+"because neither_has_many_nor_belongs_to."
			else
				return "New return value from #{self.class.name}.association_macro_type(#{association_name})=#{self.class.association_macro_type(association_name)}."
			end #case
		else
			associations_foreign_key_values=ass.map { |a| a.send(associations_foreign_key_name) }.uniq.join(',')
			return "Association #{association_name}'s foreign key #{associations_foreign_key_name} has value #{associations_foreign_key_values},#{ass.inspect} and returns type #{ass.class.name}."
		end
		
	when :not_generic_table
		return "#{self.class.name} does not recognize #{association_name} as a generic table."
	when:not_an_association
		return "#{self.class.name} does not recognize #{association_name} as association."
	else
		return "New return value from #{self.class.name}.association_arity(#{association_name})=#{self.class.association_arity(association_name)}."
	end #if
end

#classDefiniton(model_class_name) ⇒ Object

def


290
291
292
# File 'app/models/no_db.rb', line 290

def classDefiniton(model_class_name)
	return "class #{rubyClassName(model_class_name)}  < ActiveRecord::Base\ninclude Generic_Table\nend"
end

#classReference(model_class_name) ⇒ Object

def


293
294
295
296
297
# File 'app/models/no_db.rb', line 293

def classReference(model_class_name)
	rubyClassName=rubyClassName(model_class_name)
	model_class_eval=eval("#{classDefiniton(rubyClassName)}\n#{rubyClassName}")
	return model_class_eval
end

#column_DefinitionsObject

def


153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'app/models/no_db.rb', line 153

def column_Definitions
	adaptiveAcquisition
	names=getNames
#	Global::log.debug("names=#{names}")
	typeNums=[] # make it array, so array functons can be used
        numSamples=0
        begin
        	typeNums=updateMaxTypeNum(typeNums)
        	numSamples = numSamples+1
        end until streamEnd or numSamples>10
	@sqlTypes=[]
	ret=[]
	names.each_index do |i| 
		@sqlTypes.push(Import_Column.row2ImportType(typeNums[i]))
#		Global::log.info("#{names[i]} #{@sqlTypes[i]} \"#{@sqlValues[i]}\" #{typeNums[i]}")
		ret.push([names[i],@sqlTypes[i]])
#		Global::log.info("ret=#{ret}")
	end
#	Global::log.info("ret=#{ret}")
	return ret
end

#display(exp) ⇒ Object


209
210
211
212
213
# File 'app/models/no_db.rb', line 209

def display(exp)
 puts "#{exp}="
 puts "#{eval(exp)}"
 puts "#{exp}=#{eval(exp)}"
end

#display_full_time(time) ⇒ Object

def


406
407
408
# File 'app/models/no_db.rb', line 406

def display_full_time(time)
	time.rfc2822
end

#eval_constant(constant_name) ⇒ Object

def


383
384
385
386
387
# File 'app/models/no_db.rb', line 383

def eval_constant(constant_name)
	constant_name.constantize
rescue NameError
	return nil
end

#exclude(variableHash, exclusionList = []) ⇒ Object


272
273
274
275
276
277
278
279
# File 'app/models/no_db.rb', line 272

def exclude(variableHash,exclusionList=[])
	ret=Hash.new
	variableHash.each_pair do |key,value|
		if !exclusionList.include?(key)
			ret[key]=value
		end
	end
end

#find_or_initialize(findCriteria) ⇒ Object


197
198
199
200
201
202
203
204
205
206
207
208
# File 'app/models/no_db.rb', line 197

def find_or_initialize(findCriteria)
	records=find(:all,findCriteria)
	if records.empty? then
		ret= self.new(findCriteria)
		return ret
	elsif records.size==1 then
		return records[0]
	else
		@@log.debug("criteria not unque; records=#{records.inspect}")
		raise 
	end
end

#initFailObject


280
281
282
283
284
# File 'app/models/no_db.rb', line 280

def initFail
	puts "Table does not exist. Enter following command in rails to create:"
	puts self.class.scaffold
	exit
end

#is_ActiveRecord_table?(model_class_name) ⇒ Boolean

def

Returns:

  • (Boolean)

398
399
400
401
402
403
404
405
# File 'app/models/no_db.rb', line 398

def is_ActiveRecord_table?(model_class_name)
	if is_table?(model_class_name.tableize) then
		model_class=eval_constant(model_class_name.classify)
		model_class.new.kind_of?(ActiveRecord::Base)
	else
		return false
	end #if
end

#is_table?(table_name) ⇒ Boolean

def

Returns:

  • (Boolean)

388
389
390
391
392
393
394
395
396
397
# File 'app/models/no_db.rb', line 388

def is_table?(table_name)
	raise "table_name must include only [A-Za-z0-9_]." if (table_name =~ /^[A-Za-z0-9_]+$/).nil?
	if table_exists?(table_name) then
		return true
	#~ elsif table_exists?(table_name.tableize) then
		#~ return true
	else
		return false
	end #if
end

#logObject


107
108
109
110
111
112
# File 'app/models/no_db.rb', line 107

def log
begin
	acquire
	wait
end until false
end

#Match_and_strip(regexp = /=$/) ⇒ Object

def


378
379
380
381
382
# File 'app/models/no_db.rb', line 378

def Match_and_strip(regexp=/=$/)
	matching_methods(regexp).map do |m|
		m.sub(regexp,'')
	end
end

#monitor(keys) ⇒ Object

method log


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'app/models/no_db.rb', line 113

def monitor(keys) # update continously
#	Global::log.info("in monitor self.name=#{self.name}")
	whoAmI
	#generic_acquisitions
	begin
		acquisitionData=acquire
		if self.acquisitionsUpdated?(acquisitionData) then
			row=find_or_initialize(keys)
			row.process(acquisitionData)
			row.printLog
		else
#			Global::log.info(acquisitionData)
		end
	
		wait
	end until false
end

#pg_table_exists?(tableName = self.to_s.downcase) ⇒ Boolean

Returns:

  • (Boolean)

257
258
259
260
261
262
263
264
# File 'app/models/no_db.rb', line 257

def pg_table_exists?(tableName=self.to_s.downcase)
	sql="select table_name from information_schema.tables where table_schema='public' AND table_name='#{tableName}';"
#	Global::log.debug("sql=#{sql}")
	res  = find_by_sql(sql)
#	Global::log.info("res.size=#{res.size}")
	#puts "res=#{res}"
	return res.size>0
end

#process(acquisitionData) ⇒ Object

def


98
99
100
101
102
103
104
105
106
# File 'app/models/no_db.rb', line 98

def process(acquisitionData)
	acqClasses=Generic_Acquisitions.parse_classes(m)
	acqClasses.each map do |ac|
		variableHashes=ac.parse(acquisitionData)
	end #each
	row.updates(variableHashes)
	row.save
	return row
end

#Require_Table(tableName = self.to_s) ⇒ Object


214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'app/models/no_db.rb', line 214

def Require_Table(tableName=self.to_s)
#	Global::log.info("in Require_Table self.class=#{self.class}")
#	Global::log.info("in Require_Table self.to_s=#{self.to_s}")
#	Global::log.info("in Require_Table tableName=#{tableName}")
	if pg_table_exists? then
		#return new
	else
		puts "Table #{tableName} does not exist. Enter following command in rails to create:"
		#puts Generic_Columns.scaffold(Generic_Columns.column_Definitions)
		puts scaffold(self.column_Definitions)
#		puts scaffold(self.column_Definitions)
	end
end

#requireColumn(name, type) ⇒ Object


247
248
249
250
251
252
253
254
255
256
# File 'app/models/no_db.rb', line 247

def requireColumn(name,type)
#	Global::log.info("self.class=#{self.class}")
#	Global::log.info("name=#{name}")
	if has_attribute?(name) then
		return ""
	else
		puts "Column #{name} to be created with #{type}" if $VERBOSE
		return addColumn(name,type)
	end
end

#rubyClassName(model_class_name) ⇒ Object


285
286
287
288
289
# File 'app/models/no_db.rb', line 285

def rubyClassName(model_class_name)
	model_class_name=model_class_name[0,1].upcase+model_class_name[1,model_class_name.length-1] # ruby class names are constants and must start with a capital letter.
	# remainng case is unchanged to allow camel casing to separate words for model names.
	return model_class_name
end

#scaffold(columnDefs) ⇒ Object


227
228
229
230
231
232
233
234
235
236
# File 'app/models/no_db.rb', line 227

def scaffold (columnDefs)
#	Global::log.info("singularTableName=#{singularTableName}")
#	Global::log.info("in scaffold singularTableName=#{singularTableName}")
	rails="script/generate scaffold #{singularTableName} "
	columnDefs.each do  |col|
		rails="#{rails} #{col[0]}:#{col[1]}"
		#puts rails
	end
	return rails
end

#singularTableNameObject


237
238
239
240
241
# File 'app/models/no_db.rb', line 237

def singularTableName
#	Global::log.info("in singularTableName self.class=#{self.class}")
#	Global::log.info("in singularTableName self.to_s=#{self.to_s}")
	return self.to_s.chop
end

#table2yaml(table_name = self.class.name.tableize) ⇒ Object

def


298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'app/models/no_db.rb', line 298

def table2yaml(table_name=self.class.name.tableize)
	i = 0 #"000"
	limit=100 # too long slow all tests, too short give poor test coverage
	sql  = "SELECT * FROM %s LIMIT #{limit}"
    	File.open("test/fixtures/#{table_name}.yml.gen", 'w') do |file|
      		data = self.class.limit(limit).all
#		puts "data.inspect=#{data.inspect}"
		file.write "# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html"
		 file.write data.inject({}) { |hash, model_instance|
			i=i+1
			fixture_attributes=model_instance.attributes
			fixture_attributes.delete('created_at')  # automatically regenerated
			fixture_attributes.delete('updated_at')  # automatically regenerated
			if sequential_id? then
				primaryKeyValue=i
				fixture_attributes['id']=i  # automatically regenerated
			else
				primaryKeyValue=model_instance.logical_primary_key_value
				fixture_attributes.delete('id')  # automatically regenerated
			end
#			puts "fixture_attributes.inspect=#{fixture_attributes.inspect}"
#			puts "fixture_attributes.to_yaml.inspect=#{fixture_attributes.to_yaml.inspect}"
			hash[primaryKeyValue] = fixture_attributes
			hash
		}.to_yaml
	end# file open
end

#updateMaxTypeNum(maxTypeNums) ⇒ Object


145
146
147
148
149
150
151
152
# File 'app/models/no_db.rb', line 145

def updateMaxTypeNum(maxTypeNums)
	adaptiveAcquisition
	values= getValues
	values.each_index do |i|
		maxTypeNums[i]=[Import_Column.firstMatch(values[i]),maxTypeNums.fetch(i,-1)].max
	end
	return   maxTypeNums
end

#updates(variableHashes) ⇒ Object

activeRecordTableNotCreatedYet


197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'app/models/generic_table.rb', line 197

def updates(variableHashes)
#	Global::log.info("variableHashes.inspect=#{variableHashes.inspect}")
	variableHash={} # merge into single hash
	variableHashes.each do |vhs|
		vhs.each do |vh|
			variableHash.merge(vh)
		end #each
	end #each
#	Global::log.info("variableHash.inspect=#{variableHash.inspect}")
	if exists?(variableHash) then
		@@log.debug("record already exists")
	else
		row=self.new
#		Global::log.info( "variableHash['khhr_observation_time_rfc822']=#{variableHash['khhr_observation_time_rfc822']}")
		reportNull(variableHash)
		row.update_attributes(variableHash)
		now=Time.new
		if row.has_attribute?('created_at') then
			row.update_attribute("created_at",now)
		end #if
		if row.has_attribute?('updated_at') then
			row.update_attribute("updated_at",now)
		end #if
		#update_attribute("id","NULL") 
	end # if else
	
end