使用Rails 4

时间:2016-06-01 20:37:15

标签: ruby-on-rails ruby

我正在使用gritter gem在我的rails应用程序中显示简单的通知。在我的控制器中,我使用gflash方法,稍后在视图中添加通知:

gflash notification: "Welcome to my awesome website!"

现在问题是我正在为移动设备制作完全不同的视图,我需要覆盖this method which is located in the Gflash module。我想要的是这样的东西:

If the browser is a mobile browser
  Do this
else
  Use the original gflash method in Gritter::Gflash
end

所以我在config / initializers / custom_gritter.rb中添加了一个初始化器:

Gritter::Gflash.module_eval do
    def gflash *args
            @@mobile_notifications == [] ? @@mobile_notifications.push(args[0][:notice]) : @@mobile_notifications = [args[0][:notice]]
    end

    def self.mobile_notifications
        @@mobile_notifications ||= []
    end

    def self.reset_mobile_notifications
        @@mobile_notifications = nil
    end
end

这使我可以在我的控制器或视图中访问用户通知,并且工作正常:

Gritter::Gflash.mobile_notifications

但是我仍然必须确保它仅在用户拥有移动设备时才会覆盖,因此我将custom_gritter.rb文件更改为:

Gritter::Gflash.module_eval do
    alias_method :original_gflash, :gflash
    def gflash *args
        puts "override works"
        if browser.mobile?
            puts "detected mobile browser"
            @@mobile_notifications == [] ? @@mobile_notifications.push(args[0][:notice]) : @@mobile_notifications = [args[0][:notice]]
        else
            original_gflash
        end
    end

    def self.mobile_notifications
        @@mobile_notifications ||= []
    end

    def self.reset_mobile_notifications
        @@mobile_notifications = nil
    end
end

在我的终端中,我看到“覆盖工作”,但我没有看到“检测到的移动浏览器”,这意味着该条件不起作用。 browser.mobile?方法由browser gem提供。我还用过is_mobile_request?来自the mobylette gem的方法,但我有完全相同的问题。

为什么不工作?模块是否可以访问其他gem中的方法?这是解决我问题的不好方法吗?任何建议/想法将不胜感激,提前感谢!

更新:我没有错误,这意味着即使我在移动设备上打开浏览器(使用Chrome),它也会认为browser.mobile?为假。我可以通过在我的终端中出现的else语句之后添加puts "not mobile browser"来确认这一点。

知道为什么browser.mobile?在控制器中返回true而在此模块中为false?

0 个答案:

没有答案