Never been to DZone Snippets before?

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

About this user

Duane Johnson http://blog.inquirylabs.com/

« Newer Snippets
Older Snippets »
Showing 11-13 of 13 total

Autoinclude CSS Files by Controller/Action Name

def stylesheet_auto_link_tags
  stylesheets_path = "#{RAILS_ROOT}/public/stylesheets/"
 
  candidates = [ "#{controller.controller_name}", 
                 "#{controller.controller_name}_#{controller.action_name}" ]
 
  candidates.inject("") do |buf, css| 
    buf << stylesheet_link_tag(css) if FileTest.exist?("#{stylesheets_path}/#{css}.css")
    buf
  end
end


Compliments of Dema

Note: Anyone interested in this might also be interested in the bundled_resource plugin (google for it).

Render a partial to an instance variable

Normally, if you call "render_partial" within a controller, nothing but the partial will be rendered.

Occasionally, it is useful to render a partial to an instance variable as a string so that the view can still be rendered as normal, and the string can be passed in to the view.

  add_variables_to_assigns
  @content_for_navbar = @template.render_partial 'layouts/public_navbar'

Paginate an already-fetched result set (i.e. collection or array)

Sometimes it's nearly impossible to paginate a result set using the built-in :limit and :offset parameters of find(:all). Instead, you can fetch a complicated query and paginate the results afterward.

Add the following to application.rb:

  def paginate_collection(collection, options = {})
    default_options = {:per_page => 10, :page => 1}
    options = default_options.merge options
    
    pages = Paginator.new self, collection.size, options[:per_page], options[:page]
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end


Call it from within your action like this:
@pages, @users = paginate_collection User.find_custom_query, :page => @params[:page]
« Newer Snippets
Older Snippets »
Showing 11-13 of 13 total