Reputation:
I have this class:
class User < ActiveRecord::Base
attr_accessor :name, :email, :hr_id
def initialize(attributes = {:name => "Missing Name",:email => "Missing Email",:hr_id => "Missing HR ID"})
@name = attributes[:name]
@email = attributes[:email]
@hr_id = attributes[:hr_id]
end
def print_employee
"Employee No: #{@hr_id} - #{@name} (#{@email})"
end
end
And i use it like this:
def help
employee = User.new
employee.name = "Dude"
employee.email = "[email protected]"
employee.hr_id = "129836561"
@employee = employee.print_employee
end
My question is, how can i make the code in help
shorter and more elegant?
I tried:
employee = User.new('dude','[email protected]','129836561')
@employee = employee.print_employee
But i got errors.
Upvotes: 0
Views: 103
Reputation: 115541
Do this:
class UserBuilder
attr_reader :params
def initialize(params = {})
@params = params
end
def build
User.new(default_params.merge(params))
end
def default_params
{
:name => "Missing Name",
:email => "Missing Email",
:hr_id => "Missing HR ID"
}
end
end
Then:
UserBuilder.new.build
Or:
UserBuilder.new({:name => 'foo'}).build
Upvotes: 1
Reputation: 29599
You are looking for after_initialize
and/or after_find
callbacks. See the docs
after_initialize :set_default_values
private
def set_default_values
self.name ||= 'Missing name'
end
NOTE
As apneadiving has mentioned, this is not the correct way to approach your problem but I think this is the best answer to your question how to make the code more elegant. For best practice, search for service classes like apneadiving's answer and how to use them in your controller to set default values.
Upvotes: 3
Reputation:
So I did a Google search for something like "ActiveRecord default values", and one of the things I found was this Ruby gem that's supposed to set this up for you, so it might be worth checking out: default_value_for.
Example usage from the docs:
class User < ActiveRecord::Base
default_value_for :name, "(no name)"
default_value_for :last_seen do
Time.now
end
end
u = User.new
u.name # => "(no name)"
u.last_seen # => Mon Sep 22 17:28:38 +0200 2008
Upvotes: 0