This is my controller. Because the controller contains the logic to push an HTML string through an API, and that HTML contains links, one of the challenges is representing the output of a link_to helper:
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)
This set of code is the same but used for other resources, so I'd like to make this all DRY as a single module used inside the controller.
I tried putting it inside of a helper, but that didn't work at all: ssaid the helper method was unknwn.
I would put the HTML inside a partial, and then use render_to_string
in the controller to render it and send it up to LinkedIn. You could also include the relevant Helper modules in your controller, but that's kinda against MVC principles so I'd recommend the other method instead.
The answer above is equivalent to including the relevant Helper modules, however, it's a little nicer to keep views and controllers separate. Your controllers should be thin and light. The controller is just a dispatcher, it doesn't really "do" anything, it just passes things around to make things happen. If you keep it this way, it's very easy to share functionality between actions and controllers.
Railscast 132 Shows how you can use helper methods like link_to inside the controller.
If I understand correctly, you're saying you use that same (or similar) block of code over and over in other resources.
One way to DRY it up using that same code would be to just make a method for it in the ApplicationController (you're essentially defining a helper method, but defining it in the 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
But, like others have said, this is probably best to be placed in a partial.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.