2011-07-11 59 views
1

我正在修改Rails的MobileFu插件(https://github.com/brendanlim/mobile-fu)以接受是否打開插件的參數。將變量傳遞給Rails控制器方法

在控制器,你可以調用類似:

class ApplicationController < ActionController::Base 
    has_mobile_fu 
end 

但我想這樣做:

class ApplicationController < ActionController::Base 
    has_mobile_fu :mobile_enabled 

    def mobile_enabled 
    current_account.mobile_enabled? 
    end 
end 

凡current_account由一個子集查找。問題是,當我通過:mobile時,它只傳遞符號,而不是:mobile的值。

下面是相關MobileFu代碼:​​

這是我的編輯:

def has_mobile_fu(enabled, options = {}) 
    include ActionController::MobileFu::InstanceMethods 

    logger.info "Enabled is: " + enabled.to_s 

    before_filter(options) do |controller| 
    controller.set_mobile_format(enabled) 
    end 

    helper_method :is_mobile_device? 
    helper_method :in_mobile_view? 
    helper_method :is_device? 
end 

如果我把這個與控制器的靜態參數(即has_mobile_fu(false)),它工作正常。這是當我試圖傳入一個變量(即has_mobile_fu :mobile_enabled)時,我遇到了麻煩。變量只是進來作爲一個符號(所以上述記錄器輸出將Enabled is: mobile_enabled

謝謝!

+0

ideaoforder - 記得投票和/或接受幫助或解決您的問題的解決方案。這樣人們在將來也會更有可能幫助你。謝謝! – Casper

回答

0

這是一個想法的草圖。我總是喜歡使方法「聰明」。所以方法的用戶(你)不需要考慮太多。它應該只是工作。考慮到這一點:

# 1: Modify has_mobile_fu to something like this: 
def has_mobile_fu(enabler = false, &block) 
    include ActionController::MobileFu::InstanceMethods 
    enabler = block if block_given? 

    case enabler 
    when Proc 
    # Determine if we enable or not by calling proc 
    before_filter { |controller| 
     controller.set_mobile_format if enabler.call(controller) 
    } 
    when Symbol 
    # Call the method named by the symbol instead 
    before_filter { |controller| 
     controller.set_mobile_format if controller.send(enabler) 
    } 
    # Old behaviour below 
    when true 
    before_filter :force_mobile_format 
    else 
    before_filter :set_mobile_format 
    end 

    # Rest is like the old method... 
    ... 
end 

隨着你使用這樣上面的設置:

class ApplicationController < ActionController::Base 

    # The old way 
    has_mobile_fu 

    # The old way, forcing mobile format 
    has_mobile_fu true 

    # The new way using a symbol that signifies a method to call 
    # to determine if we're enabling or not 
    has_mobile_fu :mobile_enabled 

    # The new way using an in-line proc method 
    has_mobile_fu { |controller| controller.mobile_enabled } 

    def mobile_enabled 
    ... 
    end 
end 

這樣,它「只是工程」。它是向後兼容的,如果你提供了一個符號或者一個proc,那麼它們會被用來作爲方法被調用來檢查是否啓用。

注意..代碼沒有經過測試,但希望你能得到一般想法。

編輯:簡化了代碼有點...

+0

謝謝卡斯帕爾 - 這工作完美! – ideaoforder

0

那麼這裏有一個有點混亂。

  • 當你在你的控制器定義has_mobile_fu ,這是一個類的方法,而不是一個實例一個

  • 當你想成參數傳遞給方法,認爲這是一個哈希:has_mobile_fu :mobile_enabled => "somevalue"

所以在你的方法定義,如果您有:

def has_mobile_fu args 

你就可以得到使用args[:mobile_enabled]

最後的價值,因爲你想獲得取決於current_account值,考慮通過一個Lambda。

+0

對不起,我看不懂,你能編輯你的問題嗎? – apneadiving

+0

對不起 - 嘗試 - 我很難格式化我的評論。 – ideaoforder

+0

只需編輯您的問題:) – apneadiving

相關問題