2011-09-25 5 views
8

저는 bitly gem을 사용하고 있습니다. 도우미 메소드 (보기 및 메일러에서 URL을 생성하기 위해 호출하는) 내부의 비트 맵 API에 액세스하고 싶습니다.레일 : 컨트롤러 메서드 또는 인스턴스 변수 도우미 내부

가 (BTW이 할 수있는 더 적절한 장소가?) 기본적으로

class ApplicationController < ActionController::Base 
    before_filter :bitly_connect 

    def bitly_connect 
    Bitly.use_api_version_3 
    @bitly ||= Bitly.new(APP_CONFIG['bitly_username'], APP_CONFIG['bitly_api_key']) 
    end 
end 

내가 @bitly에 액세스 할 수 없습니다 :

나는 내와 ApplicationController에서이 방법의 API 연결을 시작 내 조력자들. 그 방법을 제안 할 수 있습니까?

내가 찾은 유일한 관련 스레드는 도움이되지이었다 Rails 3 and Controller Instance Variables Inside a Helper

감사합니다.

답변

9

레일은 관습에 따라 컨트롤러 동작 (및 필터)에 설정된 인스턴스 변수를 뷰에 전달합니다. 도우미 메서드는 이러한 뷰에서 사용할 수 있으며 컨트롤러 액션 내에서 설정 한 인스턴스 변수에 액세스 할 수 있어야합니다. 의 배치와 우려 사항에 관해서는 http://ruby-doc.org/core/classes/Object.html#M001028

# app/controllers/example_controller.rb 
class ExampleController 
    def index 
    @instance_variable = 'foo' 
    end 
end 

# app/helpers/example_helper.rb 
module ExampleHelper 
    def foo 
    # instance variables set in the controller actions can be accessed here 
    @instance_variable # => 'foo' 
    # alternately using instance_variable_get 
    variable = instance_variable_get(:@instance_variable) 
    variable # => 'foo' 
    end 
end 

:

또는, 당신은, 또는 개체 #의 instance_variable_get 방법을 사용하여 메소드에 변수를 전달하여 도우미 메서드 내부의 지역 변수를 설정할 수 있습니다 논리, 그것이 컨트롤러에 속한 것처럼 보이지 않습니다. 컨트롤러를 애플리케이션의 라우팅 요청으로 생각하십시오. 대부분의 논리는 모델 클래스 내에서 수행되어야합니다. "스키니 컨트롤러, 지방 모델."당신이 도우미로 액세스 할 수 있도록 컨트롤러 방법이 필요하면 http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model

2

, 당신이 아무튼 그래서 나는 또한, 방법을 변경 helper_method

class ApplicationController < ActionController::Base 
    helper_method :bitly_connect 

    def bitly_connect 
    @bitly ||= begin 
     Bitly.use_api_version_3 
     Bitly.new(APP_CONFIG['bitly_username'], APP_CONFIG['bitly_api_key']) 
    end 
    end 
end 

주를 사용할 수 있습니다 호출 할 때마다 Bitly.use_api_version_3으로 전화하십시오.

벤 심슨 (Ben Simpson)이 지적했듯이이 모델을 모델로 옮겨야합니다.