Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add presenters pattern #19

Merged
merged 4 commits into from Oct 19, 2020
Merged

Add presenters pattern #19

merged 4 commits into from Oct 19, 2020

Conversation

ldlsegovia
Copy link
Member

Presenters

For generating presenters we use:

$ rails generate presenter users_show

This will create the UsersShowPresenter class, inheriting from a base class:

class UsersShowPresenter < PowerTypes::PresenterBase
end

And its corresponding rspec file:

require 'rails_helper'

describe UsersShowPresenter do
  pending "add some examples to (or delete) #{__FILE__}"
end

To initialize a presenter inside your controller action you should execute the present_with method with valid params:

class UsersController < InheritedResources::Base
  def show
    presenter_params = { param1: 1, param2: 2 }
    @presenter = present_with(:users_show, presenter_params)
  end
end

You can access view helper methods through the h method:

class UsersShowPresenter < PowerTypes::PresenterBase
  def platanus_link
    h.link_to "Hi Platanus!", "https://platan.us"
  end
end

You can access presenter_params inside the presenter as an attr_reader

class UsersController < InheritedResources::Base
  def show
    presenter_params = { platanus_url: "https://platan.us" }
    @presenter = present_with(:users_show, presenter_params)
  end
end
class UsersShowPresenter < PowerTypes::PresenterBase
  def platanus_link
    h.link_to "Hi Platanus!", platanus_url
  end
end

If the presenter param has a decorator, the attr_reader will be decorated.

class UsersController < InheritedResources::Base
  def show
    presenter_params = { user: user }
    @presenter = present_with(:users_show, presenter_params)
  end

  private

  def user
    @user ||= User.find!(params[:id])
  end
end
class UserDecorator < Draper::Decorator
  delegate_all

  def cool_view_name
    "~º#{name}º~"
  end
end
class UsersShowPresenter < PowerTypes::PresenterBase
  def platanus_link
    h.link_to "Hi #{user.cool_view_name}!", platanus_url
  end
end

In the view, you can use it like this:

<div><%= @presenter.platanus_link %></div>

@coveralls
Copy link

coveralls commented Oct 16, 2020

Coverage Status

Coverage increased (+0.9%) to 96.899% when pulling 97c476b on presenters into 25b184e on master.

spec/lib/presenter/presentable_spec.rb Outdated Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants