Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Command registry, minimal version
- require 'auth'
- require 'commands'
- Dir['commands/*'].each {|f| require f }
- Commands["register-person"].call("lupine_85", "aPassword")
- # disconnected database event
- Auth.current_instance.reconnect!
- # auth.rb
- class Auth
- class << self
- attr_accessor :current_instance
- end
- # optional
- self.current_instance = new("default-connect-string")
- def initialize(db_conn_string)
- @db = nil # Sequel.connect( ... )
- @alist_m = Mutex.new
- @alist = {}
- end
- def reconnect!
- # change value of @db, possibly @alist
- end
- def register(username, password)
- resident = nil # Resident.new(...)
- @db # @db.save(resident) # or whatever
- end
- def authenticate!(username, password)
- if true # Resident.where(:username => username, :password => password).size == 1
- # Or however the DB / resident class works
- @alist_m.synchronize { @alist[username] = true }
- true
- else
- false
- end
- end
- def logout(username)
- @alist_m.synchronize { !!@alist.delete(username) }
- end
- def logged_in?(username)
- @alist_m.synchronize { @alist.has_key?(username) }
- end
- end
- # commands.rb
- class NamedProc < Proc
- attr_accessor :command_name
- def initialize(command_name, *args, &blk)
- @command_name = command_name
- super(*args, &blk)
- end
- end
- module Commands
- def self.[](name)
- all_registered[name] # TODO: don't calculate reflection for every call!
- end
- def self.all_registered
- cmds = Commands.constants.collect {|c_name| Commands.const_get(c_name) }
- Hash[*cmds.collect {|c| [c.command_name, c] }.flatten]
- end
- end
- # commands/register.rb
- # This command uses the Auth.current_instance convention to access the database / model
- module Commands
- Register = NamedProc.new("register-person") {|username, password|
- Auth.current_instance.register(username, password)
- }
- end
- # commands/login.rb
- # This one relies on the caller to pass it an instance of auth. Either will work.
- module Commands
- Login = NamedProc.new("login") {|auth_instance, username, password|
- auth_instance.register(username, password)
- # ...
- }
- end
Add Comment
Please, Sign In to add comment