Slots plugin
Posted by Nucc
I’d like to share my last Rails plugin which add comfortable management for remote_calls. I have a work for developing a photo manager. It needs a lot of remote call for change for example the name of the album, upload photo, remove uploaded photos from the div tree, rotate image without reload the whole page. The currently solution in rails like this:
/app/view/photo/index.rhtml
-
<div id="photo_1"></div>
-
<div id="photo_2"></div>
-
<%= link_to_remote "Rotate Photo 1",
-
:url => {:action => "rotate", :id => "1"} %>
/app/controllers/photo_controller.rb:
-
class PhotoController < ApplicationController
-
def index
-
end
-
-
def rotate
-
@photo = Photo.find_by_id(params[:id])
-
@photo.rotate(90)
-
@photo.save!
-
render :update do |page|
-
page["photo_1"].replace_html :partial => "photo",
-
:object => @photo
-
end
-
rescue
-
end
-
end
If we have a lot of link_to_remote for different methods, we have to write render :update .. for each one. The other problem, what happens if one of my action try to call another action. For example, always when I rotate an image, I’d like to share with the user what happens (flash a div element, with “Photo rotated” message). If I write another method for flashing message, it would be double rendering. If I write a helper method, I should always pass the page parameter, and if the message use my params[], I should pass it too. I have a solution for this problem.
Install this plugin in your Rails framework.
script/plugin install https://svn.bteam.hu/plugins/slots/trunk/
Let’s look the changes
/app/view/photo/index.rhtml
-
<div id="message"></div>
-
<div id="photo_1"></div>
-
<div id="photo_2"></div>
-
<%= link_to_remote "Rotate Photo 1",
-
:url => {:action => "rotate", :id => "1"} %>
/app/controllers/photo_controller.rb:
-
class PhotoController < ApplicationController
-
slots :rotate, :message
-
-
def index
-
end
-
-
end
/app/helpers/photo_helper.rb
-
class PhotoHelper
-
def rotate
-
@photo = Photo.find_by_id(params[:id])
-
@photo.rotate(90)
-
@photo.save!
-
-
page["photo_1"].replace_html :partial => "photo",
-
:object => @photo
-
message("Photo was rotated by 90 degree")
-
#Or we can use
-
# message("Photo #{params[:id]} was rotated by 90 degree")
-
rescue
-
end
-
-
def message(msg)
-
page["message"].replace_html :partial => "message",
-
:object => msg
-
end
-
end
As you see, I put our remote called methods into helper. It’s necessary because only helpers can change our views. If we want to use the params hash in the message method, we can do this.
In controllers, when we call slots method, it generates a method with the same name as the slot, so we can use before_filter for this methods.
Enjoy it!