2011-07-11 61 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

相关问题