user9703984
user9703984

Reputation:

how to use decorators in rails

I have some problem. i dont understand how to use decorators in my project. May be someone can help me?

personal_information.html.slim

    td.word-break.hidden-value = "*******#{form.dot_application.driver_applicant.ssn.last(4)}"
    td.word-break
      button.show-hidden-info data-field-type="ssn" data-link="#{company_dot_application_show_hidden_informations_path(@dot_application)}"
        | Show SSN

driver_apllicant_decorator.rb

def mask_string(value)
  case value
    when 'ssn'
      "*******#{form.dot_application.driver_applicant.ssn.last(4)}"
    when 'dob'
      "*******#{form.dot_application.driver_applicant.date_of_birth.last(4)}"
    else
      render 403
  end
end

And i dont understand how to use decorator in my views in

td.word-break.hidden-value = "*******# {form.dot_application.driver_applicant.ssn.last(4)}"

How to refactor the code for render "****1234" right with use decorator?

Upvotes: 2

Views: 1772

Answers (1)

Tom Lord
Tom Lord

Reputation: 28285

The idea of a decorator is simply to "extend the model" with presentation methods, for use in views - either by directly calling object, or delegating methods. A decorator does not perform controller actions, like render 403; that is not its job.

For instance, you could write this decorator as:

class DriverApplicantDecorator < Draper::Decorator
  def masked_ssn
    mask_string(object.ssn)
  end

  def masked_date_of_birth
    mask_string(object.date_of_birth)
  end

  private

  def mask_string(value)
    "*******#{value.last(4)}"
  end
end

In your view, you can then simply call these methods - so long as you are referencing the decorated model.

For example, this could be:

td.word-break.hidden-value= form.dot_application.driver_applicant.decorate.masked_ssn

(Or elsewhere, as per the above link, you may not need to explicitly call decorate in the view like that.)

Upvotes: 4

Related Questions