2014-10-22 4 views
-2

루비와 opensshift에 익숙하지 않아서 무엇을하고 있는지 잘 모르겠습니다.Ruby 정의되지 않은 메서드`[] 'for nil : 메서드 호출 전의 NilClass (NoMethodError)

루비 코드를 git으로 푸시하고 빌드를 시작하면이 오류가 발생합니다. NilClass (NoMethodError) :이 오류가 발생 후 내가 다시 올바른 평가를 얻고 있지만, 인터프리터는 정의되지 않은 메서드`[] '무기 호에 던지고 원인

remote: Building Ruby cartridge 
remote: /var/lib/openshift/234325h2345234523452/app-root/runtime/repo/GetMovieRTRating.rb:23:in `Rating': undefined method `[]' for nil:NilClass (NoMethodError) 
remote:   from /var/lib/openshift/234325h2345234523452/app-root/runtime/repo/createCinemaTweets.rb:74:in `Run' 
remote:   from /var/lib/openshift/234325h2345234523452/app-root/runtime/repo/Driver.rb:5:in `<top (required)>' 
remote:   from /opt/rh/ruby193/root/usr/share/rubygems/rubygems/custom_require.rb:36:in `require' 
remote:   from /opt/rh/ruby193/root/usr/share/rubygems/rubygems/custom_require.rb:36:in `require' 
remote: going to call rating 0 "Teenage%20Mutant%20Ninja%20Turtles", 2014 
remote: Got the rating from the script: 22% 
remote: going to call rating 1 "Teenage%20Mutant%20Ninja%20Turtles", 2014 
remote: Got the rating from the script: 22% 
remote: going to call rating 2 "The%20Maze%20Runner", 2014 
remote: Got the rating from the script: 63% 
remote: going to call rating 3 "The%20Maze%20Runner", 2014 
remote: Got the rating from the script: 63% 
remote: going to call rating 4 "The%20Maze%20Runner", 2014 
remote: Got the rating from the script: 63% 
remote: going to call rating 5 "Gone%20Girl", 2014 
remote: An error occurred executing 'gear postreceive' (exit code: 1) 
remote: Error message: CLIENT_ERROR: Failed to execute action hook 'build' for application 
remote: 
remote: For more details about the problem, try running the command again with the '--trace' option. 

평가 방법이 작동 않습니다. 나는 이것이 다른 방법으로 돌지 않는 한 실패한 액션 훅 빌드를 일으키는 것으로 추정한다. 이 클래스

class Rotten 

def Rating(movie="terminator", year=1984)  
    @rottenKey="<key>" 
    @movie = movie.gsub(/\"/i, '') 
    @requiredYear = year.to_i 

    @url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=#{@movie}&page_limit=50&apikey=#{@rottenKey}" 

    resp = Net::HTTP.get_response(URI.parse(@url)) 
    data = resp.body 

    @i=0 
    @parsedData = JSON.parse(data)['movies'] 

    while @i < 50 do 
     @foundYear = @parsedData[@i]['year'].to_i 
     @rating = @parsedData[@i]['ratings']['critics_score'] 

     @i +=1 
     if @foundYear - @requiredYear == 0 then 
     return "#{@rating}%" 
     end 
    end 
end 
end 

되고

을한다는 것이다 나는

@rating = Rotten.new.Rating("#{@movieTitleURL}",@ratingYear)

감사

+0

대부분의 변수에 @를 사용하는 이유가 있습니까? – tomsoft

답변

0

나는이 @rating 기회에 대한 시도와 관련이있다 생각

와 다른 클래스에서 호출
@parsedData[@i]['ratings'] 
#=> nil 

nil[]을 호출 했으므로 실패합니다. 당신이 뭔가를 시도 할 수있는

class Rotten 
    @@rotten_key = "<key>" 
    def self.rating(movie="terminator", required_year=1984)  
    @movie = movie.gsub(/\"/i, '') 

    @url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=#{@movie}&page_limit=50&apikey=#{@@rotten_key}" 

    resp = Net::HTTP.get_response(URI.parse(@url)) 

    JSON.parse(resp.body)['movies'].take(50).find({ratings:{}})do |obj| 
     obj['year'].to_i == required_year.to_i 
    end['ratings']['critics_score'] 
    end 
end 

공지 사항 (루비 구문 snake_case하지 낙타 표기법로 작성)를 중요하지 않은 인스턴스 변수의 명명 규칙과 같은 몇 가지 청소 (내가 API 키가 없기 때문에 제가 테스트 할 수 있지만) 다음 . 당신은 내가 당신이라면 좀 더

class Rotten 
    attr_accessor :movie, :requested_year 
    @@rotten_key = "<key>" 
    @@rotten_url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?page_limit=50&apikey=#{@@rotten_key}" 

    def initialize(movie, requested_year) 
    @movie = movie.gsub(/\"/i, '') 
    @requested_year = requested_year 
    end 
    def ratings 
    movie_data['ratings'] || {} 
    end 
    def critics_score 
    ratings['critics_score'].to_i 
    end 
    def movie_data 
    @movie_data ||= get_movie_data 
    end 

    private 
    def get_movie_data 
     resp = Net::HTTP.get_response(URI.parse(@@rotten_url + "&movie=#{@movie}")) 
     JSON.parse(resp.body)['movies'].find({}){|movie| movie['year'].to_i == @year} 
    end 
end 

처럼 뭔가를하지만 더 조금이를 구축 할이 당신에게 인스턴스 변수, 예를 들어 내부에 더 액세스 권한을 부여합니다 Rotten.rating("movie name", year)

이것을 호출 할 수 있습니다

movie = Rotten.new('terminator',1984) 
movie.movie 
#=>'terminator' 
movie.requested_year 
#=> 1984 
movie.ratings 
#=>{'critics_score' => 89, 'some_other_score'=>67} 
movie.critics_score 
#=> 89 
movie.movie_data 
#=>{'ratings' => {'critics_score' => 89, 'some_other_score'=>67}, 'year' => 1984} 

나는 재미있는 문제처럼 보였다하지만 난 당신이 좋아하면 여기에서 일어나고있는 모든 것을 설명 드릴 것 같은이 대답에 도취 조금이라도했을 수 있습니다.

+0

적절한 루비에서 이것을 풀어 주셔서 감사합니다. 변경 사항을 구현하고 다시보고하겠습니다. 등급 방법을 호출하기 전에 내가 얻는 오류에 대해 의견을 말할 수 있습니까? –

+0

@JimmyCasey 오류가'GetMovieRTRating.rb'에서 23 행에 있다고 말합니다. 우리가보고있는 파일인지 여부는 알 수 없으므로 말하기 어렵습니다. 그러나 그 행을 보면, 'nil '을 반환하는 것에 대한 표시 – engineersmnky

+0

당신의 도움에 감사드립니다. 클래스 구조가 오류를 제거했습니다. –

관련 문제