Added association_proc #38

Closed
wants to merge 1 commit into
from
Jump to file or symbol
Failed to load files and symbols.
+40 −3
Diff settings

Always

Just for now

View
@@ -205,6 +205,14 @@ Here are some other examples of the many possibilites to custom the output conte
<% end %>
```
+Optionally, if you want to wrap the inner part of the value with some text
+(e.g. adding quotes), you can do so by specifying a proc for `ShowFor.association_proc`
+that will be called with any association text. E.g.:
+
+```ruby
+ ShowFor.association_proc = lambda { |association, t| "'#{t}'" }
+```
+
## Maintainers
* José Valim (http://github.com/josevalim)
@@ -34,4 +34,8 @@
# If you want to wrap the text inside a label (e.g. to append a semicolon),
# specify label_proc - it will be automatically called, passing in the label text.
# config.label_proc = lambda { |l| l + ":" }
+
+ # If you want to wrap the text of an association value (e.g. wrap with quotes),
+ # specify association_proc - it will be automatically called, passing in the association text.
+ # config.association_proc = lambda { |association, t| "'#{t}'" }
end
View
@@ -44,10 +44,13 @@ module ShowFor
mattr_accessor :association_methods
@@association_methods = [ :name, :title, :to_s ]
-
+
mattr_accessor :label_proc
@@label_proc = nil
+ mattr_accessor :association_proc
+ @@association_proc = nil
+
# Yield self for configuration block:
#
# ShowFor.setup do |config|
@@ -46,7 +46,12 @@ def values_from_association(association, options) #:nodoc:
end
method = options.delete(:using) || ShowFor.association_methods.find { |m| sample.respond_to?(m) }
- association.is_a?(Array) ? association.map(&method) : association.try(method)
+
+ association.is_a?(Array) ? association.map{ |a| apply_association_proc(a, method) } : apply_association_proc(association, method)
+ end
+
+ def apply_association_proc(association, method)
+ ShowFor.association_proc ? template.instance_exec(association, association.try(method), &ShowFor.association_proc) : association.try(method)
end
end
-end
+end
View
@@ -69,4 +69,21 @@ class AssociationTest < ActionView::TestCase
assert_select "div.show_for p.wrapper p.collection span", "Tag 2"
assert_select "div.show_for p.wrapper p.collection span", "Tag 3"
end
+
+ test "should let you override the association wrapper" do
+ swap ShowFor, :association_proc => proc { |a, v| "|#{v}|" } do
+ with_association_for @user, :company
+ assert_select "div.show_for p.wrapper", /|PlataformaTec|/
+ end
+ end
+
+ test "should let you override the association wrapper with has_many/has_and_belongs_to_many" do
+ swap ShowFor, :association_proc => proc { |a, v| "|#{v}|" } do
+ with_association_for @user, :tags
+ assert_select "div.show_for p.wrapper ul.collection"
+ assert_select "div.show_for p.wrapper ul.collection li", "|Tag 1|"
+ assert_select "div.show_for p.wrapper ul.collection li", "|Tag 2|"
+ assert_select "div.show_for p.wrapper ul.collection li", "|Tag 3|"
+ end
+ end
end