2

The below is a snippet of code from the OpenProject open source project. I am at a loss at what this ruby code is doing and going through ruby documentation has not helped.

The manage method is being invoked by the code in the initializer, but I'm not sure what the argument being passed in is.

Using a debugger, when I look at the content of 'item' in the manage method, it simply says, :block.

CAn someone explain or refer me to some documentation that would explain how manage is being invoked?

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

4

1 回答 1

2

The arguments being passed to manage are :blocks, and a block.

The yield, just yields control to the block that was passed in as an argument.

yield is being called with homescreen[item] where item equals :blocks.

So yield will just pass homescreen[:blocks] to the block.

The code ends up doing this:

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? } }
    )
于 2015-10-29T23:03:45.630 回答