2012-07-13 2 views
3

어떻게 루비에서 디렉토리의 각 파일에있는 모든 클래스의 인스턴스를 만들고 배열로 제공합니까? ?디렉토리의 모든 클래스 인스턴스를 자동으로 작성하려면 어떻게합니까?

미리 감사드립니다.

+0

이 작업을 수행 할 왜 그냥 궁금해서? ...이있다 순전히 학문적? 또는 항목을 미리 캐시하고 싶습니까? – scunliffe

+0

아니요, 미리 정의 된 배열에 클래스를 추가하기 위해 코드로 돌아갈 필요가 없기 때문에이 작업을 수행하고 있습니다. 내 생각에 클래스가 포함 된 파일을 디렉토리에 놓고 스크립트가 어려운 부분을 수행하도록하기 위해 작업량을 단순성과 동일하게 낮 춥니 다. – user1207719

답변

6

ObjectSpace을 사용하여 새 클래스를 찾고 인스턴스화 할 수 있습니다. 그들은 모두 그들의 .rb 파일을 포함하고 초기화 인수를 취하지 같은 이름을 공유하는 가정

def load_and_instantiate(class_files) 
    # Find all the classes in ObjectSpace before the requires 
    before = ObjectSpace.each_object(Class).to_a 
    # Require all files 
    class_files.each {|file| require file } 
    # Find all the classes now 
    after = ObjectSpace.each_object(Class).to_a 
    # Map on the difference and instantiate 
    (after - before).map {|klass| klass.new } 
end 

# Load them! 
files = Dir.glob("path/to/dir/*.rb") 
objects = load_and_instantiate(files) 
+0

재미있는 솔루션, 결코 생각하지 못했습니다. 고맙습니다. – user1207719

+0

쿨 솔루션, +1 –

0

...

#initialize array of objects 
objects = [] 

#list ruby files in directory 
classes = Dir.glob("*.rb") 

#make method to easily remove file extension 
def cleanse(fileName) 
    return fileName.gsub(".rb", "") 
end 

classes.each do |file| 
    #require the new class 
    require fileName 

    #add it to our array 
    objects[objects.length] = eval(cleanse(file) + ".new()") 
end 
+0

답변에 Ruby에서 일반적인 코드가 포함되어 있습니다. 뱀 케이스가 일반적으로 선호되므로'fileName'은'file_name'이어야합니다. 'objects [object.length] = eval ...'는 PHP처럼 보이며'objects << eval ... '인 경우 훨씬 더 좋을 것입니다. – gmalette

+0

@gmalette 아, 고마워요. 이상한 점은 PHP로 개발하기 시작한 지 얼마되지 않아 루비에서 더 오랫동안 일 해왔다는 것입니다. – Mark

관련 문제