2009-08-05 1 views
1

단일 파일 snippet.rb에서이 코드를 얻었으며 예상대로 실행됩니다. 이 스크립트는 현재 시간에 URL의 미리보기 이미지를 가져 오는 dzone 스 니펫에서 가져온 것입니다.레일에 기본 루비 테스트 코드가있는 단일 파일을 재사용 하시겠습니까?

이제이 기능을 레일즈와 통합하고 싶습니다. 시작하려면 어떻게해야할까요? 이것을 lib 디렉토리에있는 루비 파일에 넣거나 모듈로 만들까요 ??? Ruby에 익숙하지 않아서 누구나 시작할 수있는 방법과 위치를 알려줄 수 있습니까?

require 'net/http' 
    require 'rubygems' 
    require 'xmlsimple' 

    class Nailer 

     @@api_baseurl = 'http://webthumb.bluga.net/api.php' 
     @@api_key = 'YOUR-API-KEY' 

     attr_accessor :collection_time, :job_id, :ok 

     def initialize(url, width = 1024, height = 768) 
      url = url.gsub!(/&/, '&') 
      api_request = 
    %Q{<webthumb><apikey>#{@@api_key}</apikey><request><url>#{url}</url><width>#{width}</width><height>#{height}</height></request></webthumb>} 

      result = do_request(api_request) 

      if result.class == Net::HTTPOK 
       result_data = XmlSimple.xml_in(result.body) 
       @job_id = result_data['jobs'].first['job'].first['content'] 
       @collection_time = Time.now.to_i + result_data['jobs'].first['job'].first['estimate'].to_i 
       @ok = true 
      else 
       @ok = false 
      end 
     end 

     def retrieve(size = :small) 
      api_request = 
    %Q{<webthumb><apikey>#{@@api_key}</apikey><fetch><job>#{@job_id}</job><size>#{size.to_s}</size></fetch></webthumb>} 
      result = do_request(api_request) 
      result.body 
     end 

     def retrieve_to_file(filename, size = :small) 
      File.new(filename, 'w+').write(retrieve(size.to_s)) 
     end 

     def ready? 
      return unless Time.now.to_i >= @collection_time 

      api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><status><job>#{@job_id}</job></status></webthumb>} 
      result = do_request(api_request) 

      if result.class == Net::HTTPOK 
       @ok = true 
       result_data = XmlSimple.xml_in(result.body) 
       begin 
       @result_url = result_data['jobStatus'].first['status'].first['pickup'] 
       @completion_time = result_data['jobStatus'].first['status'].first['completionTime'] 
       rescue 
       @collection_time += 60 
        return false 
       end 
      else 
       @ok = false 
      end 

      true 
     end 

     def ok? 
      @ok == true 
     end 

     def wait_until_ready 
      sleep 1 until ready? 
     end 

     private 

     def do_request(body) 
      api_url = URI.parse(@@api_baseurl) 
      request = Net::HTTP::Post.new(api_url.path) 
      request.body = body 
      Net::HTTP.new(api_url.host, api_url.port).start {|h| h.request(request) } 
     end 
    end 

    url = 'http://www.rubyinside.com/' 
    t = Nailer.new(url) 

    if t.ok? 
     t.wait_until_ready 
     t.retrieve_to_file('out1.jpg', :small) 
     t.retrieve_to_file('out2.jpg', :medium) 
     t.retrieve_to_file('out3.jpg', :medium2) 
     t.retrieve_to_file('out4.jpg', :large) 
     puts "Thumbnails saved" 
    else 
     puts "Error" 
    end 

답변

0

lib 디렉토리는 그런 유틸리티 코드를위한 좋은 장소입니다.

0

나에게 당신이 lib/nailer.rb 파일의 lib/디렉토리에 똑바로 놓을 수있는 것처럼 보입니다. 그러면 가야합니다. lib /가 레일스 애플리케이션의로드 경로에 있으므로 특정 파일의 맨 위에있는 "require 'nailer'"의 단순한 이름 공간으로 클래스를 가져와야합니다.

도 app/models에 넣을 수 있습니다. ActiveRecord가 아닌 모델을 넣어도 괜찮습니다. 이것은 도메인의 데이터 모델이 아니기 때문에 lib /가 아마도 더 나은 곳이라고 생각합니다.

3

lib/nailer.rb에 넣으십시오. 잘하겠습니다. Rails의 자동 로딩을 사용하면 구성이나 필요없이 Nailer.new(...) 등을 사용할 수 있습니다.

+0

감사합니다. 나는 그것을 시도하고 돌아올 것입니다. – Autodidact