在 Ruby on Rails 中阻止调用 [英] Block call in Ruby on Rails

查看:49
本文介绍了在 Ruby on Rails 中阻止调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清理我的代码并摆脱很多丑陋的哈希值.在我看来,我定义了几个这样的操作:

I'm trying to clean up my code and get rid of a lot of ugly hashes. In my views I define several actions like this:

@actions = {
  :interest => {'Show interest', link_to(..), :disabled => true},
  :follow   => {'Follow this case', link_to(..)}
  ...
}

随着这些哈希值的增长,可维护性降低.我想将上述格式转换为类似的格式:

As these hashes grow, the maintainability decreases. I want to convert the above format to something like:

actions do
   item :interest, 'Show interest', link_to(..), :disabled => true
   item :follow,   'Follow',        link_to(..)
   ...
end

我如何构建我的辅助方法以允许这样做?'item' 方法最好只在 'actions' 块中可用,而不是在全局范围内.

How do I structure my helper methods to allow this? Preferably the 'item'-method should only be available in the 'actions' block and not in the global scope.

谢谢!

推荐答案

我认为这种技术被称为洁净室",其中您有一个匿名对象,其中包含您要调用的方法,以便该方法仅可用从您的区块内:

i think this technique is called a 'clean room', where you have an anonymous object that contains the method you want to call so that the method is only available from within your block:

def actions(&block)
  cleanroom = Class.new{
    def item(*args)
      puts "these args were passed in: #{args.inspect}"
    end
  }
  cr = cleanroom.new
  cr.instance_eval &block
end

当然这个item"方法只是放置一些文本,但你可以做任何你需要的.

of course this "item" method just puts some text, but you cando whatever you need.

actions do
  item "foo", "bar", "baz"
end  #=> these args were passed in: ["foo", "bar", "baz"]

这篇关于在 Ruby on Rails 中阻止调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆