原代码:
def self.user_admin_links
ADMIN_PAGES.inject([]) do |result, page|
result << Page.new(controller: page[:name]) if page[:menu] && (page[:group_admin] || page[:company_admin])
result
end
end
def self.super_admin_links
ADMIN_PAGES.inject([]) do |result, page|
result << Page.new(controller: page[:name]) if page[:super_admin]
result
end
end
我试图像这样重构:
array_builder = Proc.new do |conditional|
ADMIN_PAGES.inject([]) do |result, page|
result << Page.new(controller: page[:name]) if conditional
result
end
end
def self.user_admin_links
array_builder.call(page[:menu] && (page[:group_admin] || page[:company_admin]))
end
def self.super_admin_links
array_builder.call(page[:super_admin])
end
但我得到这个错误:
Error: undefined local variable or method `array_builder' for Page:Class.
当我把 array_builder 变成一个类方法时,像这样:
def self.array_builder
Proc.new do |conditional|
ADMIN_PAGES.inject([]) do |result, hsh|
result << Page.new(controller: hsh[:name]) if conditional
result
end
end
end
我在 self.user_admin_links 方法中收到一个错误,即“页面”无法识别。