DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

WillPaginate RemoteLinkRenderer

07.08.2008
| 4353 views |
  • submit to reddit
        // overrides the normal willpaginate link renderer for use with Ajax Requests and the tiny_mce_plus plugin

class RemoteLinkRenderer < WillPaginate::LinkRenderer
  def page_link_or_span(page, span_class = 'current', text = nil)
    text ||= page.to_s
    # RAILS_DEFAULT_LOGGER.error "DEBUG: page: #{page.inspect}"
    if page and page != current_page
      @template.link_to_remote text, :url => url_for(page), :method => :get
    else
      @template.content_tag :span, text, :class => span_class
    end
  end
  
  # Returns URL params for +page_link_or_span+, taking the current GET params
  # and <tt>:params</tt> option into account.
  def url_for(page)
    RAILS_DEFAULT_LOGGER.error "DEBUG: page: #{page.inspect}"
    page_one = page == 1
    unless @url_string and !page_one
      @url_params = {}
      # page links should preserve GET parameters
      stringified_merge @url_params, @template.params if @template.request.get?
      stringified_merge @url_params, @options[:params] if @options[:params]
      RAILS_DEFAULT_LOGGER.error "DEBUG: #{param_name.to_s}"
      if complex = param_name.to_s.index(/[^\w-]/)
        page_param = (defined?(CGIMethods) ? CGIMethods : ActionController::AbstractRequest).
          parse_query_parameters("#{param_name}=#{page}")
        
        stringified_merge @url_params, page_param
      else
        @url_params[param_name] = page_one ? 1 : 2
      end
      RAILS_DEFAULT_LOGGER.error "DEBUG: #{@url_params.inspect}"
      url = @template.url_for(@url_params)
      RAILS_DEFAULT_LOGGER.error "DEBUG: url: #{url.inspect}"
      return url if page_one
      
      if complex
        @url_string = url.sub(%r!((?:\?|&)#{CGI.escape param_name}=)#{page}!, '\1@')
        return url
      else
        @url_string = url
        @url_params[param_name] = 3
        @template.url_for(@url_params).split(//).each_with_index do |char, i|
          if char == '3' and url[i, 1] == '2'
            @url_string[i] = '@'
            break
          end
        end
      end
    end
    # finally!
    @url_string.sub '@', page.to_s
  end
  
  # Recursively merge into target hash by using stringified keys from the other one
  def stringified_merge(target, other)
    target = target.stringify_keys
    other = other.stringify_keys
    other.each do |key, value|
      existing = target[key]

      if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?)
        stringified_merge(existing || (target[key] = {}), value)
      else
        target[key] = value
      end
    end
  end
end