在Rails中创建动态助手方法 [英] creating dynamic helper methods in rails

查看:62
本文介绍了在Rails中创建动态助手方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一堆像这样的动态助手方法:

I am trying to create a bunch of dynamic helper methods like these:

show_admin_sidebar
show_posts_sidebar
show_users_sidebar

到目前为止,我的helper.rb文件中有此文件:

So far I have this in my helper.rb file:

#spits out a partial 
def show_sidebar(name, show_sidebar = true)
  @content_for_sidebar = render :partial => "partials/#{name}"                       
  @show_sidebar = show_sidebar
end

def show_sidebar?
  @show_sidebar
end

在我的应用程序布局文件中,我有这个:(注意-我正在使用HAML):

In my application layout file I have this: (NB - I'm using HAML):

- if show_sidebar?
  = yield(:sidebar)

这使我可以发表以下看法:

This allows me to say the following in my views:

- show_sidebar(:foo)
- show_sidebar(:bar)

这将呈现所需的局部.

此问题是每页只能添加一个侧边栏.因此,我认为我需要动态方法,例如:show_admin_sidebar,show_foo_sidebar.

The problem with this is that I can only add one sidebar per page. So, I figure I need to have dynamic methods like: show_admin_sidebar, show_foo_sidebar.

所以我试图做到这一点:

So I have tried to do this:

def show_#{name}_sidebar(show_sidebar = true)
@name = name  
@content_for_#{@name}_sidebar = render :partial => "partials/#{@name}"                       
  @show_sidebar = show_sidebar
end

,然后在我的布局中:

- if show_sidebar?
  = yield("{@name}_sidebar")

但是Rails根本不喜欢这样.

But rails does not like this at all.

我已经尝试了几乎所有可以在帮助文件中想到的所有内容,但没有任何效果.

I have tried almost everything I can think of in my helper file and nothing works.

之所以使用辅助方法是因为我希望我的内容div的页面宽度为100%,除非存在侧边栏,在这种情况下,主要内容将进入较小的div,侧边栏内容将进入其自身..

The reason I am using helper methods for this is because I want my content div to be 100% page width unless there is a sidebar present in which case the main content goes into a smaller div and the sidebar content goes into it's own..

如果无法正常工作,则可以通过手动添加局部零件轻松解决此问题,但是我想解决这个问题.

If I can't get this working, then I can easily fix the problem by just adding the partials manually but I'd like to get my head round this....

任何人都对这种事情有经验吗?

Anyone got any experience with this kind of thing?

推荐答案

这是为您提供的解决方案,但是我不建议过多的元编程:

Here is a solution for you, however I wouldn't suggest too much metaprogramming:

#Add the following snippet to the proper helper module:
['admin','user','whatever'].each do |name|
  class_eval{
    "def show_#{name}_sidebar(show_sidebar = true)
       @name = #{name}  
       @content_for_#{@name}_sidebar = render :partial => 'partials/#{@name}'                       
       @show_sidebar = show_sidebar
     end"
  }
end

这篇关于在Rails中创建动态助手方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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