Class: Sadie

Inherits:
Object
  • Object
show all
Defined in:
lib/sadie.rb,
lib/sadie/version.rb,
lib/sadie/defaults.rb

Constant Summary collapse

BEFORE =
1
AFTER =
2
EACH =
3
VERSION =
"0.0.50"
DEFAULTS =

ppdp = File.join(“lib/sadie/primer_plugins”,File.join(“gems/sadie-#VERSION”,ENV))

{
  "sadie.primers_dirpath" => File.expand_path("primers","/var/sadie"),
  "sadie.sessions_dirpath" => File.expand_path("sessions","/var/sadie")
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Sadie

method: constructor

options can include any kay, value pairs but the following key values bear mention:
  REQUIRED

    sadie.sessions_dirpath
          or
        sadie.session_id
          or
        sadie.session_filepath  <- this is probably a bad call, use with caution

    and

      sadie.primers_dirpath

    and
      sadie.primer_plugins_dirpath


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/sadie.rb', line 168

def initialize( options )
    
    # check instance sanity
    _checkInstanceSanity        
    _checkClassSanity
    
    Sadie::setCurrentSadieInstance( self )
    
    # internalize defaults to shortterm
    DEFAULTS.each do |key, value|
            _set( key, value )
    end
    
    # iterate over constructor args, but do primers_dirpath last since it
    # causes a call to initializePrimers
    options.each do |key, value|
            set( key, value )
    end
            
    # if a path to a session is given, init using session file
    if options.has_key?( "sadie.session_filepath" )
        set( "sadie.session_filepath", options["sadie.session_filepath"] )
        _initializeWithSessionFilePath( get("sadie.session_filepath") )
    elsif options.has_key?( "sadie.session_id" )
        set( "sadie.session_id", options["sadie.session_id"] )
        _initializeWithSessionId( get( "sadie.session_id" ) )
    else
        set( "sadie.session_id", _generateNewSessionId )
    end
    
    # add the default sadie plugins dir
    plugins_dirpath = "lib/sadie/primer_plugins"   # for dev
    if ! File.exists? plugins_dirpath
        plugins_dirpath = File.join(
            ENV['GEM_HOME'],
            "gems/sadie-#{Sadie::VERSION}",
            "lib/sadie/primer_plugins"
        )
        
        if ! File.exists? plugins_dirpath
            plugins_dirpath = File.expand_path "../sadie/lib/sadie/primer_plugins"
        end
        
    end        
    addPrimerPluginsDirPath plugins_dirpath
    
end

Class Method Details

.eacher(eacher_params, &block) ⇒ Object

method: Sadie::eacher

called by eacher files to hook into priming operations and calls to set method



70
71
72
73
# File 'lib/sadie.rb', line 70

def self.eacher( eacher_params, &block )
    current_sadie_instance = Sadie::getCurrentSadieInstance
    current_sadie_instance.eacher( eacher_params, &block )
end

.eacherFrame(sadiekey, occur_at, param = nil) ⇒ Object

method: Sadie::eacherFrame

eacherFrame is called by get and set methods and is available to primer plugins as well. when eacher primer files call eacher, they are registering code to be run either BEFORE or AFTER the key/value store is set. Note that the BEFORE eacherFrame runs just before priming when a primer exists and just before set for keys set without primers. EACH eacherFrames are called as the data is being assembled, if such a thing makes sense. The included SQLQueryTo2DArray plugin tries to call any eacherFrame with an EACH occurAt parameter with each row and the registering an EACH eacher might make sense for any number of incrementally built data types



87
88
89
90
# File 'lib/sadie.rb', line 87

def self.eacherFrame( sadiekey, occur_at, param=nil )
    current_sadie_instance = Sadie::getCurrentSadieInstance
    current_sadie_instance.eacherFrame( sadiekey, occur_at, param )
end

.getCurrentSadieInstanceObject

method: Sadie::getCurrentSadieInstance

called by plugin handlers to get access to the current Sadie instance



50
51
52
# File 'lib/sadie.rb', line 50

def self.getCurrentSadieInstance
    @current_sadie_instance
end

.getSadieInstance(options) ⇒ Object

method: Sadie::getSadieInstance

returns a new Sadie instance. Options match those of Sadie’s constructor method



35
36
37
# File 'lib/sadie.rb', line 35

def self.getSadieInstance( options )
    Sadie.new(options)
end

.iniFileToHash(filepath) ⇒ Object

method: Sadie::iniFileToHash

utility class method. accepts a filepath. digests ini file and returns hash of hashes.



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/sadie.rb', line 105

def self.iniFileToHash ( filepath )
    section = nil
    ret = Hash.new
    File.open( filepath, "r" ).each do |f|
        f.each_line do |line|
            next if line.match(/^;/) # skip comments
            if matches = line.match(/\[([^\]]+)\]/)
                section = matches[1]
                ret[section] = Hash.new
            elsif matches = line.match(/^\s*([^\s\=]+)\s*\=\s*([^\s]+.*)\s*$/)
                key = matches[1]
                value = matches[2]
                
                # strip quotes
                if qmatches = value.match(/[\'\"](.*)[\'\"]/)
                    value = qmatches[1]
                end
                
                if defined? section
                    ret[section][key] = value
                end
            end
        end
    end
    ret.empty? and return nil
    return ret
end

.prime(primer_definition, &block) ⇒ Object

method: Sadie::Prime

called by the .res files to register the keys the .res will prime for

accepts as an argument a hash and a block. The hash must include the key: ‘provides’ and it must define an array of keys that the calling resource (.res) file will have provided after the block is evaluated



62
63
64
65
# File 'lib/sadie.rb', line 62

def self.prime ( primer_definition, &block )
    current_sadie_instance = Sadie::getCurrentSadieInstance
    current_sadie_instance.prime( primer_definition, &block )
end

.registerPrimerPlugin(arghash, &block) ⇒ Object

method: Sadie::registerPrimerPlugin

this method is called in the .plugin.rb files to register new plugin types



96
97
98
99
# File 'lib/sadie.rb', line 96

def self.registerPrimerPlugin ( arghash, &block )
    current_sadie_instance = Sadie::getCurrentSadieInstance
    current_sadie_instance.registerPrimerPlugin( arghash, &block )
end

.setCurrentSadieInstance(instance) ⇒ Object

method: Sadie::setCurrentSadieInstance

this is called just prior to calling a primer plugin to handle a primer to provide a current sadie instance for Sadie::getCurrentSadieInstance to return



43
44
45
# File 'lib/sadie.rb', line 43

def self.setCurrentSadieInstance ( instance )
    @current_sadie_instance = instance
end

.templatedFileToString(filepath, binding = nil) ⇒ Object

method: Sadie::templatedFileToString

utility class method. accepts a filepath. digests a template and returns a string containing processed template output



138
139
140
141
142
143
144
145
146
147
148
# File 'lib/sadie.rb', line 138

def self.templatedFileToString( filepath, binding=nil )
    
    template = ERB.new File.new(filepath).read
    current_sadie_instance = Sadie::getCurrentSadieInstance
    if defined? binding
        template.result binding 
    else
        template.result self
    end
    
end

Instance Method Details

#addPrimerPluginsDirPath(path) ⇒ Object

method: addPrimerPluginsDirPath

addPrimerPluginsDirPath adds a directory which will be scanned for plugins to register just before initializePrimers looks for primers to initialize



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/sadie.rb', line 332

def addPrimerPluginsDirPath( path )
    
    exppath = File.expand_path(path)
    
    # add the path to the system load path
    $LOAD_PATH.include?(exppath) \
        or $LOAD_PATH.unshift(exppath)
        
    # add the path to the pluginsdir array
    defined? @plugins_dir_paths \
        or @plugins_dir_paths = Array.new        
    @plugins_dir_paths.include?(exppath) \
        or @plugins_dir_paths.unshift(exppath)
    
    @primer_plugins_initialized = nil
    return self
end

#debug!(lvl, msg) ⇒ Object

method: getDebugLevel

will print a debugging message if the current debug level is greater than or equal to lvl



240
241
242
243
# File 'lib/sadie.rb', line 240

def debug!( lvl, msg )
    defined? @debug_level or @debug_level = 10
    (lvl <= @debug_level) and puts "SADIE(#{lvl}): #{msg}"
end

#destroy!(key) ⇒ Object

method: destroy!

remove the key from sadie



496
497
498
499
# File 'lib/sadie.rb', line 496

def destroy! ( key )
    unset( key )
    primed?( key ) and unprime( key )
end

#destroyOnGet?(key) ⇒ Boolean

method: destroyOnGet?

returns true if the destructOnGet flag is set for the key

Returns:

  • (Boolean)


504
505
506
# File 'lib/sadie.rb', line 504

def destroyOnGet?( key )
    ( @flag_destroyonget.has_key?( key ) && @flag_destroyonget["#{key}"] )
end

#eacher(params, &block) ⇒ Object

method: eacher

( usually this will be called by the class method…it looks better )

see class method eacher for an explanation



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/sadie.rb', line 251

def eacher( params, &block )
    filepath        = getCurrentPrimerFilepath
    key_prefix      = getCurrentPrimerKeyPrefix
    occur_at        = params[:when]
    
    # gen sadie key
    basefilename    = filepath.gsub(/^.*\//,"")
    sadiekey        = key_prefix + "." + basefilename.gsub(/\.each(?:\..*)*$/,"")
    sadiekey        = sadiekey.gsub( /^\.+/,"" )
    if params.has_key? "sadiekey"
        sadiekey    = params["sadiekey"]
    end
    
    whichEacherFrame != Sadie::EACH and debug! 10, "whicheacherframe: #{whichEacherFrame}, occur_at: #{occur_at}"
    
    if midEacherInit?
        
        debug! 10, "in mid eacher init (#{sadiekey})"
        
        memorizeEacherFileLocation( sadiekey, filepath )
        
        if params.has_key? :provides
            
            # make sure we're passing an array
            provide_array = params[:provides]
            provide_array.respond_to? "each" or provide_array = [provide_array]
            
            # tell sadie that the sadiekey primer also provides everything in the provide array
            setEachersProvidedByPrimer( sadiekey, provide_array )
            
        end            
        
    elsif whichEacherFrame == occur_at
        
        occur_at != Sadie::EACH and debug! 10, "pre-yield for skey: #{sadiekey}, #{occur_at}"
        
        if block.arity == 0
            yield self
        else
            yield self, getEacherParam
        end
        
        occur_at != Sadie::EACH and debug! 10, "post-yield for skey: #{sadiekey}, #{occur_at}"
    end
end

#eacherFrame(sadiekey, occur_at, param = nil) ⇒ Object

method: eacherFrame

( usually this will be called by the class method…it looks better )

see class method eacherFrame for an explanation



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/sadie.rb', line 303

def eacherFrame( sadiekey, occur_at, param=nil )
    
    occur_at != Sadie::EACH and debug! 8, "eacherFrame(#{occur_at}): #{sadiekey}"
    
    key = sadiekey
#         if defined? @eacher_frame_redirect
#             if @eacher_frame_redirect.has_key? key
#                 key = @eacher_frame_redirect[key]
#             end
#         end
    
    setEacherFrame( occur_at )
    defined? param and setEacherParam( param )
    if filepaths = eacherFilepaths( key )
        filepaths.each do |filepath|
             occur_at != Sadie::EACH and debug! 8, "eacher frame loading: #{filepath} for key: #{key}"
            load filepath
        end
    end
    unsetEacherParam
    unsetEacherFrame
end

#get(k) ⇒ Object

method: get

a standard getter which primes the unprimed and recalls “expensive” facts from files completely behind-the-scenes as directed by the resource (.res) files



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'lib/sadie.rb', line 422

def get( k )
    
    debug! 10, "get(#{k})"
    
    defined? @eacher_frame_redirect or @eacher_frame_redirect = Hash.new
    
    if ! isset?( k )
        debug! 10, "#{k} is not set"
        if isEacherKey?( k )
            debug! 10, "sadiekey: #[k} is eacher, fetching: #{@eacher_frame_redirect[k]}"
            get @eacher_frame_redirect[k]
        
        elsif primeable?( k )
            
            debug! 10, "calling eacher from get method for #{k}"
            setUnbalancedEacher k
            Sadie::eacherFrame( k, BEFORE )
            
            # prime if not yet primed
            primed?( k ) or _prime( k )
        end
    end
    
    return _recallExpensive( k ) if expensive?( k )
    
    # if it's already set, return known answer
    if isset?( k )
        
        # _get the return value
        return_value = _get( k )
        
        # unset and unprime if destructOnGet?
        destroyOnGet?( k ) \
            and destroy! k
        
        return return_value
    end
    
end

#getDebugLevelObject

method: getDebugLevel

return current debug level (default is 10)



230
231
232
233
# File 'lib/sadie.rb', line 230

def getDebugLevel
    defined? @debug_level or @debug_level = 10
    @debug_level
end

#initializePrimersObject

method: initializePrimers

call this method only after registering all the plugin directories and setting the appropriate session and primer directory paths. after this is called, the key/val pairs will be available via get



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# File 'lib/sadie.rb', line 599

def initializePrimers
    
    Sadie::setCurrentSadieInstance( self )
    
    # make sure primer plugins have been initialized
    primerPluginsInitialized? \
        or initializePrimerPlugins
    
    eachersInitialized? \
        or initializeEachers
    
    primers_dirpath = get( "sadie.primers_dirpath" ) \
        or raise "sadie.primers_dirpath not set"

    return true if primersInitialized? primers_dirpath

    debug! 1, "Initializing primers..."
    initializePrimerDirectory( "", primers_dirpath )
    debug! 1, "...finished initializing primers."
    
    @flag_primed[primers_dirpath] = true
end

#isset?(key) ⇒ Boolean

method: isset?

returns true if sadie has a value for the key

Returns:

  • (Boolean)


472
473
474
475
476
# File 'lib/sadie.rb', line 472

def isset?( key )
    return true if @shortterm.has_key?( key )
    return true if expensive?( key )
    false
end

#output(k) ⇒ Object

method: output

an alias for get. intended for use with primers that produce an output beyond their return value



465
466
467
# File 'lib/sadie.rb', line 465

def output( k )
    return get( k )
end

#prime(primer_definition, &block) ⇒ Object

method: prime

( usually this will be called by the class method…it looks better )

see class method prime for an explanation



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/sadie.rb', line 356

def prime( primer_definition, &block )
    # validate params
    defined? primer_definition \
        or raise "Prime called without parameters"
    primer_definition.is_a? Hash \
        or raise "Prime called without hash parameters"
    defined? primer_definition["provides"] \
        or raise "Prime called without provides parameter"
    
    # if initializing primers, just remember how to get back to the primer later,
    # otherwise, prime
    if midPrimerInit?
        
        # mid primer init, just memorize primer location
        memorizePrimerLocation( @mid_primer_filepath, getCurrentPrimerPluginFilepath, primer_definition["provides"] )
    else
        
        # run code block with the current sadie instance
        block.call( self )
        
        # loop thru all primer provides, ensuring each primed
        current_primer_filepath = getCurrentPrimerFilepath
        primer_definition["provides"].each do | key |
            
            # skip blank lines
            next if key.match /^\s*$/
            
            # key primed or raise error
            primed? key \
                or raise "primer definition file: #{current_primer_filepath} was supposed to define #{key}, but did not"
        end
    end
    
end

#registerPrimerPlugin(arghash, &block) ⇒ Object

method: registerPrimerPlugin

( usually this will be called by the class method…it looks better )

see class method registerPrimerPlugin for an explanation



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/sadie.rb', line 397

def registerPrimerPlugin ( arghash, &block )
    
    # if mid plugin init is set, we're registering the plugin
    # init mode, just store arghash info
    accepts_block = arghash.has_key?( "accepts-block" ) && arghash["accepts-block"] ? true : false
    prime_on_init = arghash.has_key?( "prime-on-init" ) && arghash["prime-on-init"] ? true : false
    
    # if mid plugin init, register the plugin params with the match
    if midPluginInit?
        
        regPluginMatch( arghash["match"], @mid_plugin_filepath, accepts_block, prime_on_init )
        
    # midplugininit returned false, we're actually in the process of either initializing
    # a primer or actually priming
    else
        yield self, getCurrentPrimerKeyPrefix, getCurrentPrimerFilepath
    end
end

#revert!Object

method: revert!

return to last saved state



583
584
585
586
587
588
589
590
591
# File 'lib/sadie.rb', line 583

def revert!
    
    @shortterm = {
        "sadie.session_id"                => get( "sadie.session_id" ),
        "sadie.sessions_dirpath"          => get( "sadie.sessions_dirpath" )
    }
    
    _initializeWithSessionId( get( "sadie.session_id" ) )
end

#saveObject

method: save

serialize to session file



569
570
571
572
573
574
575
576
577
# File 'lib/sadie.rb', line 569

def save
    session_id = get("sadie.session_id")
    session_filepath = File.expand_path( "session."+session_id, get( "sadie.sessions_dirpath" ) )
    serialized_value                = Marshal::dump( [ @shortterm, @flag_primed, @flag_expensive ] )
    File.open(session_filepath, 'w') { |f|
        f.write( serialized_value )
    }
    return session_id
end

#set(k, v) ⇒ Object

method: set

alias for setCheap(k,v)



510
511
512
# File 'lib/sadie.rb', line 510

def set( k, v )
    setCheap( k, v )
end

#setCheap(k, v) ⇒ Object

method: setCheap

the cheap setter. key, value pairs stored via this method are kept in memory



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/sadie.rb', line 517

def setCheap( k, v )
    
    debug! 9,  "setting cheap: #{k}"
    Sadie::eacherFrame( k, BEFORE ) if ! eacherUnbalanced?( k )
            setUnbalancedEacher k
    
    if getDebugLevel == 10
        debug! 10, "dumping value:"
        pp v
    end
    
    # set it, mark not expensive and primed
    _set( k, v )
    _expensive( k, false )
    _primed( k, true )
    
    Sadie::eacherFrame( k, AFTER, v )
    clearUnbalancedEacher k
    
end

#setDebugLevel(lvl) ⇒ Object

method: setDebugLevel

from 0 to 10 with 0 being no debugging messages and 10 being all debugging messages



220
221
222
223
224
# File 'lib/sadie.rb', line 220

def setDebugLevel( lvl )
    lvl > 10 and lvl = 10
    lvl < 0 and lvl = 0
    @debug_level  = lvl.to_i
end

#setDestroyOnGet(key, turnon = true) ⇒ Object

method: setDestroyOnGet

key value will go away and key will be unprimed and unset after next get

NOTE: this doesn't make sense with keys that were set via setExpensive
      so it can be set, but nothing's going to happen differently


484
485
486
487
488
489
490
491
# File 'lib/sadie.rb', line 484

def setDestroyOnGet( key, turnon=true )
    if ( turnon )
        @flag_destroyonget["#{key}"] = true
        return true
    end
    @flag_destroyonget.has_key?( key ) \
        and @flag_destroyonget.delete( key )
end

#setExpensive(k, v) ⇒ Object

method: setExpensive

the expensive setter. key, value pairs stored via this method are not kept in memory but are stored to file and recalled as needed



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/sadie.rb', line 542

def setExpensive(k,v)
    
    debug! 9,  "setting expensive: #{k}"
    Sadie::eacherFrame( k, BEFORE ) if ! eacherUnbalanced?( k )
                     setUnbalancedEacher k

    
    expensive_filepath              = _computeExpensiveFilepath( k )
    serialized_value                = Marshal::dump( v )
    
    File.exist? File.dirname( expensive_filepath ) \
        or Dir.mkdir File.dirname( expensive_filepath )
    
    File.open(expensive_filepath, 'w') { |f|
        f.write( serialized_value )
    }
    _expensive( k, true )
    _primed( k, true )
    
    Sadie::eacherFrame( k, AFTER, v )
    clearUnbalancedEacher k
end