Module: Alchemist::Server

Defined in:
lib/alchemist-server.rb,
lib/alchemist-server/version.rb

Constant Summary collapse

SERVER_PORT =
79 * 100
VERSION =
"0.0.2"

Class Method Summary collapse

Class Method Details

.load_history(file_name) ⇒ Object



114
115
116
117
118
119
120
# File 'lib/alchemist-server.rb', line 114

def self.load_history(file_name)
  if File.exist? file_name
    WorldHistory.parse File.read(file_name)
  else
    WorldHistory.genesis
  end
end

.match_command?(command_name, command) ⇒ Boolean

Returns:

  • (Boolean)


122
123
124
# File 'lib/alchemist-server.rb', line 122

def self.match_command?(command_name, command)
  command_name =~ /^#{command.pattern}/
end

.one_shot(world_file, command_string_ascii) ⇒ Object



65
66
67
68
69
70
71
72
73
74
# File 'lib/alchemist-server.rb', line 65

def self.one_shot(world_file, command_string_ascii)
  command_string = command_string_ascii.force_encoding Encoding::UTF_8
  avatar_name, command, *args = command_string.split /\s+/

  if command_mod = COMMANDS.detect { |c| match_command? command, c }
    run_command_module command_string, world_file
  else
    run_special_command world_file, command, *args
  end
end

.run(world_file) ⇒ Object



60
61
62
63
# File 'lib/alchemist-server.rb', line 60

def self.run(world_file)
  ::EventMachine.start_server "", SERVER_PORT, ServerHandler.new(world_file)
  puts "Listening on #{SERVER_PORT}"
end

.run_append(command_string_ascii, world_file, history) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/alchemist-server.rb', line 82

def self.run_append(command_string_ascii, world_file, history)
  command_string = command_string_ascii.force_encoding Encoding::UTF_8
  event = Event.new command_string, Time.now
  outcome = event.happen history

  if outcome.try :new_world
    new_history = WorldHistory.new event, history

    File.open(world_file,'a') do |f|
      f.write event.to_s
      f.write "\n"
    end
  end

  outcome.update new_history: new_history
end

.run_command_module(command_string, world_file) ⇒ Object



76
77
78
79
80
# File 'lib/alchemist-server.rb', line 76

def self.run_command_module(command_string, world_file)
  history = load_history world_file
  outcome = run_append command_string, world_file, history
  outcome.try :response
end

.run_special_command(world_file, command_string, *args) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/alchemist-server.rb', line 99

def self.run_special_command(world_file, command_string, *args)
  case command_string
  when /^show_raw_file$/
    File.read(world_file)
  when /^show_history$/
    load_history(world_file).to_s
  when /^dim(ensions)?$/
    load_history(world_file).world.dimensions(*args).to_s
  when /^geo(graphy)?$/
    load_history(world_file).world.geography.to_s
  else
    "Unknown Command: #{command_string}"
  end
end