link_to_block in Rails?
Ever since Seaside was featured in Ruby On Rails podcast, I was wondering if there's any use for having a link_to_block method...
<% variable = Time.now %>
<%= link_to_block("Click me to execute a block of code") do |c|
c.render(:text => "Time.now = \"#{Time.now}\"<br />variable = \"#{variable}\"")
end %>
I guess the only way to find out is to have it available first...
# paste everything into app/controllers/application.rb
# to empower all your controllers
# all links generated by 'link_to_block' goes here
def continued
# should probably use Drb Hash object instead of global variable $PROCHASH
if $PROCHASH and $PROCHASH[@session.session_id] and
(block = $PROCHASH[@session.session_id][params[:id]]) and
block.respond_to?(:call)
block.call(self)
else
raise "No block to continue for '#{params[:id]}'"
end
end
# similar to 'link_to', but accepts a block of code instead of URL/HTTP options
# when clicked, the block is executed
def link_to_block(text, &block)
# should probably use Drb Hash object instead of global variable $PROCHASH
$PROCHASH ||= Hash.new(:created_at => Time.now)
action_name = text.to_sym.to_s
$PROCHASH[@session.session_id] ||= Hash.new
$PROCHASH[@session.session_id].merge!({
action_name => Proc.new(&block),
})
# we do have to remember to house-keep this hash... someday
url = url_for(:action => 'continued', :id => action_name)
"<a xhref=\"#{url}\">#{CGI.escapeHTML(text)}</a>"
end
# makes it accessible within views (e.g. rhtml)
helper_method :link_to_block
An example of clicking a link_to_block and seeing the variable in the block...