Created
November 14, 2012 12:00
-
-
Save josevalim/4071747 to your computer and use it in GitHub Desktop.
Easy within
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This allows developers to pass an Active Model object | |
# to within, check and uncheck. This is very useful when | |
# used with `content_tag_for` since `content_tag_for` | |
# generates an unique dom id for each object. With this | |
# module, we can write: | |
# | |
# within comment do | |
# click_link "Destroy" | |
# end | |
# | |
# Or even better: | |
# | |
# click_link_within comment, "Destroy" | |
# | |
# Enabling or disabling roles based on checkboxes is also easy: | |
# | |
# check role | |
# | |
module ActiveModelWithin | |
def within(*args) | |
object, prefix = args | |
scope = if object.respond_to?(:to_model) | |
['#' + ActionController::RecordIdentifier.dom_id(object, prefix)] | |
else | |
args | |
end | |
super(*scope) | |
end | |
def click_link_within(scope, link) | |
within(scope) { click_link(link) } | |
end | |
%w(check uncheck).each do |method| | |
class_eval <<-RUBY, __FILE__, __LINE__ + 1 | |
def #{method}(*args) | |
if args[0].respond_to?(:to_model) | |
scope = ActionController::RecordIdentifier.dom_id(args[0], args[1]) | |
super(scope) | |
else | |
super | |
end | |
end | |
RUBY | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment