我正在将一些项目移动到Rails,我想复制这个PHP代码:
http://www.php.net/manual/en/functions.anonymous.php#106046
到目前为止,我有这个:
def html (tag, id = "", hclass = "")
hopen = "<#{tag}"
hclose = "</#{tag}>"
unless id == ""
hopen += " id='"#{id}'""
end
unless hclass == ""
hopen += " class='"#{hclass}'""
end
hopen += ">"
return lambda { |data| print hopen,data,hclose}
end
我需要创建变量,如下所示:.PHP
$layout = array('container','header','pmain','lsidebar','rsidebar','footer');
foreach ($layout as $element)
$$element = html ("div", $element);
这是我的 RUBY 原型
layout = [:body, :header, :sidebar, :footer]
##I know this isn't right, but how do I create the dynamic functions like PHP???
layout.each {|x| instance_variable_set "@#{x}", 0 }
另外,我需要调用函数,没有调用方法可以做到这一点吗?如果我必须嵌套呼叫,它会很混乱。
h1 = html(:h1)
mainx = html(:div )
puts mainx.class
puts mainx.call(h1.call("Blog!"))
你在这里做了很多工作,但这里有一些关于过渡的帮助:
$layout = array('container','header','pmain','lsidebar','rsidebar','footer');
foreach ($layout as $element)
$$element = html ("div", $element);
据我所知,这是一个数组转换,所以等效的是这样的:
layout = [ @container, @header, @pmain, @lsidebar, @rsidebar, @footer]
layout.collect! do |element|
# Using the built-in content_tag method instead of
# the custom reimplementation with curried parameters.
content_tag("div", element)
end
Ruby 没有取消引用变量的方法,因为 Ruby 中的变量以完全不同的方式运行。实例变量保留在对象的上下文中,而变量仅在给定范围内保留。您可以按名称获取和设置任意实例变量,但通常不能对局部变量执行相同的操作。除了 eval { var }
之外,Ruby 中没有$$var
等价物,由于它如何评估潜在的任意代码,因此它真的很不受欢迎。
不过,我真的有一种不好的感觉,为什么你需要这样做。模板应该是解决必须在这个低级别争论事情的一种方式。
如果你是Ruby的新手,最好通读String和Array的文档,因为它们都充满了有用的方法。数组还包括可枚举模块,该模块添加了更多内容。
如果你在一个rails项目中,有很多帮助程序可以帮助你构建html
。实际上,有一个名为 **content_tag** 的帮助程序方法可以执行相同的操作。您可以在此处查看文档:http://apidock.com/rails/v3.1.0/ActionView/Helpers/TagHelper/content_tag
示例用法
content_tag(:tag_i_want, :id => 'my_id', :class => 'my_class') do
"the content I want inside the tag"
end
输出:
<tag_i_want id="my_id" class="my_class">the content I want inside the tag</tag_i_want>
第二个问题有点奇怪。多解释你想做什么。¿创建@body、@header、@sidebar和@footer变量?仅此而已?