patterns | Dmytro Shteflyuk's Home https://kpumuk.info In my blog I'll try to describe about interesting technologies, my discovery in IT and some useful things about programming. Mon, 07 Sep 2015 23:43:35 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 Simplifying your Ruby on Rails code: Presenter pattern, cells plugin https://kpumuk.info/ruby-on-rails/simplifying-your-ruby-on-rails-code/ https://kpumuk.info/ruby-on-rails/simplifying-your-ruby-on-rails-code/#comments Wed, 09 Sep 2009 05:41:14 +0000 http://kpumuk.info/?p=937 Today we will talk about code organization in Ruby on Rails projects. As everybody knows, Ruby on Rails is a conventional framework, which means you should follow framework architects’ decisions (put your controllers inside app/controllers, move all your logic into models, etc.) But there are many open questions around those conventions. In this write-up I […]

The post Simplifying your Ruby on Rails code: Presenter pattern, cells plugin first appeared on Dmytro Shteflyuk's Home.]]>
Today we will talk about code organization in Ruby on Rails projects. As everybody knows, Ruby on Rails is a conventional framework, which means you should follow framework architects’ decisions (put your controllers inside app/controllers, move all your logic into models, etc.) But there are many open questions around those conventions. In this write-up I will try to summarize my personal experience and show how I usually solve these problems.

Here is the list of questions we will talk about:

  1. You have some logic in your view, which uses your models extensively. There are no places in other views with such logic. The classic recommendation is to move this code into a model, but after a short time your models become bloated with stupid one-off helper methods. The solution: pattern Presenter.

  2. Your constructor contains a lot of code to retrieve some values for your views from the database or another storage. You have a lot of fragment_exist? calls to ensure no of your data is loaded when corresponding fragment is already in cache. It’s really hard to test a particular action because of it’s size. The solution: pattern Presenter.

  3. You have a partial, used everywhere on the site. It accepts a lot of parameters to configure how rendered code should look like. The header of this partial, which initializes default values of parameters, becomes larger and larger. The solution: cells plugin.

Please note: sample application is available on GitHub.

Presenter Pattern

Okay, you have an idea when to use this patterns. Let’s look at the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class HomeController < ApplicationController
  def show
    unless fragment_exist?('home/top_videos')
      @top_videos = Video.top.all(:limit => 10)
    end
   
    unless fragment_exist?('home/categories')
      @categories = Category.all(:order => 'name DESC')
    end
   
    unless fragment_exist?('home/featured_videos')
      @featured_videos = Video.featured.all(:limit => 5)
    end

    unless fragment_exist?('home/latest_videos')
      @latest_videos = Video.latest.all(:limit => 5)
    end
  end
end

And the view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<h1>Home page</h1>

<div id="top_videos">
    <h2>Top videos</h2>
    <% cache('home/top_videos') do %>
        <%= render 'videos', :videos => @top_videos, :hide_description => true %>
    <% end %>
</div>

<div class="tabs">
    <ul id="taxonomy">
        <li><a href="#" id="categories" class="current">Categories</a></li>
    </ul>
    <div class="categories_panel">
        <h2>Categories</h2>
        <% cache('home/categories') do %>
            <%= render 'categories' %>
        <% end %>
    </div>
</div>

<div class="box">
    <div id="latest">
        <h2>Latest videos</h2>
        <% cache('home/latest_videos') do %>
            <%= render 'videos', :videos => @latest_videos, :hide_thumbnail => true %>
        <% end %>
    </div>
    <div id="featured">
        <h2>Featured videos</h2>
        <% cache('home/featured_videos') do %>
            <%= render 'videos', :videos => @featured_videos, :hide_thumbnail => true %>
        <% end %>
    </div>
</div>

Note: this code is available in the first commit of my presenter example project.

Scary code, isn’t it? So let’s refactor it using Presenter pattern. I prefer to put presenters into a separate folder app/presenters, so first we should add it to Rails load path. Add this line to your config/environment.rb:

1
2
3
config.load_paths += %W(
  #{Rails.root}/app/presenters
)

Now we are ready to write our presenter (app/presenters/home_presenters/show_presenter.rb):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module HomePresenters
  class ShowPresenter
    def top_videos
      @top_videos ||= Video.top.all(:limit => 10)
    end

    def categories
      @categories ||= Category.all(:order => 'name DESC')
    end
   
    def featured_videos
      @featured_videos ||= Video.featured.all(:limit => 5)
    end

    def latest_videos
      @latest_videos ||= Video.latest.all(:limit => 5)
    end
  end
end

Sometimes presenters depend on parameters, so feel free to add an initialize method. It could accept particular params or whole params collection:

1
2
3
def initialize(video_id)
  @video_id = video_id
end

Now let’s refactor our controller:

1
2
3
4
5
class HomeController < ApplicationController
  def show
    @presenter = HomePresenters::ShowPresenter.new
  end
end

Whoa, that’s nice! View now is little different:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<h1>Home page</h1>

<div id="top_videos">
    <h2>Top videos</h2>
    <% cache('home/top_videos') do %>
        <%= render 'videos', :videos => @presenter.top_videos, :hide_description => true %>
    <% end %>
</div>

<div class="tabs">
    <ul id="taxonomy">
        <li><a href="#" id="categories" class="current">Categories</a></li>
    </ul>
    <div class="categories_panel">
        <h2>Categories</h2>
        <% cache('home/categories') do %>
            <%= render 'categories' %>
        <% end %>
    </div>
</div>

<div class="box">
    <div id="latest">
        <h2>Latest videos</h2>
        <% cache('home/latest_videos') do %>
            <%= render 'videos', :videos => @presenter.latest_videos, :hide_thumbnail => true %>
        <% end %>
    </div>
    <div id="featured">
        <h2>Featured videos</h2>
        <% cache('home/featured_videos') do %>
            <%= render 'videos', :videos => @presenter.featured_videos, :hide_thumbnail => true %>
        <% end %>
    </div>
</div>

Presenters testing is much easier than testing of bloated controllers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
describe HomePresenters::ShowPresenter do
  before :each do
    @presenter = HomePresenters::ShowPresenter.new
  end
 
  it 'should respond to :top_videos' do
    expect { @presenter.top_videos }.to_not raise_error
  end

  it 'should respond to :categories' do
    expect { @presenter.categories }.to_not raise_error
  end

  it 'should respond to :featured_videos' do
    expect { @presenter.featured_videos }.to_not raise_error
  end

  it 'should respond to :latest_videos' do
    expect { @presenter.latest_videos }.to_not raise_error
  end
end

Please note: this code is available in the second commit of my presenter example project.

Please note: you should not do any manipulations on models in presenters. They only decorate models with helper methods to be used inside controllers or views, nothing else. There are several articles describing a Conductor pattern as a presenter, do not repeat their mistakes. See the first link in the list below to get an idea about the differences.

Related links:

Cells Plugin

Okay, now we have a clean controller. But what about views? Let’s take a look at the videos partial:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<%
 hide_thumbnail   = hide_thumbnail === true;
 hide_description = hide_description === true;
 css_class      ||= 'videos'
 style          ||= :div
 case style.to_sym
   when :section
     parent_tag = 'section'
     child_tag = 'div'
   when :list
     parent_tag = 'ul'
     child_tag = 'li'
   else
     parent_tag = 'div'
     child_tag = 'div'
 end
%>

<% content_tag parent_tag, :class => css_class do %>
  <% videos.each do |video| %>
    <% content_tag child_tag do %>
      <h3><%= h video.title %></h3>
      <%= image_tag(video.thumbnail_url, :class => 'thumb') unless hide_thumbnail %>
      <%= '<p>%s</p>' % h(video.description) unless hide_description %>
    <% end %>
  <% end %>
<% end %>

So, what the heck? Is this a view or a controller? Remember old PHP days, with all this spaghetti code? That is it. It’s hard to test, it looks scary, it bad. So here cells plugin comes to the stage.

First, we need to install the plugin:

1
script/plugin install git://github.com/apotonick/cells.git

Now let’s generate a cell:

1
script/generate cell Video videos

And write some code (app/cells/video.rb):

1
2
3
4
5
6
7
8
9
10
11
12
13
class VideoCell < Cell::Base
  def videos
    @videos = @opts[:videos]
    @hide_thumbnail = @opts[:hide_thumbnail] === true;
    @hide_description = @opts[:hide_description] === true;
    @css_class = @opts[:css_class] || 'videos'
   
    view = (@opts[:style] || :div).to_sym
    view = :div unless [:section, :list].include?(view)

    render :view => "videos_#{view}"
  end
end

app/cells/video/videos_section.html.erb:

1
2
3
4
5
6
7
<section class="<%= @css_class %>">
  <% @videos.each do |video| %>
    <div>
      <%= render :partial => 'video', :locals => { :video => video } %>
    </div>
  <% end %>
</section>

app/cells/video/videos_list.html.erb:

1
2
3
4
5
6
7
<ul class="<%= @css_class %>">
  <% @videos.each do |video| %>
    <li>
      <%= render :partial => 'video', :locals => { :video => video } %>
    </li>
  <% end %>
</ul>

app/cells/video/videos_div.html.erb:

1
2
3
4
5
6
7
<div class="<%= @css_class %>">
  <% @videos.each do |video| %>
    <div>
      <%= render :partial => 'video', :locals => { :video => video } %>
    </div>
  <% end %>
</div>

app/cells/video/_video.html.erb:

1
2
3
<h3><%= h video.title %></h3>
<%= image_tag(video.thumbnail_url, :class => 'thumb') unless @hide_thumbnail %>
<%= '<p>%s</p>' % h(video.description) unless @hide_description %>

And the view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<h1>Home page</h1>

<div id="top_videos">
    <h2>Top videos</h2>
    <% cache('home/top_videos') do %>
        <%= render_cell :video, :videos, :videos => @presenter.top_videos, :hide_description => true %>
    <% end %>
</div>

<div class="tabs">
    <ul id="taxonomy">
        <li><a href="#" id="categories" class="current">Categories</a></li>
    </ul>
    <div class="categories_panel">
        <h2>Categories</h2>
        <% cache('home/categories') do %>
            <%= render 'categories' %>
        <% end %>
    </div>
</div>

<div class="box">
    <div id="latest">
        <h2>Latest videos</h2>
        <% cache('home/latest_videos') do %>
            <%= render_cell :video, :videos, :videos => @presenter.latest_videos, :hide_thumbnail => true %>
        <% end %>
    </div>
    <div id="featured">
        <h2>Featured videos</h2>
        <% cache('home/featured_videos') do %>
            <%= render_cell :video, :videos, :videos => @presenter.featured_videos, :hide_thumbnail => true %>
        <% end %>
    </div>
</div>

Wow! That’s pretty easy to read and modify. All the logic is in the code now, all the views are easy to read, and moreover: it’s more than easy to test now! I have a little plugin called rspec-cells, and I have committed a patch yesterday to get it working with the latest RSpec. Here is how you spec could look like:

1
2
3
4
5
6
7
8
9
describe VideoCell do
  context '.videos' do
    it 'should initialize :videos variable' do
      videos = mock('Videos')
      render_cell :videos, :videos => videos
      assigns[:videos].should be(videos)
    end
  end
end

So it looks almost like a classic Ruby on Rails controller spec. I hope to review the code in nearest feature and will send a pull request to the cells plugin author. Of course, if you
found a bug, feel free to contact me.

Please note: this code is available in the third commit of my presenter example project.

Related links:

That’s all I wanted to show you today. I think a Presenter Example project will be updated periodically, so follow it on GitHub, follow me in Twitter or on GitHub to get instant updates. Also take a look at the rspec-cells plugin, maybe you will have some time to make it better.

The post Simplifying your Ruby on Rails code: Presenter pattern, cells plugin first appeared on Dmytro Shteflyuk's Home.]]>
https://kpumuk.info/ruby-on-rails/simplifying-your-ruby-on-rails-code/feed/ 25
Exploring Zend_Controller class of Zend Framework https://kpumuk.info/php/exploring-zend_controller-class-of-zend-framework/ https://kpumuk.info/php/exploring-zend_controller-class-of-zend-framework/#comments Thu, 27 Apr 2006 22:19:56 +0000 http://kpumuk.info/php/exploring-zend_controller-class-of-zend-framework/ Zend Framework team works with gusto on the Zend Framework, great framework for building powerful web-applications in PHP. But too many peoples are confused with its seeming complexity. In this post I will try to explain architecture of most useful part (in my opinion) of Zend Framework – Zend_Controller. For a start, let’s look at […]

The post Exploring Zend_Controller class of Zend Framework first appeared on Dmytro Shteflyuk's Home.]]>
Zend Framework team works with gusto on the Zend Framework, great framework for building powerful web-applications in PHP. But too many peoples are confused with its seeming complexity. In this post I will try to explain architecture of most useful part (in my opinion) of Zend Framework – Zend_Controller.

For a start, let’s look at the following diagram.

Zend_Controller workflow

On this picture you can see workflow of the program based on the Zend Framework. Let’s examine what happens when user requested page.

  1. Script runs Zend_Controller_Front.
  2. Router object will be called to build Zend_Controller_Dispatcher_Token object which contains information about controller, action and params. Before starting routing process routeStartup() method of plugins will be executed to notify plugins that the router is starting up. routeShutdown() method of plugins will be called to notify plugins that the router is shutting down. It’s possible to replace Zend_Controller_Dispatcher_Token returned by router here.
  3. dispatchLoopStartup() method of plugins will be called to notify plugins that the dispatch loop is starting up.
  4. Dispatch loop will be started. Zend_Controller_Dispatcher is repeatedly called until all actions have been dispatched sequentially. This means that you can build chain of actions for execution several operations (for example, authenticate user and forward flow to user’s private area on the server without round-trip.) Before each iteration preDispatch() and after each one postDispatch() methods of plugins will be called to notify plugins that a dispatch iteration occurs.
  5. On each dispatch iteration Zend_Controller_Dispatcher will instantiate Zend_Controller_Action object and will call it’s method run().
  6. Zend_Controller_Action object will call method corresponding to action in Zend_Controller_Dispatcher_Token object. In this class you can use protected method _forward() to set next action to execute without round-trip (in this case dispatch iteration will be repeated again for new action).
  7. dispatchLoopShutdown() method of plugins will be called to notify plugins that the dispatch loop is shutting down.

All notifications to plugins are executed through Zend_Controller_Plugin_Broker which maintains plugins list. This class just forwards all notifications to all plugins in the list.

For example, let’s imagine that user requested following URL: http://somehost.com/products/save/id/10. After saving product with id=10 in database, it’s necessary to show message like “Product has been saved in the database”. Message box is implemented in MessagesController‘s method named showMessageAction(). In this case workflow will be like following:

  1. Script runs Zend_Controller_Front.
  2. Router object will parse requested URL and will extract following information:
    • controllerproducts
    • actionsave
    • paramsid = 10

    Based on this data it will construct Zend_Controller_Dispatcher_Token.

  3. Dispatch loop will be started. Zend_Controller_Dispatcher‘s dispatch() method will be called for Zend_Controller_Dispatcher_Token constructed on previous step.
  4. Dispatcher will instantiate ProductsController object and call it’s run() method. This method will call own method saveAction().
  5. saveAction() method will save product in database. Then it will call method _forward() in following way: $this->forward("messages", "showMessage", array("msg" => "Product has been saved in the database"));.
  6. Dispatch loop isn’t finished because flow was forwarded to another action. Zend_Controller_Dispatcher will be called again with new action.
  7. showMessageAction does not need to forward to another action, therefor workflow will be finished.

To get more detailed information refer to the official manual.

The post Exploring Zend_Controller class of Zend Framework first appeared on Dmytro Shteflyuk's Home.]]>
https://kpumuk.info/php/exploring-zend_controller-class-of-zend-framework/feed/ 12