Nik So Nik So - 4 months ago 35
Ruby Question

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!

Answer

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