Skip to content

Instantly share code, notes, and snippets.

@ramontayag
Created July 23, 2011 07:16
Show Gist options
  • Save ramontayag/1101138 to your computer and use it in GitHub Desktop.
Save ramontayag/1101138 to your computer and use it in GitHub Desktop.
How I setup my Apotomo widgets

Your app/widgets directory can get crazy pretty fast. If you're learning Apotomo, then you'll probably move things around and try many ways to order your widgets directory. This is not so much about that - I still haven't found a good way to organize my widgets, but I've found a way to keep the widget classes themselves DRY.

Create an ApplicationWidget just like Rails' ApplicationController

And it should look something like this:

# A BaseWidget to apply stuff to widgets across
# the board. All widgets should inherit from this
class ApplicationWidget < Apotomo::Widget
  include ActionController::RecordIdentifier # so I can use `dom_id`
  # include Devise::Controllers::Helpers # if you use devise
  helper_method :current_user # so I can call current_user in the views of my widgets
  helper_method :current_site # so I can call current_site in the view of my widgets
  helper ::ApplicationHelper
  helper ::SomeOtherHelper
  after_initialize :setup!

  private

  # This is called by the after_initialize
  # Any variables that are passed in from the parent of the widget go in here.
  # Since I scope things by "site" (or scope by "account"), I need to pass it in
  # all the time.
  def setup!(*)
    @current_site ||= options[:current_site]
  end

  # Do you scope by an account?
  # You have to pass it into the widget from your controller though:
  #   MyController < ApplicationController
  #     has_widgets do |root|
  #       root << widget(:my_widget, :current_site => current_site)
  #     end
  #   end
  def current_site
    @current_site
  end

  # Do you use cancan? Uncomment this:
  #def current_ability
  #  ::Ability.new current_user
  #end
end

That makes your widgets much slimmer

A typical widget will contain a lot less code, and be something like:

class Image::Inserter::UploadWidget < ApplicationWidget
  responds_to_event :insert

  def display
    render
  end

  def insert(event)
    @image = current_site.images.find event[:image_id]
    render :view => :insert
  end

  private

  def setup!(*)
    # Your own widget-specific set up here
    # But call `super options` after to call
    # ApplicationWidget#setup! method
    super options
  end
end

Comments?

Fork this! Make this guide better. That's why it's a gist after all.

@regdog
Copy link

regdog commented Feb 7, 2012

pretty good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment