2015-04-07 22 views
0

我正在嘗試從一個類創建一個對象。但是,在需要時,他們的對象將被創建..下面有點硬編碼解釋從腳本中創建一個對象Ruby

incoming_message = #message sent though inter webs 
class Repeater 
    def initialize(username, ip) 
    #repeat incoming message to back to ip 
    end 
end 
incoming_message = Repeater.new(user, ip) 

現在,我不能這樣做,監守incoming_message不是一個常數。 我該如何解決這個問題?

編輯:

要清理一些事情。我確實需要使用這個類來創建具有不同名稱的多個對象。轉發器用於聊天服務器,在該服務器中接收來自1個用戶的傳入消息,然後將所有連接的客戶端發回。連接的每個新客戶端都會有一個使用該特定IP地址創建的對象,以便可以將來自其他客戶的消息發送給客戶端。

這將需要在每個人都從其他用戶的信息發送到同一個端口上的服務器讀取消息,然後寫信給客戶的是什麼信號...

我希望這有助於爲所有的困惑遺憾: )

+1

我認爲你將不得不澄清你的問題有點:) – mikej

+0

@mikej完成:)謝謝 – Gittb

回答

0

如果要維護某種全局類級別的狀態,則應在Repeater上定義一個類級別的訪問器,以便您可以將重複消息分配給該類別級別的狀態。

class Repeater 
    class << self 
    attr_accessor :incoming_message 
    end 

    def initialize(username, ip) 
    # repeat Repeater.incoming_message to back to ip 
    end 
end 

Repeater.incoming_message = "what" 
Repeater.new(user, ip) 
0

您需要使用一些解析+序列化。他們可以連線已經序列化/編組的字符串嗎?

1) convert the ruby code to yaml or json 
2) use the json or yaml load method like myobj = YAML.load(new_yaml_string) 

save it in another file called input and do a 
require 'input' 
create object of repeater 
相關問題