From 99ac02ba073068a90368a6c9c936c7dfe8a70a08 Mon Sep 17 00:00:00 2001 From: Tom Kadwill Date: Thu, 4 Jun 2015 16:59:59 +0100 Subject: [PATCH] Fix view rendering so layout methods can be called --- lib/lotus/view/rendering/layout_scope.rb | 8 ++++++-- lib/lotus/view/rendering/scope.rb | 11 ++++++++++- test/fixtures.rb | 4 ++++ .../templates/store/templates/home/index.html.erb | 1 + test/layout_test.rb | 5 +++++ 5 files changed, 26 insertions(+), 3 deletions(-) diff --git a/lib/lotus/view/rendering/layout_scope.rb b/lib/lotus/view/rendering/layout_scope.rb index bc25cd44..e801740a 100644 --- a/lib/lotus/view/rendering/layout_scope.rb +++ b/lib/lotus/view/rendering/layout_scope.rb @@ -203,8 +203,8 @@ def respond_to_missing?(m, include_all) def method_missing(m, *args, &blk) if @scope.respond_to?(m) @scope.__send__(m, *args, &blk) - elsif @layout.respond_to?(m) - @layout.__send__(m, *args, &blk) + elsif layout.respond_to?(m) + layout.__send__(m, *args, &blk) else super end @@ -228,6 +228,10 @@ def _options(options) opts[:locals].merge!(options.fetch(:locals){ ::Hash.new }) end end + + def layout + @layout || @layout.class.layout.new(@scope, "") + end end end end diff --git a/lib/lotus/view/rendering/scope.rb b/lib/lotus/view/rendering/scope.rb index 42afe457..449fa00d 100644 --- a/lib/lotus/view/rendering/scope.rb +++ b/lib/lotus/view/rendering/scope.rb @@ -21,7 +21,7 @@ class Scope < LayoutScope # @api private # @since 0.1.0 def initialize(view, locals = {}) - @view, @locals = view, locals + @view, @locals, @layout = view, locals, layout end # Returns an inspect String @@ -70,6 +70,15 @@ def method_missing(m, *args, &block) end ) end + + private + def layout + if @view.class.respond_to?(:layout) + @view.class.layout.new(self, "") + else + nil + end + end end end end diff --git a/test/fixtures.rb b/test/fixtures.rb index 232bf0b0..45cf3a36 100644 --- a/test/fixtures.rb +++ b/test/fixtures.rb @@ -326,6 +326,10 @@ class StoreLayout def head %() end + + def user_name + "Joe Blogs" + end end module Home diff --git a/test/fixtures/templates/store/templates/home/index.html.erb b/test/fixtures/templates/store/templates/home/index.html.erb index 72e7760d..2212f6e4 100644 --- a/test/fixtures/templates/store/templates/home/index.html.erb +++ b/test/fixtures/templates/store/templates/home/index.html.erb @@ -1 +1,2 @@ +<%= user_name %> yeah diff --git a/test/layout_test.rb b/test/layout_test.rb index cf6c3096..0f9ad9bb 100644 --- a/test/layout_test.rb +++ b/test/layout_test.rb @@ -27,6 +27,11 @@ class MissingLayout rendered.must_match %(yeah) end + it 'methods defined in layout are available from the view' do + rendered = Store::Views::Home::Index.render(format: :html) + rendered.must_match %(Joe Blogs) + end + it 'renders content to return value from view' do rendered = Store::Views::Products::Show.render(format: :html) rendered.must_match %(Product)