【问题标题】:Can someone explain to me how this ruby syntax works?有人可以向我解释一下这种 ruby​​ 语法是如何工作的吗?
【发布时间】:2015-10-29 22:54:09
【问题描述】:

以下是来自 OpenProject 开源项目的一段代码。我不知道这个 ruby​​ 代码在做什么,并且通过 ruby​​ 文档没有帮助。

初始化器中的代码正在调用 manage 方法,但我不确定传入的参数是什么。

使用调试器,当我在 manage 方法中查看 'item' 的内容时,它只是说,:block。

谁能解释或让我参考一些可以解释如何调用 manage 的文档?

require 'open_project/homescreen'

  OpenProject::Homescreen.manage :blocks do |blocks|
  blocks.push(
    { partial: 'welcome',
      if: Proc.new { Setting.welcome_on_homescreen? && !Setting.welcome_text.empty? } },
    { partial: 'projects' },
    { partial: 'users',
      if: Proc.new { User.current.admin? } },
    { partial: 'my_account',
      if: Proc.new { User.current.logged? } },
    { partial: 'news',
      if: Proc.new { !@news.empty? } },
    { partial: 'community' },
    { partial: 'administration',
      if: Proc.new { User.current.admin? } }
  )
end


module OpenProject
  module Homescreen
    class << self
      ##
      # Access a defined item on the homescreen
      # By default, this will likely be :blocks and :links,
      # however plugins may define their own blocks and
      # render them in the call_hook.
      def [](item)
        homescreen[item]
      end

      ##
      # Manage the given content for this item,
      # yielding it.
      def manage(item, default = [])
        homescreen[item] ||= default
        yield homescreen[item]
      end

      private

      def homescreen
        @content ||= {}
      end
    end
  end
end

open_project/homescreen.rb

【问题讨论】:

    标签: ruby-on-rails ruby openproject


    【解决方案1】:

    传递给manage 的参数是:blocks 和一个块。

    yield 只是将控制权交给作为参数传入的块。

    yield 被 homescreen[item] 调用,其中 item 等于 :blocks。

    所以yield 只会将homescreen[:blocks] 传递给块。

    代码最终会这样做:

    homescreen[:blocks].push (
        { partial: 'welcome',
          if: Proc.new { Setting.welcome_on_homescreen? && !Setting.welcome_text.empty? } },
        { partial: 'projects' },
        { partial: 'users',
          if: Proc.new { User.current.admin? } },
        { partial: 'my_account',
          if: Proc.new { User.current.logged? } },
        { partial: 'news',
          if: Proc.new { !@news.empty? } },
        { partial: 'community' },
        { partial: 'administration',
          if: Proc.new { User.current.admin? } }
        )
    

    【讨论】:

    • 谢谢。我不得不重新阅读一些关于块的引物以及你的解释,我认为它终于成功了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多