Skip to content
Browse files

You can now pass values from outside to the render method (e.g. `#to_…

…json`), they will be available as block parameters inside `#link`.
  • Loading branch information...
1 parent 993e6f8 commit 46fb88d1a79338188a9d05d353fc721d6a058e4e @apotonick committed May 18, 2012
Showing with 28 additions and 5 deletions.
  1. +4 −0 CHANGES.markdown
  2. +14 −5 lib/roar/representer/feature/hypermedia.rb
  3. +10 −0 test/hypermedia_feature_test.rb
View
4 CHANGES.markdown
@@ -1,3 +1,7 @@
+## 0.10.2
+
+* You can now pass values from outside to the render method (e.g. `#to_json`), they will be available as block parameters inside `#link`.
+
## 0.10.1
* Adding the Coercion feature.
View
19 lib/roar/representer/feature/hypermedia.rb
@@ -19,13 +19,22 @@ module Feature
# link :rel => :next, :title => "Next, please!" do
# "http://orders/#{id}"
# end
+ #
+ # Sometimes you need values from outside when the representation links are rendered. Just pass them
+ # to the render method, they will be available as block parameters.
+ #
+ # link :self do |opts|
+ # "http://orders/#{opts[:id]}"
+ # end
+ #
+ # model.to_json(:id => 1)
module Hypermedia
def self.included(base)
base.extend ClassMethods
end
def before_serialize(options={})
- prepare_links! unless options[:links] == false # DISCUSS: doesn't work when links are already setup (e.g. from #deserialize).
+ prepare_links!(options) unless options[:links] == false # DISCUSS: doesn't work when links are already setup (e.g. from #deserialize).
super # Representer::Base
end
@@ -39,19 +48,19 @@ def links
protected
# Setup hypermedia links by invoking their blocks. Usually called by #serialize.
- def prepare_links!
+ def prepare_links!(*args)
links_def = find_links_definition or return
links_def.rel2block.each do |config| # config is [{..}, block]
options = config.first
- options[:href] = run_link_block(config.last) or next
+ options[:href] = run_link_block(config.last, *args) or next
links.update_link(Feature::Hypermedia::Hyperlink.new(options))
end
end
- def run_link_block(block)
- instance_exec(&block)
+ def run_link_block(block, *args)
+ instance_exec(*args, &block)
end
def find_links_definition
View
10 test/hypermedia_feature_test.rb
@@ -31,6 +31,16 @@ class HypermediaTest
assert_equal "{\"links\":[{\"rel\":\"self\",\"href\":\"http://self\",\"title\":\"Hey, @myabc\"}]}", Object.new.extend(@mod).to_json
end
+
+ it "receives options from to_*" do
+ @mod.class_eval do
+ link :self do |opts|
+ "http://self/#{opts[:id]}"
+ end
+ end
+
+ assert_equal "{\"links\":[{\"rel\":\"self\",\"href\":\"http://self/1\"}]}", Object.new.extend(@mod).to_json(:id => 1)
+ end
end

1 comment on commit 46fb88d

@myabc
myabc commented on 46fb88d May 21, 2012

nice!

Please sign in to comment.
Something went wrong with that request. Please try again.