2011-05-25 81 views
1

这是我的控制器。因为控制器包含逻辑通过API来推动一个HTML字符串,而该HTML包含链接,面临的挑战之一是代表一个的link_to辅助的输出:如何让我的控制器更加干爽 - 我想使用控制器内的帮助器 - Rails 3

client = LinkedIn::Client.new(ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET']) 
57  client.authorize_from_access(current_user.atoken, current_user.asecret) 
58  public_profile_url = client.profile(:fields => "public-profile-url").public_profile_url 
59  string = "<a href='#{public_profile_url}'>#{current_user.full_name}</a> has shared: " 
60  string = string + "<a href = 'http://www.domain.com/question/#{@question.id}'>#{@question.title}</a>" 
61  #<a href='http://www.domain.com/review/#{@review.id}'>#{@review.title}</a> " 
62  debugger 
63  client.update_network(string) 

这组代码是相同的,但所用对于其他资源,所以我想将这个全部DRY作为控制器内部使用的单个模块。

我试图把它放进一个帮手,但根本没有用:ssaid的帮手方法是无法识别的。

回答

2

Railscast 132说明如何在控制器内部使用helper方法(如link_to)。

3

我会将HTML放入部分内容中,然后在控制器中使用render_to_string将其呈现并发送至LinkedIn。你也可以在你的控制器中包含相关的Helper模块,但这有点违反MVC原则,所以我建议使用其他方法。

上面的答案等同于包含相关的Helper模块,但是,保持视图和控制器分离会更好一点。你的控制器应该很薄,很轻。控制器只是一个调度程序,它并不真正“做”任何事情,它只是通过事情来完成任务。如果以这种方式保留它,在动作和控制器之间共享功能非常容易。

+0

即使我可以同意这一点,比我的解决方案更清洁 – 2011-05-25 23:29:11

+0

好吧....所以我会创建一个单独的文件_linkedin_message.erb .html作为一个部分,然后我如何呈现字符串?感谢这看起来像一种方式去,但我不熟悉它。 – Angela 2011-05-27 16:33:26

+0

您将呈现为正常的部分,当您需要所有该消息的HTML时,尝试使用render_to_string“users/linkedin_message”,:layout => false。 – 2011-05-28 02:47:50

1

如果我理解正确,你说你在其他资源中反复使用相同的(或类似的)代码块。

一种方法使用相同的代码是只让一个方法是在ApplicationController中(你基本上定义一个辅助方法,但在ApplicationController中定义它干起来。

class ApplicationController < ActionController::Base 
    ... 

    # The following line makes the method available in the views, too. 
    helper_method :the_new_method 

protected 
    def the_new_method(args) 
    # Put your code here 
    end 
end 

但是,像其他人所说,这可能是最好的部分。

+0

所以我可以把代码实例化LinkedIn客户端和所有这些东西作为控制器中的方法?并在部分使用teh html片段?或者它是一个还是另一个? – Angela 2011-05-27 16:34:21

+0

这是两个。因为它是在ApplicationController中声明的,所有控制器都可以使用该方法。 'helper_method:the_new_method'这一行也使它在视图/部分中可用。 – venables 2011-05-27 16:55:37