Guest User

Untitled

a guest
Oct 12th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. # Command registry, minimal version
  2.  
  3. require 'auth'
  4. require 'commands'
  5. Dir['commands/*'].each {|f| require f }
  6.  
  7. Commands["register-person"].call("lupine_85", "aPassword")
  8. # disconnected database event
  9. Auth.current_instance.reconnect!
  10.  
  11. # auth.rb
  12. class Auth
  13. class << self
  14. attr_accessor :current_instance
  15. end
  16.  
  17. # optional
  18. self.current_instance = new("default-connect-string")
  19.  
  20. def initialize(db_conn_string)
  21. @db = nil # Sequel.connect( ... )
  22. @alist_m = Mutex.new
  23. @alist = {}
  24. end
  25.  
  26. def reconnect!
  27. # change value of @db, possibly @alist
  28. end
  29.  
  30. def register(username, password)
  31. resident = nil # Resident.new(...)
  32. @db # @db.save(resident) # or whatever
  33. end
  34.  
  35. def authenticate!(username, password)
  36. if true # Resident.where(:username => username, :password => password).size == 1
  37. # Or however the DB / resident class works
  38. @alist_m.synchronize { @alist[username] = true }
  39. true
  40. else
  41. false
  42. end
  43. end
  44.  
  45. def logout(username)
  46. @alist_m.synchronize { !!@alist.delete(username) }
  47. end
  48.  
  49. def logged_in?(username)
  50. @alist_m.synchronize { @alist.has_key?(username) }
  51. end
  52. end
  53.  
  54. # commands.rb
  55.  
  56. class NamedProc < Proc
  57. attr_accessor :command_name
  58.  
  59. def initialize(command_name, *args, &blk)
  60. @command_name = command_name
  61. super(*args, &blk)
  62. end
  63. end
  64.  
  65. module Commands
  66. def self.[](name)
  67. all_registered[name] # TODO: don't calculate reflection for every call!
  68. end
  69. def self.all_registered
  70. cmds = Commands.constants.collect {|c_name| Commands.const_get(c_name) }
  71. Hash[*cmds.collect {|c| [c.command_name, c] }.flatten]
  72. end
  73.  
  74. end
  75.  
  76. # commands/register.rb
  77.  
  78. # This command uses the Auth.current_instance convention to access the database / model
  79. module Commands
  80. Register = NamedProc.new("register-person") {|username, password|
  81. Auth.current_instance.register(username, password)
  82. }
  83. end
  84.  
  85. # commands/login.rb
  86.  
  87. # This one relies on the caller to pass it an instance of auth. Either will work.
  88. module Commands
  89. Login = NamedProc.new("login") {|auth_instance, username, password|
  90. auth_instance.register(username, password)
  91. # ...
  92. }
  93. end
Add Comment
Please, Sign In to add comment