Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails delegate with a different name

Hi there I am using the Form Object refactor pattern. I have two models, Project and User. such that

Project.first.name # "Buy milk"
User.first.name # "John Doe"

I have a form that accepts the NAME of a project, and the NAME of the user.

class UserForm
  include ActiveModel::Model

   def initialize(name:'', project_name:'')
    @name = name
    @project_name = project_name
   end

  def persisted?
    false
  end

  def self.model_name
    ActiveModel::Name.new(self, nil, "ProjectForm")
  end

  delegate :name, :email, to: :user
  delegate :project_name, to: :project # PROBLEM: project has #name not #project_name method

  def user
    @user ||= User.new
  end

  def project
    @project ||= Project.new
  end

end

The main problem lies in the initialize and the delegate part of the code, since both Project and User has a field name, and so I can't have @name for both in the initialize. Is there a way to do something like

delegate name: :project_name?

Thank you!

like image 588
Nik So Avatar asked Aug 09 '16 16:08

Nik So


2 Answers

Delegate allows you to specify prefix for the delegated field.

delegate :name, to: :project, prefix: true

It will allow to access it as project_name.

Alternatively it's possible to specify your own prefix for it:

delegate :name, to: :project, prefix: :my_project

It will allow to access it as my_project_name.

http://apidock.com/rails/Module/delegate

like image 135
SunnyMagadan Avatar answered Oct 16 '22 19:10

SunnyMagadan


You can use prefix

class UserForm
  include ActiveModel::Model

   def initialize(name:'', project_name:'')
    @name = name
    @project_name = project_name
   end

  def persisted?
    false
  end

  def self.model_name
    ActiveModel::Name.new(self, nil, "ProjectForm")
  end

  delegate :name, :email, to: :user, prefix: true
  delegate :name, to: :project, prefix: true

  def user
    @user ||= User.new
  end

  def project
    @project ||= Project.new
  end

end

More informations : http://apidock.com/rails/Module/delegate

Now, you can call the prefixed methods like this:

UserForm.new.user_name
UserForm.new.project_name
like image 21
Gearnode Avatar answered Oct 16 '22 19:10

Gearnode